Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 42c1b65632 | |||
| de7bd34aa8 | |||
| 68a4b7f984 | |||
| e5fe8b903a | |||
| c6b01def4c | |||
| 63fcf33416 |
@@ -18,6 +18,7 @@
|
|||||||
"echarts": "^6.1.0",
|
"echarts": "^6.1.0",
|
||||||
"echarts-for-react": "^3.0.6",
|
"echarts-for-react": "^3.0.6",
|
||||||
"element-china-area-data": "^6.1.0",
|
"element-china-area-data": "^6.1.0",
|
||||||
|
"jspdf": "^4.2.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-router-dom": "^6.26.0"
|
"react-router-dom": "^6.26.0"
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ import SystemSettingsPage from './pages/SystemSettingsPage';
|
|||||||
import TestWhitelistPage from './pages/TestWhitelistPage';
|
import TestWhitelistPage from './pages/TestWhitelistPage';
|
||||||
import WecomBotsPage from './pages/WecomBotsPage';
|
import WecomBotsPage from './pages/WecomBotsPage';
|
||||||
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
||||||
|
import WecomReportsPage from './pages/WecomReportsPage';
|
||||||
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
||||||
import LlmConfigsPage from './pages/LlmConfigsPage';
|
import LlmConfigsPage from './pages/LlmConfigsPage';
|
||||||
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
||||||
@@ -95,6 +96,7 @@ export default function App() {
|
|||||||
<Route path="/wecom-bots" element={<Navigate to="/wecom/bots" replace />} />
|
<Route path="/wecom-bots" element={<Navigate to="/wecom/bots" replace />} />
|
||||||
<Route path="/wecom/bots" element={<WecomBotsPage />} />
|
<Route path="/wecom/bots" element={<WecomBotsPage />} />
|
||||||
<Route path="/wecom/pushes" element={<WecomMessagePushesPage />} />
|
<Route path="/wecom/pushes" element={<WecomMessagePushesPage />} />
|
||||||
|
<Route path="/wecom/reports" element={<WecomReportsPage />} />
|
||||||
<Route path="/logs/wecom-bots" element={<WecomBotLogsPage />} />
|
<Route path="/logs/wecom-bots" element={<WecomBotLogsPage />} />
|
||||||
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
||||||
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
Descriptions,
|
Descriptions,
|
||||||
Drawer,
|
Drawer,
|
||||||
@@ -140,6 +141,14 @@ export default function OrderTrackDrawer({
|
|||||||
</Space>
|
</Space>
|
||||||
</Image.PreviewGroup>
|
</Image.PreviewGroup>
|
||||||
</div>
|
</div>
|
||||||
|
) : nodes.some((n) => n.statusName?.includes('签收') || n.trackInfo?.includes('签收')) ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
message="暂无签收照片"
|
||||||
|
description="小飞侠 100108 未返回图片(可能是本人签收未拍照,或照片已过期)。可在「小飞侠联调」用运单号复测。"
|
||||||
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Typography.Title level={5} style={{ marginTop: 0 }}>
|
<Typography.Title level={5} style={{ marginTop: 0 }}>
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
children: [
|
children: [
|
||||||
{ key: '/wecom/bots', label: '智能机器人' },
|
{ key: '/wecom/bots', label: '智能机器人' },
|
||||||
{ key: '/wecom/pushes', label: '消息推送' },
|
{ key: '/wecom/pushes', label: '消息推送' },
|
||||||
|
{ key: '/wecom/reports', label: '报告' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
||||||
@@ -186,6 +187,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/activity-posters': 'activity_posters',
|
'/activity-posters': 'activity_posters',
|
||||||
'/wecom/bots': 'wecom_bots',
|
'/wecom/bots': 'wecom_bots',
|
||||||
'/wecom/pushes': 'wecom_bots',
|
'/wecom/pushes': 'wecom_bots',
|
||||||
|
'/wecom/reports': 'wecom_bots',
|
||||||
'wecom-group': 'wecom_bots',
|
'wecom-group': 'wecom_bots',
|
||||||
'/llm-configs': 'llm_configs',
|
'/llm-configs': 'llm_configs',
|
||||||
'/knowledge-bases': 'knowledge_bases',
|
'/knowledge-bases': 'knowledge_bases',
|
||||||
|
|||||||
@@ -147,50 +147,12 @@ export type DashboardStats = {
|
|||||||
ordersByStatus: Array<{ status: string; count: number }>;
|
ordersByStatus: Array<{ status: string; count: number }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type DashboardAnalytics = {
|
export type {
|
||||||
summary: {
|
DashboardAnalytics,
|
||||||
users: number;
|
DashboardGranularity,
|
||||||
orders: number;
|
DashboardLineChart,
|
||||||
payingUsers: number;
|
DashboardLineHref,
|
||||||
partners: number;
|
} from '@dukang/shared-types';
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
};
|
|
||||||
byDate: Array<{
|
|
||||||
date: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
partners: number;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
}>;
|
|
||||||
byCity: Array<{
|
|
||||||
cityId: string;
|
|
||||||
cityName: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
partners: number;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
}>;
|
|
||||||
byPromo: Array<{
|
|
||||||
promoCodeId: string | null;
|
|
||||||
code: string;
|
|
||||||
name: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
}>;
|
|
||||||
byPartner: Array<{
|
|
||||||
partnerAccountId: string;
|
|
||||||
companyName: string;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type SystemVersion = {
|
export type SystemVersion = {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import type { ECharts } from 'echarts';
|
||||||
|
|
||||||
|
const TITLE_FONT = 'bold 32px "Microsoft YaHei","PingFang SC","Noto Sans SC",sans-serif';
|
||||||
|
const SUB_FONT = '22px "Microsoft YaHei","PingFang SC","Noto Sans SC",sans-serif';
|
||||||
|
|
||||||
|
type ChartShot = {
|
||||||
|
title: string;
|
||||||
|
instance: ECharts | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
function loadImage(src: string): Promise<HTMLImageElement> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => resolve(img);
|
||||||
|
img.onerror = () => reject(new Error('图表截图失败'));
|
||||||
|
img.src = src;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function composePage(params: {
|
||||||
|
chartPng: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
}): Promise<{ dataUrl: string; width: number; height: number }> {
|
||||||
|
const img = await loadImage(params.chartPng);
|
||||||
|
const header = 96;
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = img.width;
|
||||||
|
canvas.height = img.height + header;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) throw new Error('无法生成 PDF 画布');
|
||||||
|
ctx.fillStyle = '#ffffff';
|
||||||
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
ctx.textBaseline = 'top';
|
||||||
|
ctx.fillStyle = '#1f1f1f';
|
||||||
|
ctx.font = TITLE_FONT;
|
||||||
|
ctx.fillText(params.title, 24, 16, canvas.width - 48);
|
||||||
|
ctx.fillStyle = '#8c8c8c';
|
||||||
|
ctx.font = SUB_FONT;
|
||||||
|
ctx.fillText(params.subtitle, 24, 56, canvas.width - 48);
|
||||||
|
ctx.drawImage(img, 0, header);
|
||||||
|
return {
|
||||||
|
dataUrl: canvas.toDataURL('image/jpeg', 0.92),
|
||||||
|
width: canvas.width,
|
||||||
|
height: canvas.height,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把当前已渲染折线图打成横向 A4 PDF(不含 KPI / 待办)。 */
|
||||||
|
export async function downloadDashboardChartsPdf(params: {
|
||||||
|
filename: string;
|
||||||
|
subtitle: string;
|
||||||
|
charts: ChartShot[];
|
||||||
|
}): Promise<void> {
|
||||||
|
const ready = params.charts.filter((c): c is { title: string; instance: ECharts } => !!c.instance);
|
||||||
|
if (ready.length === 0) {
|
||||||
|
throw new Error('暂无可下载的图');
|
||||||
|
}
|
||||||
|
if (ready.length !== params.charts.length) {
|
||||||
|
throw new Error('图表尚未渲染完成,请稍后再试');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { jsPDF } = await import('jspdf');
|
||||||
|
const pdf = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
|
||||||
|
const pageW = pdf.internal.pageSize.getWidth();
|
||||||
|
const pageH = pdf.internal.pageSize.getHeight();
|
||||||
|
const margin = 10;
|
||||||
|
|
||||||
|
for (let i = 0; i < ready.length; i += 1) {
|
||||||
|
const chart = ready[i];
|
||||||
|
const png = chart.instance.getDataURL({
|
||||||
|
type: 'png',
|
||||||
|
pixelRatio: 2,
|
||||||
|
backgroundColor: '#ffffff',
|
||||||
|
});
|
||||||
|
const page = await composePage({
|
||||||
|
chartPng: png,
|
||||||
|
title: chart.title,
|
||||||
|
subtitle: params.subtitle,
|
||||||
|
});
|
||||||
|
const maxW = pageW - margin * 2;
|
||||||
|
const maxH = pageH - margin * 2;
|
||||||
|
const ratio = Math.min(maxW / page.width, maxH / page.height);
|
||||||
|
const w = page.width * ratio;
|
||||||
|
const h = page.height * ratio;
|
||||||
|
const x = (pageW - w) / 2;
|
||||||
|
const y = margin + (maxH - h) / 2;
|
||||||
|
if (i > 0) pdf.addPage();
|
||||||
|
pdf.addImage(page.dataUrl, 'JPEG', x, y, w, h);
|
||||||
|
}
|
||||||
|
|
||||||
|
const filename = params.filename.endsWith('.pdf') ? params.filename : `${params.filename}.pdf`;
|
||||||
|
pdf.save(filename);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import { Link, useNavigate } from 'react-router-dom';
|
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
@@ -129,12 +129,18 @@ function formatApiError(err: unknown): string | null {
|
|||||||
|
|
||||||
export default function CityPartnersPage() {
|
export default function CityPartnersPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const initialCityId = searchParams.get('cityId')?.trim() || '';
|
||||||
const [filterForm] = Form.useForm();
|
const [filterForm] = Form.useForm();
|
||||||
const [editForm] = Form.useForm();
|
const [editForm] = Form.useForm();
|
||||||
const [createForm] = Form.useForm();
|
const [createForm] = Form.useForm();
|
||||||
const [subForm] = Form.useForm();
|
const [subForm] = Form.useForm();
|
||||||
const [subEditForm] = Form.useForm();
|
const [subEditForm] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string | boolean>>({});
|
const [filters, setFilters] = useState<Record<string, string | boolean>>(() => {
|
||||||
|
const init: Record<string, string | boolean> = {};
|
||||||
|
if (initialCityId) init.cityId = initialCityId;
|
||||||
|
return init;
|
||||||
|
});
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||||
'/admin/partners',
|
'/admin/partners',
|
||||||
() => {
|
() => {
|
||||||
@@ -484,6 +490,7 @@ export default function CityPartnersPage() {
|
|||||||
form={filterForm}
|
form={filterForm}
|
||||||
layout="inline"
|
layout="inline"
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
|
initialValues={initialCityId ? { cityId: initialCityId } : undefined}
|
||||||
onFinish={(v) => {
|
onFinish={(v) => {
|
||||||
setFilters(v);
|
setFilters(v);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
|
|||||||
@@ -1,12 +1,23 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button, Card, Col, DatePicker, Descriptions, Form, Modal, Row, Select, Space, Statistic, Table, Typography, message,
|
Button, Card, Col, DatePicker, Descriptions, Form, Modal, Row, Segmented, Select, Space, Statistic, Table, Typography, message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import { CloudUploadOutlined, ReloadOutlined } from '@ant-design/icons';
|
import { CloudUploadOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||||
import dayjs, { type Dayjs } from 'dayjs';
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
import ReactECharts from 'echarts-for-react';
|
import ReactECharts from 'echarts-for-react';
|
||||||
import type { EChartsOption } from 'echarts';
|
import { getInstanceByDom, type EChartsOption } from 'echarts';
|
||||||
|
import {
|
||||||
|
addShanghaiDays,
|
||||||
|
defaultShanghaiRangeYmds,
|
||||||
|
shanghaiMonthRange,
|
||||||
|
shanghaiQuarterIndex,
|
||||||
|
shanghaiQuarterRange,
|
||||||
|
shanghaiWeekRange,
|
||||||
|
shanghaiYearMonth,
|
||||||
|
shanghaiYmd,
|
||||||
|
} from '@dukang/domain';
|
||||||
|
import type { DashboardGranularity, DashboardLineChart, DashboardLineHref } from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
request,
|
request,
|
||||||
type DashboardAnalytics,
|
type DashboardAnalytics,
|
||||||
@@ -17,6 +28,7 @@ import {
|
|||||||
type SystemVersion,
|
type SystemVersion,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||||
|
import { downloadDashboardChartsPdf } from '../lib/dashboard-charts-pdf';
|
||||||
|
|
||||||
const STATUS_LABELS: Record<string, string> = {
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
PENDING_PAY: '待付款',
|
PENDING_PAY: '待付款',
|
||||||
@@ -36,26 +48,121 @@ const DEPLOYED_BY_LABELS: Record<string, string> = {
|
|||||||
admin: 'Admin 发布',
|
admin: 'Admin 发布',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const GRAIN_OPTIONS: Array<{ label: string; value: DashboardGranularity }> = [
|
||||||
|
{ label: '日', value: 'day' },
|
||||||
|
{ label: '周', value: 'week' },
|
||||||
|
{ label: '月', value: 'month' },
|
||||||
|
{ label: '季', value: 'quarter' },
|
||||||
|
{ label: '年', value: 'year' },
|
||||||
|
];
|
||||||
|
|
||||||
|
type ChartMetric = 'total' | 'increment';
|
||||||
|
|
||||||
|
const METRIC_OPTIONS: Array<{ label: string; value: ChartMetric }> = [
|
||||||
|
{ label: '总量', value: 'total' },
|
||||||
|
{ label: '增量', value: 'increment' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function toDayjsRange(from: Date, toInclusive: Date): [Dayjs, Dayjs] {
|
||||||
|
return [dayjs(shanghaiYmd(from)), dayjs(shanghaiYmd(toInclusive))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 完整上一自然周 / 上月 / 上季(北京日历) */
|
||||||
|
function datePresetRange(kind: 'lastWeek' | 'lastMonth' | 'lastQuarter'): [Dayjs, Dayjs] {
|
||||||
|
const today = new Date();
|
||||||
|
if (kind === 'lastWeek') {
|
||||||
|
const thisMonday = shanghaiWeekRange(today).start;
|
||||||
|
return toDayjsRange(addShanghaiDays(thisMonday, -7), addShanghaiDays(thisMonday, -1));
|
||||||
|
}
|
||||||
|
if (kind === 'lastMonth') {
|
||||||
|
const { year, month } = shanghaiYearMonth(today);
|
||||||
|
const prev = month === 1 ? { year: year - 1, month: 12 } : { year, month: month - 1 };
|
||||||
|
const r = shanghaiMonthRange(prev.year, prev.month);
|
||||||
|
return toDayjsRange(r.start, addShanghaiDays(r.endExclusive, -1));
|
||||||
|
}
|
||||||
|
const { year, quarter } = shanghaiQuarterIndex(today);
|
||||||
|
const prev = quarter === 1 ? { year: year - 1, quarter: 4 } : { year, quarter: quarter - 1 };
|
||||||
|
const r = shanghaiQuarterRange(prev.year, prev.quarter);
|
||||||
|
return toDayjsRange(r.start, addShanghaiDays(r.endExclusive, -1));
|
||||||
|
}
|
||||||
|
|
||||||
|
const DATE_PRESETS: Array<{ key: 'lastWeek' | 'lastMonth' | 'lastQuarter'; label: string }> = [
|
||||||
|
{ key: 'lastWeek', label: '上周' },
|
||||||
|
{ key: 'lastMonth', label: '上月' },
|
||||||
|
{ key: 'lastQuarter', label: '上季度' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function chartIsMetric(key: string, metric: ChartMetric): boolean {
|
||||||
|
const isInc = key.includes('.increment');
|
||||||
|
return metric === 'increment' ? isInc : !isInc;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HREF_PATH: Record<DashboardLineHref, string> = {
|
||||||
|
users: '/users',
|
||||||
|
partners: '/city-partners',
|
||||||
|
stores: '/stores',
|
||||||
|
orders: '/orders',
|
||||||
|
redeems: '/redeem-records',
|
||||||
|
};
|
||||||
|
|
||||||
type CityOption = { id: string; name: string; code: string };
|
type CityOption = { id: string; name: string; code: string };
|
||||||
type PromoOption = { id: string; code: string; name: string };
|
|
||||||
|
|
||||||
type AnalyticsFilters = {
|
type AnalyticsFilters = {
|
||||||
|
granularity: DashboardGranularity;
|
||||||
range: [Dayjs, Dayjs];
|
range: [Dayjs, Dayjs];
|
||||||
cityId?: string;
|
cityId?: string;
|
||||||
promoCodeId?: string;
|
|
||||||
partnerAccountId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function defaultRange(grain: DashboardGranularity): [Dayjs, Dayjs] {
|
||||||
|
const y = defaultShanghaiRangeYmds(grain);
|
||||||
|
return [dayjs(y.from), dayjs(y.to)];
|
||||||
|
}
|
||||||
|
|
||||||
function buildAnalyticsQs(f: AnalyticsFilters) {
|
function buildAnalyticsQs(f: AnalyticsFilters) {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('granularity', f.granularity);
|
||||||
qs.set('dateFrom', f.range[0].format('YYYY-MM-DD'));
|
qs.set('dateFrom', f.range[0].format('YYYY-MM-DD'));
|
||||||
qs.set('dateTo', f.range[1].format('YYYY-MM-DD'));
|
qs.set('dateTo', f.range[1].format('YYYY-MM-DD'));
|
||||||
if (f.cityId) qs.set('cityId', f.cityId);
|
if (f.cityId) qs.set('cityId', f.cityId);
|
||||||
if (f.promoCodeId) qs.set('promoCodeId', f.promoCodeId);
|
|
||||||
if (f.partnerAccountId) qs.set('partnerAccountId', f.partnerAccountId);
|
|
||||||
return qs.toString();
|
return qs.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function listHref(kind: DashboardLineHref, f: AnalyticsFilters): string {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('createdFrom', f.range[0].format('YYYY-MM-DD'));
|
||||||
|
qs.set('createdTo', f.range[1].format('YYYY-MM-DD'));
|
||||||
|
if (f.cityId && f.cityId !== 'none') qs.set('cityId', f.cityId);
|
||||||
|
const s = qs.toString();
|
||||||
|
return s ? `${HREF_PATH[kind]}?${s}` : HREF_PATH[kind];
|
||||||
|
}
|
||||||
|
|
||||||
|
function lineOption(
|
||||||
|
periods: Array<{ key: string; label: string }>,
|
||||||
|
chart: DashboardLineChart,
|
||||||
|
): EChartsOption {
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { type: 'scroll', top: 0 },
|
||||||
|
grid: { left: 56, right: 28, top: 48, bottom: periods.length > 14 ? 64 : 36 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: periods.map((p) => p.label),
|
||||||
|
axisLabel: { rotate: periods.length > 14 ? 45 : 0 },
|
||||||
|
},
|
||||||
|
yAxis: {
|
||||||
|
type: 'value',
|
||||||
|
minInterval: chart.unit === 'count' ? 1 : undefined,
|
||||||
|
},
|
||||||
|
series: chart.series.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
type: 'line' as const,
|
||||||
|
smooth: true,
|
||||||
|
showSymbol: periods.length <= 24,
|
||||||
|
data: s.values,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||||
const [version, setVersion] = useState<SystemVersion | null>(null);
|
const [version, setVersion] = useState<SystemVersion | null>(null);
|
||||||
@@ -72,27 +179,27 @@ export default function DashboardPage() {
|
|||||||
const canStores = has('stores');
|
const canStores = has('stores');
|
||||||
const canStoreAudits = has('store_audits');
|
const canStoreAudits = has('store_audits');
|
||||||
const canPartners = has('partners');
|
const canPartners = has('partners');
|
||||||
const canPromo = has('promo_codes');
|
|
||||||
const canFinance = has('finance');
|
const canFinance = has('finance');
|
||||||
const canBenefit = has('benefit');
|
const canBenefit = has('benefit');
|
||||||
const canDeliveries = has('deliveries');
|
const canDeliveries = has('deliveries');
|
||||||
const canTickets = has('tickets');
|
const canTickets = has('tickets');
|
||||||
const permsReady = profile !== null;
|
const permsReady = profile !== null;
|
||||||
|
const hasAnalytics = canUsers || canOrders || canPartners || canStores || canBenefit;
|
||||||
|
|
||||||
const [filterForm] = Form.useForm<{
|
const [filterForm] = Form.useForm<{
|
||||||
range: [Dayjs, Dayjs];
|
range: [Dayjs, Dayjs];
|
||||||
cityId?: string;
|
cityId?: string;
|
||||||
promoCodeId?: string;
|
|
||||||
partnerAccountId?: string;
|
|
||||||
}>();
|
}>();
|
||||||
const [filters, setFilters] = useState<AnalyticsFilters>({
|
const [filters, setFilters] = useState<AnalyticsFilters>({
|
||||||
range: [dayjs().subtract(29, 'day'), dayjs()],
|
granularity: 'day',
|
||||||
|
range: defaultRange('day'),
|
||||||
});
|
});
|
||||||
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
|
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
|
||||||
const [analyticsLoading, setAnalyticsLoading] = useState(true);
|
const [analyticsLoading, setAnalyticsLoading] = useState(true);
|
||||||
const [cities, setCities] = useState<CityOption[]>([]);
|
const [cities, setCities] = useState<CityOption[]>([]);
|
||||||
const [promos, setPromos] = useState<PromoOption[]>([]);
|
const [metric, setMetric] = useState<ChartMetric>('total');
|
||||||
const [partners, setPartners] = useState<Array<{ id: string; companyName?: string | null; name: string }>>([]);
|
const [pdfLoading, setPdfLoading] = useState(false);
|
||||||
|
const chartsWrapRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const loadVersion = useCallback(() => {
|
const loadVersion = useCallback(() => {
|
||||||
setVersionLoading(true);
|
setVersionLoading(true);
|
||||||
@@ -136,18 +243,6 @@ export default function DashboardPage() {
|
|||||||
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||||
.then((res) => setCities(res.items ?? []))
|
.then((res) => setCities(res.items ?? []))
|
||||||
.catch(() => setCities([]));
|
.catch(() => setCities([]));
|
||||||
if ((profile.permissionKeys ?? []).includes('promo_codes')) {
|
|
||||||
void request<Paginated<PromoOption>>(`/admin/promo-codes?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
|
||||||
.then((res) => setPromos(res.items ?? []))
|
|
||||||
.catch(() => setPromos([]));
|
|
||||||
}
|
|
||||||
if ((profile.permissionKeys ?? []).includes('partners')) {
|
|
||||||
void request<Paginated<{ id: string; companyName?: string | null; name: string }>>(
|
|
||||||
`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`,
|
|
||||||
)
|
|
||||||
.then((res) => setPartners(res.items ?? []))
|
|
||||||
.catch(() => setPartners([]));
|
|
||||||
}
|
|
||||||
}, [profile]);
|
}, [profile]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -157,42 +252,22 @@ export default function DashboardPage() {
|
|||||||
function applyFilters(values: {
|
function applyFilters(values: {
|
||||||
range?: [Dayjs, Dayjs];
|
range?: [Dayjs, Dayjs];
|
||||||
cityId?: string;
|
cityId?: string;
|
||||||
promoCodeId?: string;
|
|
||||||
partnerAccountId?: string;
|
|
||||||
}) {
|
}) {
|
||||||
const next: AnalyticsFilters = {
|
setFilters((prev) => ({
|
||||||
range: values.range ?? filters.range,
|
...prev,
|
||||||
|
range: values.range ?? prev.range,
|
||||||
cityId: values.cityId || undefined,
|
cityId: values.cityId || undefined,
|
||||||
promoCodeId: values.promoCodeId || undefined,
|
}));
|
||||||
partnerAccountId: values.partnerAccountId || undefined,
|
|
||||||
};
|
|
||||||
setFilters(next);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setCityFilter(cityId: string) {
|
function setGranularity(granularity: DashboardGranularity) {
|
||||||
const next = { ...filters, cityId: cityId === filters.cityId ? undefined : cityId };
|
setFilters((prev) => ({ ...prev, granularity }));
|
||||||
filterForm.setFieldsValue({ cityId: next.cityId });
|
|
||||||
setFilters(next);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setPromoFilter(promoCodeId: string) {
|
function applyDatePreset(kind: 'lastWeek' | 'lastMonth' | 'lastQuarter') {
|
||||||
const key = promoCodeId === 'null' || promoCodeId === '' ? 'none' : promoCodeId;
|
const range = datePresetRange(kind);
|
||||||
const next = {
|
filterForm.setFieldsValue({ range });
|
||||||
...filters,
|
setFilters((prev) => ({ ...prev, range }));
|
||||||
promoCodeId: key === filters.promoCodeId ? undefined : key,
|
|
||||||
};
|
|
||||||
filterForm.setFieldsValue({ promoCodeId: next.promoCodeId });
|
|
||||||
setFilters(next);
|
|
||||||
}
|
|
||||||
|
|
||||||
function setPartnerFilter(partnerAccountId: string) {
|
|
||||||
const next = {
|
|
||||||
...filters,
|
|
||||||
partnerAccountId:
|
|
||||||
partnerAccountId === filters.partnerAccountId ? undefined : partnerAccountId,
|
|
||||||
};
|
|
||||||
filterForm.setFieldsValue({ partnerAccountId: next.partnerAccountId });
|
|
||||||
setFilters(next);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDeploy() {
|
function handleDeploy() {
|
||||||
@@ -217,224 +292,51 @@ export default function DashboardPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shortSha = version?.commitId ? version.commitId.slice(0, 7) : '—';
|
const shortSha = version?.commitId ? version.commitId.slice(0, 7) : '—';
|
||||||
|
const periods = analytics?.periods ?? [];
|
||||||
|
const chartOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
(analytics?.charts ?? [])
|
||||||
|
.filter((chart) => chartIsMetric(chart.key, metric))
|
||||||
|
.map((chart) => ({
|
||||||
|
chart,
|
||||||
|
option: lineOption(periods, chart),
|
||||||
|
})),
|
||||||
|
[analytics, periods, metric],
|
||||||
|
);
|
||||||
|
|
||||||
const ordersDrillQs = useMemo(() => {
|
async function handleDownloadPdf() {
|
||||||
const qs = new URLSearchParams();
|
if (analyticsLoading || chartOptions.length === 0) {
|
||||||
qs.set('createdFrom', filters.range[0].format('YYYY-MM-DD'));
|
message.warning('暂无可下载的图');
|
||||||
qs.set('createdTo', filters.range[1].format('YYYY-MM-DD'));
|
return;
|
||||||
if (filters.cityId && filters.cityId !== 'none') qs.set('cityId', filters.cityId);
|
|
||||||
return qs.toString();
|
|
||||||
}, [filters]);
|
|
||||||
|
|
||||||
const byDateOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byDate ?? [];
|
|
||||||
const legend: string[] = [];
|
|
||||||
const series: EChartsOption['series'] = [];
|
|
||||||
if (canUsers) {
|
|
||||||
legend.push('新增用户');
|
|
||||||
series.push({ name: '新增用户', type: 'line', smooth: true, data: rows.map((r) => r.users) });
|
|
||||||
}
|
}
|
||||||
if (canOrders) {
|
const grainLabel = GRAIN_OPTIONS.find((o) => o.value === filters.granularity)?.label ?? filters.granularity;
|
||||||
legend.push('订单数');
|
const metricLabel = metric === 'increment' ? '增量' : '总量';
|
||||||
series.push({ name: '订单数', type: 'line', smooth: true, data: rows.map((r) => r.orders) });
|
const cityLabel = !filters.cityId
|
||||||
}
|
? (cityScoped ? '全部负责城市' : '全部开城')
|
||||||
return {
|
: filters.cityId === 'none'
|
||||||
tooltip: { trigger: 'axis' },
|
? '未选城'
|
||||||
legend: { data: legend },
|
: (cities.find((c) => c.id === filters.cityId)?.name ?? '城市');
|
||||||
grid: { left: 40, right: 20, top: 40, bottom: 40 },
|
const from = filters.range[0].format('YYYY-MM-DD');
|
||||||
xAxis: {
|
const to = filters.range[1].format('YYYY-MM-DD');
|
||||||
type: 'category',
|
setPdfLoading(true);
|
||||||
data: rows.map((r) => r.date.slice(5)),
|
try {
|
||||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
const doms = [
|
||||||
},
|
...(chartsWrapRef.current?.querySelectorAll<HTMLElement>('[_echarts_instance_]') ?? []),
|
||||||
yAxis: { type: 'value', minInterval: 1 },
|
];
|
||||||
series,
|
await downloadDashboardChartsPdf({
|
||||||
};
|
filename: `数据概览-${metricLabel}-${grainLabel}-${from}_${to}.pdf`,
|
||||||
}, [analytics, canUsers, canOrders]);
|
subtitle: `${metricLabel} · ${grainLabel} · ${from} ~ ${to} · ${cityLabel}`,
|
||||||
|
charts: chartOptions.map(({ chart }, index) => ({
|
||||||
const byCityOption = useMemo<EChartsOption>(() => {
|
title: chart.title,
|
||||||
const rows = analytics?.byCity ?? [];
|
instance: doms[index] ? getInstanceByDom(doms[index]) : undefined,
|
||||||
const legend: string[] = [];
|
})),
|
||||||
const series: EChartsOption['series'] = [];
|
|
||||||
if (canUsers) {
|
|
||||||
legend.push('用户');
|
|
||||||
series.push({ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 });
|
|
||||||
}
|
|
||||||
if (canOrders) {
|
|
||||||
legend.push('订单');
|
|
||||||
series.push({ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 });
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: legend },
|
|
||||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.cityName),
|
|
||||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: { type: 'value', minInterval: 1 },
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}, [analytics, canUsers, canOrders]);
|
|
||||||
|
|
||||||
const byPromoOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byPromo ?? [];
|
|
||||||
const legend: string[] = [];
|
|
||||||
const series: EChartsOption['series'] = [];
|
|
||||||
if (canUsers) {
|
|
||||||
legend.push('用户');
|
|
||||||
series.push({ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 });
|
|
||||||
}
|
|
||||||
if (canOrders) {
|
|
||||||
legend.push('订单');
|
|
||||||
series.push({ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 });
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: legend },
|
|
||||||
grid: { left: 48, right: 20, top: 40, bottom: 64 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.name || r.code),
|
|
||||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: { type: 'value', minInterval: 1 },
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}, [analytics, canUsers, canOrders]);
|
|
||||||
|
|
||||||
const opsByDateOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byDate ?? [];
|
|
||||||
const legend: string[] = [];
|
|
||||||
const series: NonNullable<EChartsOption['series']> = [];
|
|
||||||
if (canPartners) {
|
|
||||||
legend.push('新增合伙人');
|
|
||||||
series.push({ name: '新增合伙人', type: 'line', smooth: true, data: rows.map((r) => r.partners) });
|
|
||||||
}
|
|
||||||
if (canStores) {
|
|
||||||
legend.push('新签门店');
|
|
||||||
series.push({ name: '新签门店', type: 'line', smooth: true, data: rows.map((r) => r.stores) });
|
|
||||||
}
|
|
||||||
if (canBenefit) {
|
|
||||||
legend.push('核销笔数', '核销金额');
|
|
||||||
series.push({ name: '核销笔数', type: 'line', smooth: true, data: rows.map((r) => r.redeems) });
|
|
||||||
series.push({
|
|
||||||
name: '核销金额',
|
|
||||||
type: 'line',
|
|
||||||
smooth: true,
|
|
||||||
yAxisIndex: 1,
|
|
||||||
data: rows.map((r) => r.redeemAmount),
|
|
||||||
});
|
});
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '下载 PDF 失败');
|
||||||
|
} finally {
|
||||||
|
setPdfLoading(false);
|
||||||
}
|
}
|
||||||
return {
|
}
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: legend },
|
|
||||||
grid: { left: 48, right: 48, top: 48, bottom: 40 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.date.slice(5)),
|
|
||||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: [
|
|
||||||
{ type: 'value', name: '数量', minInterval: 1 },
|
|
||||||
{ type: 'value', name: '金额', minInterval: 1 },
|
|
||||||
],
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}, [analytics, canPartners, canStores, canBenefit]);
|
|
||||||
|
|
||||||
const opsByCityOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byCity ?? [];
|
|
||||||
const legend: string[] = [];
|
|
||||||
const series: EChartsOption['series'] = [];
|
|
||||||
if (canPartners) {
|
|
||||||
legend.push('合伙人');
|
|
||||||
series.push({ name: '合伙人', type: 'bar', data: rows.map((r) => r.partners), barMaxWidth: 28 });
|
|
||||||
}
|
|
||||||
if (canStores) {
|
|
||||||
legend.push('门店');
|
|
||||||
series.push({ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 });
|
|
||||||
}
|
|
||||||
if (canBenefit) {
|
|
||||||
legend.push('核销笔数');
|
|
||||||
series.push({ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 });
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: legend },
|
|
||||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.cityName),
|
|
||||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: { type: 'value', minInterval: 1 },
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}, [analytics, canPartners, canStores, canBenefit]);
|
|
||||||
|
|
||||||
const opsByPartnerOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byPartner ?? [];
|
|
||||||
const legend: string[] = [];
|
|
||||||
const series: NonNullable<EChartsOption['series']> = [];
|
|
||||||
if (canStores) {
|
|
||||||
legend.push('门店');
|
|
||||||
series.push({ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 });
|
|
||||||
}
|
|
||||||
if (canBenefit) {
|
|
||||||
legend.push('核销笔数', '核销金额');
|
|
||||||
series.push({ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 });
|
|
||||||
series.push({
|
|
||||||
name: '核销金额',
|
|
||||||
type: 'line',
|
|
||||||
yAxisIndex: 1,
|
|
||||||
data: rows.map((r) => r.redeemAmount),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: legend },
|
|
||||||
grid: { left: 48, right: 48, top: 40, bottom: 64 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.companyName),
|
|
||||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: [
|
|
||||||
{ type: 'value', name: '数量', minInterval: 1 },
|
|
||||||
{ type: 'value', name: '金额' },
|
|
||||||
],
|
|
||||||
series,
|
|
||||||
};
|
|
||||||
}, [analytics, canStores, canBenefit]);
|
|
||||||
|
|
||||||
const redeemByCityOption = useMemo<EChartsOption>(() => {
|
|
||||||
const rows = analytics?.byCity ?? [];
|
|
||||||
return {
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
legend: { data: ['核销笔数', '核销金额'] },
|
|
||||||
grid: { left: 48, right: 48, top: 40, bottom: 48 },
|
|
||||||
xAxis: {
|
|
||||||
type: 'category',
|
|
||||||
data: rows.map((r) => r.cityName),
|
|
||||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
|
||||||
},
|
|
||||||
yAxis: [
|
|
||||||
{ type: 'value', name: '笔数', minInterval: 1 },
|
|
||||||
{ type: 'value', name: '金额' },
|
|
||||||
],
|
|
||||||
series: [
|
|
||||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 36 },
|
|
||||||
{
|
|
||||||
name: '核销金额',
|
|
||||||
type: 'line',
|
|
||||||
yAxisIndex: 1,
|
|
||||||
data: rows.map((r) => r.redeemAmount),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}, [analytics]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -574,7 +476,7 @@ export default function DashboardPage() {
|
|||||||
</Row>
|
</Row>
|
||||||
|
|
||||||
<Card
|
<Card
|
||||||
title="数据统计筛选"
|
title="全局筛选"
|
||||||
style={{ marginBottom: 24 }}
|
style={{ marginBottom: 24 }}
|
||||||
extra={
|
extra={
|
||||||
<Button
|
<Button
|
||||||
@@ -592,8 +494,24 @@ export default function DashboardPage() {
|
|||||||
initialValues={{ range: filters.range }}
|
initialValues={{ range: filters.range }}
|
||||||
onFinish={applyFilters}
|
onFinish={applyFilters}
|
||||||
>
|
>
|
||||||
<Form.Item name="range" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
|
<Form.Item label="粒度">
|
||||||
<DatePicker.RangePicker allowClear={false} />
|
<Segmented
|
||||||
|
options={GRAIN_OPTIONS}
|
||||||
|
value={filters.granularity}
|
||||||
|
onChange={(v) => setGranularity(v as DashboardGranularity)}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="日期" required>
|
||||||
|
<Space size={8} wrap>
|
||||||
|
<Form.Item name="range" noStyle rules={[{ required: true, message: '请选择日期' }]}>
|
||||||
|
<DatePicker.RangePicker allowClear={false} />
|
||||||
|
</Form.Item>
|
||||||
|
{DATE_PRESETS.map((preset) => (
|
||||||
|
<Button key={preset.key} autoInsertSpace={false} onClick={() => applyDatePreset(preset.key)}>
|
||||||
|
{preset.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="cityId" label="城市">
|
<Form.Item name="cityId" label="城市">
|
||||||
<Select
|
<Select
|
||||||
@@ -606,230 +524,49 @@ export default function DashboardPage() {
|
|||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
{canPromo ? (
|
<Form.Item label="指标">
|
||||||
<Form.Item name="promoCodeId" label="推广码">
|
<Segmented
|
||||||
<Select
|
options={METRIC_OPTIONS}
|
||||||
allowClear
|
value={metric}
|
||||||
placeholder="全部来源"
|
onChange={(v) => setMetric(v as ChartMetric)}
|
||||||
style={{ width: 200 }}
|
/>
|
||||||
options={[
|
</Form.Item>
|
||||||
{ value: 'none', label: '自然量 / 无推广码' },
|
|
||||||
...promos.map((p) => ({ value: p.id, label: `${p.name}(${p.code})` })),
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
{canPartners ? (
|
|
||||||
<Form.Item name="partnerAccountId" label="合伙人">
|
|
||||||
<Select
|
|
||||||
allowClear
|
|
||||||
placeholder="全部合伙人"
|
|
||||||
style={{ width: 200 }}
|
|
||||||
options={partners.map((p) => ({
|
|
||||||
value: p.id,
|
|
||||||
label: p.companyName || p.name,
|
|
||||||
}))}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
<Button type="primary" htmlType="submit">查询</Button>
|
<Button type="primary" htmlType="submit">查询</Button>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Button
|
||||||
|
icon={<DownloadOutlined />}
|
||||||
|
loading={pdfLoading}
|
||||||
|
disabled={!hasAnalytics || analyticsLoading || chartOptions.length === 0}
|
||||||
|
onClick={() => void handleDownloadPdf()}
|
||||||
|
>
|
||||||
|
下载PDF
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{canUsers || canOrders ? (
|
{permsReady && !hasAnalytics ? (
|
||||||
<Card
|
<Card style={{ marginBottom: 24 }}>
|
||||||
title={canUsers && canOrders ? '用户 / 订单统计' : canUsers ? '用户统计' : '订单统计'}
|
<Typography.Text type="secondary">当前账号无可视指标</Typography.Text>
|
||||||
style={{ marginBottom: 24 }}
|
</Card>
|
||||||
extra={
|
|
||||||
<Space>
|
|
||||||
{canOrders ? <Link to={`/orders?${ordersDrillQs}`}>查看订单</Link> : null}
|
|
||||||
{canUsers ? <Link to="/users">查看用户</Link> : null}
|
|
||||||
</Space>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
|
||||||
{canUsers ? (
|
|
||||||
<Col xs={24} sm={8}>
|
|
||||||
<Statistic title="区间新增用户" value={analytics?.summary.users ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canOrders ? (
|
|
||||||
<Col xs={24} sm={8}>
|
|
||||||
<Statistic title="区间订单数" value={analytics?.summary.orders ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canOrders ? (
|
|
||||||
<Col xs={24} sm={8}>
|
|
||||||
<Statistic title="区间付费用户" value={analytics?.summary.payingUsers ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
</Row>
|
|
||||||
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24}>
|
|
||||||
<Card type="inner" title="按日趋势" loading={analyticsLoading} size="small">
|
|
||||||
<ReactECharts option={byDateOption} style={{ height: 320 }} notMerge />
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={24} lg={canPromo ? 12 : 24}>
|
|
||||||
<Card
|
|
||||||
type="inner"
|
|
||||||
title="按城市(点击柱联动筛选)"
|
|
||||||
loading={analyticsLoading}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<ReactECharts
|
|
||||||
option={byCityOption}
|
|
||||||
style={{ height: 300 }}
|
|
||||||
notMerge
|
|
||||||
onEvents={{
|
|
||||||
click: (params: { name?: string }) => {
|
|
||||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
|
||||||
if (row) setCityFilter(row.cityId);
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
{canPromo ? (
|
|
||||||
<Col xs={24} lg={12}>
|
|
||||||
<Card
|
|
||||||
type="inner"
|
|
||||||
title="按推广码(点击柱联动筛选)"
|
|
||||||
loading={analyticsLoading}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<ReactECharts
|
|
||||||
option={byPromoOption}
|
|
||||||
style={{ height: 300 }}
|
|
||||||
notMerge
|
|
||||||
onEvents={{
|
|
||||||
click: (params: { name?: string }) => {
|
|
||||||
const row = (analytics?.byPromo ?? []).find(
|
|
||||||
(r) => (r.name || r.code) === params.name,
|
|
||||||
);
|
|
||||||
if (row) setPromoFilter(row.promoCodeId ?? 'none');
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
</Row>
|
|
||||||
</Card>
|
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{canPartners || canStores || canBenefit ? (
|
{hasAnalytics ? (
|
||||||
<Card
|
<div ref={chartsWrapRef} style={{ marginBottom: 24 }}>
|
||||||
title={[canPartners && '合伙人', canStores && '门店', canBenefit && '核销'].filter(Boolean).join(' / ') + '统计'}
|
{chartOptions.map(({ chart, option }) => (
|
||||||
style={{ marginBottom: 24 }}
|
|
||||||
extra={
|
|
||||||
<Space>
|
|
||||||
{canPartners ? <Link to="/city-partners">查看合伙人</Link> : null}
|
|
||||||
{canStores ? <Link to="/stores">查看门店</Link> : null}
|
|
||||||
{canBenefit ? <Link to="/redeem-records">查看核销</Link> : null}
|
|
||||||
</Space>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
|
||||||
{canPartners ? (
|
|
||||||
<Col xs={24} sm={6}>
|
|
||||||
<Statistic title="区间新增合伙人" value={analytics?.summary.partners ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canStores ? (
|
|
||||||
<Col xs={24} sm={6}>
|
|
||||||
<Statistic title="区间新签门店" value={analytics?.summary.stores ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canBenefit ? (
|
|
||||||
<Col xs={24} sm={6}>
|
|
||||||
<Statistic title="区间核销笔数" value={analytics?.summary.redeems ?? 0} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canBenefit ? (
|
|
||||||
<Col xs={24} sm={6}>
|
|
||||||
<Statistic title="区间核销金额" value={analytics?.summary.redeemAmount ?? 0} precision={2} />
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
</Row>
|
|
||||||
|
|
||||||
<Row gutter={[16, 16]}>
|
|
||||||
<Col xs={24}>
|
|
||||||
<Card type="inner" title="按日趋势" loading={analyticsLoading} size="small">
|
|
||||||
<ReactECharts option={opsByDateOption} style={{ height: 320 }} notMerge />
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
<Col xs={24} lg={canBenefit ? 12 : 24}>
|
|
||||||
<Card
|
<Card
|
||||||
type="inner"
|
key={chart.key}
|
||||||
title="按城市(点击柱联动筛选)"
|
title={chart.title}
|
||||||
|
extra={<Link to={listHref(chart.href, filters)}>查看</Link>}
|
||||||
loading={analyticsLoading}
|
loading={analyticsLoading}
|
||||||
size="small"
|
style={{ marginBottom: 16 }}
|
||||||
>
|
>
|
||||||
<ReactECharts
|
<ReactECharts option={option} style={{ height: 320, width: '100%' }} notMerge />
|
||||||
option={opsByCityOption}
|
|
||||||
style={{ height: 300 }}
|
|
||||||
notMerge
|
|
||||||
onEvents={{
|
|
||||||
click: (params: { name?: string }) => {
|
|
||||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
|
||||||
if (row) setCityFilter(row.cityId);
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
))}
|
||||||
{canBenefit ? (
|
</div>
|
||||||
<Col xs={24} lg={12}>
|
|
||||||
<Card
|
|
||||||
type="inner"
|
|
||||||
title="按城市核销金额"
|
|
||||||
loading={analyticsLoading}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<ReactECharts
|
|
||||||
option={redeemByCityOption}
|
|
||||||
style={{ height: 300 }}
|
|
||||||
notMerge
|
|
||||||
onEvents={{
|
|
||||||
click: (params: { name?: string }) => {
|
|
||||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
|
||||||
if (row) setCityFilter(row.cityId);
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
{canPartners && (canStores || canBenefit) ? (
|
|
||||||
<Col xs={24}>
|
|
||||||
<Card
|
|
||||||
type="inner"
|
|
||||||
title="按合伙人(门店 / 核销,点击联动筛选)"
|
|
||||||
loading={analyticsLoading}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<ReactECharts
|
|
||||||
option={opsByPartnerOption}
|
|
||||||
style={{ height: 320 }}
|
|
||||||
notMerge
|
|
||||||
onEvents={{
|
|
||||||
click: (params: { name?: string }) => {
|
|
||||||
const row = (analytics?.byPartner ?? []).find(
|
|
||||||
(r) => r.companyName === params.name,
|
|
||||||
);
|
|
||||||
if (row) setPartnerFilter(row.partnerAccountId);
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Card>
|
|
||||||
</Col>
|
|
||||||
) : null}
|
|
||||||
</Row>
|
|
||||||
</Card>
|
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{canFinance || canTickets ? (
|
{canFinance || canTickets ? (
|
||||||
|
|||||||
@@ -327,6 +327,9 @@ export default function OrdersPage() {
|
|||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const initialOrderNo = searchParams.get('orderNo')?.trim() || '';
|
const initialOrderNo = searchParams.get('orderNo')?.trim() || '';
|
||||||
const initialPromoCodeId = searchParams.get('promoCodeId')?.trim() || '';
|
const initialPromoCodeId = searchParams.get('promoCodeId')?.trim() || '';
|
||||||
|
const initialCityId = searchParams.get('cityId')?.trim() || '';
|
||||||
|
const initialCreatedFrom = searchParams.get('createdFrom')?.trim() || '';
|
||||||
|
const initialCreatedTo = searchParams.get('createdTo')?.trim() || '';
|
||||||
const initialStatusParam = searchParams.getAll('status').join(',');
|
const initialStatusParam = searchParams.getAll('status').join(',');
|
||||||
const initialStatuses = useMemo(
|
const initialStatuses = useMemo(
|
||||||
() => initialStatusParam.split(',').map((s) => s.trim()).filter(Boolean),
|
() => initialStatusParam.split(',').map((s) => s.trim()).filter(Boolean),
|
||||||
@@ -389,6 +392,18 @@ export default function OrdersPage() {
|
|||||||
}
|
}
|
||||||
}, [form, initialOrderNo]);
|
}, [form, initialOrderNo]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const patch: { cityId?: string; dateRange?: [Dayjs, Dayjs] } = {};
|
||||||
|
if (initialCityId) patch.cityId = initialCityId;
|
||||||
|
if (
|
||||||
|
/^\d{4}-\d{2}-\d{2}$/.test(initialCreatedFrom) &&
|
||||||
|
/^\d{4}-\d{2}-\d{2}$/.test(initialCreatedTo)
|
||||||
|
) {
|
||||||
|
patch.dateRange = [dayjs(initialCreatedFrom), dayjs(initialCreatedTo)];
|
||||||
|
}
|
||||||
|
if (Object.keys(patch).length) form.setFieldsValue(patch);
|
||||||
|
}, [form, initialCityId, initialCreatedFrom, initialCreatedTo]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialStatuses.length) {
|
if (initialStatuses.length) {
|
||||||
form.setFieldsValue({ status: initialStatuses });
|
form.setFieldsValue({ status: initialStatuses });
|
||||||
@@ -437,7 +452,7 @@ export default function OrdersPage() {
|
|||||||
const statusList = statuses.length ? statuses : initialStatuses;
|
const statusList = statuses.length ? statuses : initialStatuses;
|
||||||
for (const status of statusList) qs.append('status', status);
|
for (const status of statusList) qs.append('status', status);
|
||||||
if (values.orderType) qs.set('orderType', values.orderType);
|
if (values.orderType) qs.set('orderType', values.orderType);
|
||||||
if (values.cityId) qs.set('cityId', values.cityId);
|
if (values.cityId || initialCityId) qs.set('cityId', values.cityId || initialCityId);
|
||||||
if (values.receiverPhone) qs.set('receiverPhone', values.receiverPhone);
|
if (values.receiverPhone) qs.set('receiverPhone', values.receiverPhone);
|
||||||
if (values.userKeyword) qs.set('userKeyword', values.userKeyword);
|
if (values.userKeyword) qs.set('userKeyword', values.userKeyword);
|
||||||
if (values.productKeyword) qs.set('productKeyword', values.productKeyword);
|
if (values.productKeyword) qs.set('productKeyword', values.productKeyword);
|
||||||
@@ -445,14 +460,16 @@ export default function OrdersPage() {
|
|||||||
if (values.deliveryType) qs.set('deliveryType', values.deliveryType);
|
if (values.deliveryType) qs.set('deliveryType', values.deliveryType);
|
||||||
if (values.assocPartnerAccountId) qs.set('assocPartnerAccountId', values.assocPartnerAccountId);
|
if (values.assocPartnerAccountId) qs.set('assocPartnerAccountId', values.assocPartnerAccountId);
|
||||||
if (initialPromoCodeId) qs.set('promoCodeId', initialPromoCodeId);
|
if (initialPromoCodeId) qs.set('promoCodeId', initialPromoCodeId);
|
||||||
if (values.dateRange?.[0]) qs.set('createdFrom', values.dateRange[0].format('YYYY-MM-DD'));
|
const createdFrom = values.dateRange?.[0]?.format('YYYY-MM-DD') || initialCreatedFrom;
|
||||||
if (values.dateRange?.[1]) qs.set('createdTo', values.dateRange[1].format('YYYY-MM-DD'));
|
const createdTo = values.dateRange?.[1]?.format('YYYY-MM-DD') || initialCreatedTo;
|
||||||
|
if (createdFrom) qs.set('createdFrom', createdFrom);
|
||||||
|
if (createdTo) qs.set('createdTo', createdTo);
|
||||||
const res = await request<Paginated<AdminOrderRow>>(`/admin/orders?${qs}`);
|
const res = await request<Paginated<AdminOrderRow>>(`/admin/orders?${qs}`);
|
||||||
setData(res);
|
setData(res);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [form, page, pageSize, initialOrderNo, initialPromoCodeId, initialStatuses]);
|
}, [form, page, pageSize, initialOrderNo, initialPromoCodeId, initialStatuses, initialCityId, initialCreatedFrom, initialCreatedTo]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load();
|
void load();
|
||||||
@@ -721,7 +738,15 @@ export default function OrdersPage() {
|
|||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space size={4} wrap>
|
<Space size={4} wrap>
|
||||||
<span>{row.productName || '—'}</span>
|
<span>{row.productName || '—'}</span>
|
||||||
{row.fulfillmentHold ? <Tag color="orange">大单</Tag> : null}
|
{row.fulfillmentHold ? (
|
||||||
|
<Tag color="orange">
|
||||||
|
{row.fulfillmentHoldReason === 'LARGE_ORDER_GE_10_BOXES'
|
||||||
|
? '大单'
|
||||||
|
: row.fulfillmentHoldReason === 'COURIER_OUT_OF_SERVICE'
|
||||||
|
? '超区'
|
||||||
|
: '推单失败'}
|
||||||
|
</Tag>
|
||||||
|
) : null}
|
||||||
{row.orderType === 'PROXY' || row.isProxyOrder ? (
|
{row.orderType === 'PROXY' || row.isProxyOrder ? (
|
||||||
<Tag color="purple">代下单</Tag>
|
<Tag color="purple">代下单</Tag>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -1023,7 +1048,7 @@ export default function OrdersPage() {
|
|||||||
) : <span />}
|
) : <span />}
|
||||||
<Space size={12} wrap>
|
<Space size={12} wrap>
|
||||||
<Form.Item name="fulfillmentHold" valuePropName="checked" noStyle>
|
<Form.Item name="fulfillmentHold" valuePropName="checked" noStyle>
|
||||||
<Checkbox>大单拦截</Checkbox>
|
<Checkbox>履约拦截</Checkbox>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -1133,7 +1158,7 @@ export default function OrdersPage() {
|
|||||||
{detail.fulfillmentHold ? (
|
{detail.fulfillmentHold ? (
|
||||||
<Tag color="orange">
|
<Tag color="orange">
|
||||||
{FULFILLMENT_HOLD_REASON_LABELS[detail.fulfillmentHoldReason || ''] ||
|
{FULFILLMENT_HOLD_REASON_LABELS[detail.fulfillmentHoldReason || ''] ||
|
||||||
'大单待确认'}
|
'履约待确认'}
|
||||||
</Tag>
|
</Tag>
|
||||||
) : null}
|
) : null}
|
||||||
{detail.orderType === 'PROXY' || detail.isProxyOrder ? (
|
{detail.orderType === 'PROXY' || detail.isProxyOrder ? (
|
||||||
@@ -1530,10 +1555,16 @@ export default function OrdersPage() {
|
|||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
style={{ marginBottom: 12 }}
|
style={{ marginBottom: 12 }}
|
||||||
message="大单已拦截自动推小飞侠"
|
message={
|
||||||
|
shipTarget.fulfillmentHoldReason === 'LARGE_ORDER_GE_10_BOXES'
|
||||||
|
? '大单已拦截自动推小飞侠'
|
||||||
|
: shipTarget.fulfillmentHoldReason === 'COURIER_OUT_OF_SERVICE'
|
||||||
|
? '小飞侠超出服务区'
|
||||||
|
: '自动推配送失败'
|
||||||
|
}
|
||||||
description={
|
description={
|
||||||
FULFILLMENT_HOLD_REASON_LABELS[shipTarget.fulfillmentHoldReason || ''] ||
|
FULFILLMENT_HOLD_REASON_LABELS[shipTarget.fulfillmentHoldReason || ''] ||
|
||||||
'≥10箱订单需总部确认:可选仓推小飞侠,或改用快递自配送。'
|
'请确认后:可选仓重推小飞侠,或改用快递自配送。'
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Tabs,
|
||||||
|
TimePicker,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
|
import {
|
||||||
|
WECOM_REPORT_KIND_LABELS,
|
||||||
|
WECOM_REPORT_KINDS,
|
||||||
|
WECOM_REPORT_WEEKDAY_OPTIONS,
|
||||||
|
type WecomReportKind,
|
||||||
|
type WecomReportPreviewDto,
|
||||||
|
type WecomReportPushDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
|
||||||
|
type FormValues = {
|
||||||
|
name: string;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId?: string;
|
||||||
|
sendTime: Dayjs;
|
||||||
|
sendWeekday: number;
|
||||||
|
sendMonthDay: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function ReportKindPane({
|
||||||
|
kind,
|
||||||
|
row,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
kind: WecomReportKind;
|
||||||
|
row: WecomReportPushDto | undefined;
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const [form] = Form.useForm<FormValues>();
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [previewing, setPreviewing] = useState(false);
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [preview, setPreview] = useState<WecomReportPreviewDto | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!row) return;
|
||||||
|
form.setFieldsValue({
|
||||||
|
name: row.name,
|
||||||
|
webhookUrl: row.webhookUrl,
|
||||||
|
enabled: row.enabled,
|
||||||
|
mentionWecomUserId: row.mentionWecomUserId ?? undefined,
|
||||||
|
sendTime: dayjs().hour(row.sendHour).minute(row.sendMinute).second(0),
|
||||||
|
sendWeekday: row.sendWeekday,
|
||||||
|
sendMonthDay: row.sendMonthDay,
|
||||||
|
});
|
||||||
|
}, [form, row]);
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await request(`/admin/wecom-reports/${kind}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: values.name,
|
||||||
|
webhookUrl: values.webhookUrl,
|
||||||
|
enabled: values.enabled,
|
||||||
|
mentionWecomUserId: values.mentionWecomUserId?.trim() || null,
|
||||||
|
sendHour: values.sendTime.hour(),
|
||||||
|
sendMinute: values.sendTime.minute(),
|
||||||
|
sendWeekday: values.sendWeekday,
|
||||||
|
sendMonthDay: values.sendMonthDay,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
message.success('已保存');
|
||||||
|
onSaved();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openPreview() {
|
||||||
|
setPreviewing(true);
|
||||||
|
try {
|
||||||
|
const data = await request<WecomReportPreviewDto>(`/admin/wecom-reports/${kind}/preview`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: '{}',
|
||||||
|
});
|
||||||
|
setPreview(data);
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '预览失败');
|
||||||
|
} finally {
|
||||||
|
setPreviewing(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendNow() {
|
||||||
|
setSending(true);
|
||||||
|
try {
|
||||||
|
const res = await request<{ message: string }>(`/admin/wecom-reports/${kind}/send`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: '{}',
|
||||||
|
});
|
||||||
|
message.success(res.message || '已发送');
|
||||||
|
onSaved();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '发送失败');
|
||||||
|
} finally {
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const label = WECOM_REPORT_KIND_LABELS[kind];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Form form={form} layout="vertical" style={{ maxWidth: 640 }}>
|
||||||
|
<Form.Item name="enabled" label="启用定时推送" valuePropName="checked">
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
||||||
|
<Input maxLength={64} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="webhookUrl"
|
||||||
|
label="群机器人 Webhook"
|
||||||
|
extra="企业微信群「群机器人」Webhook,与「消息推送」分开配置。"
|
||||||
|
rules={[{ required: true, message: '请填写 Webhook' }]}
|
||||||
|
>
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="mentionWecomUserId" label="@成员 userid">
|
||||||
|
<Input placeholder="可选,企业微信成员账号" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="sendTime"
|
||||||
|
label="发送时刻"
|
||||||
|
extra={
|
||||||
|
kind === 'daily'
|
||||||
|
? '按北京时间当天该时刻发送当日数据。'
|
||||||
|
: kind === 'weekly'
|
||||||
|
? '按北京时间该星期该时刻发送上一自然周。'
|
||||||
|
: '按北京时间每月该日该时刻发送上一自然月。'
|
||||||
|
}
|
||||||
|
rules={[{ required: true, message: '请选择时刻' }]}
|
||||||
|
>
|
||||||
|
<TimePicker format="HH:mm" minuteStep={1} allowClear={false} />
|
||||||
|
</Form.Item>
|
||||||
|
{kind === 'weekly' ? (
|
||||||
|
<Form.Item name="sendWeekday" label="发送星期" rules={[{ required: true }]}>
|
||||||
|
<Select options={WECOM_REPORT_WEEKDAY_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{kind === 'monthly' ? (
|
||||||
|
<Form.Item name="sendMonthDay" label="每月几号" rules={[{ required: true }]}>
|
||||||
|
<InputNumber min={1} max={31} />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
{row?.lastSentAt
|
||||||
|
? `上次发送:${fmtTime(row.lastSentAt)}(${row.lastSentPeriod ?? '—'})`
|
||||||
|
: '尚未发送'}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Space wrap>
|
||||||
|
<Button type="primary" loading={saving} onClick={() => void save()}>
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
<Button loading={previewing} onClick={() => void openPreview()}>
|
||||||
|
预览
|
||||||
|
</Button>
|
||||||
|
<Button loading={sending} onClick={() => void sendNow()}>
|
||||||
|
立即发送
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Form>
|
||||||
|
<Modal
|
||||||
|
title={`预览${label}`}
|
||||||
|
open={!!preview}
|
||||||
|
onCancel={() => setPreview(null)}
|
||||||
|
footer={<Button onClick={() => setPreview(null)}>关闭</Button>}
|
||||||
|
width={560}
|
||||||
|
>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
区间 {preview?.rangeLabel}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<pre style={{ whiteSpace: 'pre-wrap', margin: 0 }}>{preview?.markdown}</pre>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WecomReportsPage() {
|
||||||
|
const [rows, setRows] = useState<WecomReportPushDto[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const load = useCallback(() => {
|
||||||
|
setLoading(true);
|
||||||
|
return request<WecomReportPushDto[]>('/admin/wecom-reports')
|
||||||
|
.then(setRows)
|
||||||
|
.catch((e) => message.error(e instanceof Error ? e.message : '加载失败'))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const byKind = new Map(rows.map((r) => [r.kind, r]));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>企微机器人 · 报告</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
日报 / 周报 / 月报走企微群机器人 Webhook,配置与「消息推送」相互独立。口径与概览一致:数量为期末存量,新增为区间内发生额;订单金额按已付
|
||||||
|
payAmount,核销按核销单。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Card loading={loading}>
|
||||||
|
<Tabs
|
||||||
|
items={WECOM_REPORT_KINDS.map((kind) => ({
|
||||||
|
key: kind,
|
||||||
|
label: WECOM_REPORT_KIND_LABELS[kind],
|
||||||
|
children: <ReportKindPane kind={kind} row={byKind.get(kind)} onSaved={() => void load()} />,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Alert, Button, Card, Col, Descriptions, Form, Input, InputNumber, Row, Select, Space,
|
Alert, Button, Card, Col, Descriptions, Form, Image, Input, InputNumber, Row, Select, Space,
|
||||||
Tabs, Tag, Typography, message,
|
Tabs, Tag, Typography, message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
@@ -53,6 +53,22 @@ const CREATE_DEFAULTS = {
|
|||||||
|
|
||||||
function ResultPanel({ result }: { result: ApiResult | null }) {
|
function ResultPanel({ result }: { result: ApiResult | null }) {
|
||||||
if (!result) return <Typography.Text type="secondary">点击「调用接口」后在此显示响应</Typography.Text>;
|
if (!result) return <Typography.Text type="secondary">点击「调用接口」后在此显示响应</Typography.Text>;
|
||||||
|
const display = (() => {
|
||||||
|
if (!result.data || typeof result.data !== 'object') return result;
|
||||||
|
const data = result.data as { count?: number; data?: string[] };
|
||||||
|
if (!Array.isArray(data.data)) return result;
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
data: data.data.map((item) =>
|
||||||
|
typeof item === 'string' && item.length > 120
|
||||||
|
? `${item.slice(0, 80)}…(len=${item.length})`
|
||||||
|
: item,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
})();
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Space style={{ marginBottom: 8 }}>
|
<Space style={{ marginBottom: 8 }}>
|
||||||
@@ -64,7 +80,7 @@ function ResultPanel({ result }: { result: ApiResult | null }) {
|
|||||||
margin: 0, padding: 12, background: '#f5f5f5', borderRadius: 4,
|
margin: 0, padding: 12, background: '#f5f5f5', borderRadius: 4,
|
||||||
maxHeight: 360, overflow: 'auto', fontSize: 12,
|
maxHeight: 360, overflow: 'auto', fontSize: 12,
|
||||||
}}>
|
}}>
|
||||||
{JSON.stringify(result, null, 2)}
|
{JSON.stringify(display, null, 2)}
|
||||||
</pre>
|
</pre>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -81,7 +97,9 @@ export default function XiaofeixiaTestPage() {
|
|||||||
const [queryForm] = Form.useForm();
|
const [queryForm] = Form.useForm();
|
||||||
const [batchForm] = Form.useForm();
|
const [batchForm] = Form.useForm();
|
||||||
const [trackForm] = Form.useForm();
|
const [trackForm] = Form.useForm();
|
||||||
|
const [signPhotoForm] = Form.useForm();
|
||||||
const [cancelForm] = Form.useForm();
|
const [cancelForm] = Form.useForm();
|
||||||
|
const [signPhotoPreview, setSignPhotoPreview] = useState<string[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void request<XfxConfig>('/admin/courier/xiaofeixia/config').then(setConfig);
|
void request<XfxConfig>('/admin/courier/xiaofeixia/config').then(setConfig);
|
||||||
@@ -99,12 +117,19 @@ export default function XiaofeixiaTestPage() {
|
|||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
});
|
});
|
||||||
setResult(res);
|
setResult(res);
|
||||||
|
if (path.endsWith('/get-sign-photos')) {
|
||||||
|
const data = (res.data as { data?: string[] } | undefined)?.data;
|
||||||
|
setSignPhotoPreview(Array.isArray(data) ? data.filter((u) => typeof u === 'string') : []);
|
||||||
|
} else {
|
||||||
|
setSignPhotoPreview([]);
|
||||||
|
}
|
||||||
if (res.ok) message.success('调用成功');
|
if (res.ok) message.success('调用成功');
|
||||||
else message.warning(res.error || '调用失败');
|
else message.warning(res.error || '调用失败');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const err = e instanceof Error ? e.message : String(e);
|
const err = e instanceof Error ? e.message : String(e);
|
||||||
message.error(err);
|
message.error(err);
|
||||||
setResult({ ok: false, elapsedMs: 0, error: err });
|
setResult({ ok: false, elapsedMs: 0, error: err });
|
||||||
|
setSignPhotoPreview([]);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -118,7 +143,7 @@ export default function XiaofeixiaTestPage() {
|
|||||||
<div>
|
<div>
|
||||||
<Typography.Title level={4}>小飞侠接口联调</Typography.Title>
|
<Typography.Title level={4}>小飞侠接口联调</Typography.Title>
|
||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
通过 HQ 后台直接调用后端封装的小飞侠 API(cmd 100101~100301)。凭证请在
|
通过 HQ 后台直接调用后端封装的小飞侠 API(cmd 100101~100301,含签收图片 100108)。凭证请在
|
||||||
<Link to="/fulfillment-providers">仓配管理</Link>
|
<Link to="/fulfillment-providers">仓配管理</Link>
|
||||||
中配置;联调会优先使用仓配管理里启用的小飞侠承运商。
|
中配置;联调会优先使用仓配管理里启用的小飞侠承运商。
|
||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
@@ -273,6 +298,25 @@ export default function XiaofeixiaTestPage() {
|
|||||||
</Form>
|
</Form>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'signPhotos',
|
||||||
|
label: '签收图片 (100108)',
|
||||||
|
children: (
|
||||||
|
<Form
|
||||||
|
form={signPhotoForm}
|
||||||
|
layout="vertical"
|
||||||
|
onFinish={(v) => void invoke('/admin/courier/xiaofeixia/get-sign-photos', v)}
|
||||||
|
>
|
||||||
|
<Form.Item name="trackingNumber" label="运单号 number">
|
||||||
|
<Input placeholder="小飞侠运单号,与商家单号二选一" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="outNumber" label="商家单号 outNumber">
|
||||||
|
<Input placeholder="外部单号,与运单号二选一" />
|
||||||
|
</Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit" loading={loading}>调用接口</Button>
|
||||||
|
</Form>
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'cancel',
|
key: 'cancel',
|
||||||
label: '取消订单 (100103)',
|
label: '取消订单 (100103)',
|
||||||
@@ -290,6 +334,24 @@ export default function XiaofeixiaTestPage() {
|
|||||||
<Col xs={24} lg={10}>
|
<Col xs={24} lg={10}>
|
||||||
<Card title="响应结果" size="small">
|
<Card title="响应结果" size="small">
|
||||||
<ResultPanel result={result} />
|
<ResultPanel result={result} />
|
||||||
|
{signPhotoPreview.length > 0 ? (
|
||||||
|
<div style={{ marginTop: 16 }}>
|
||||||
|
<Typography.Text strong>签收照片预览({signPhotoPreview.length})</Typography.Text>
|
||||||
|
<Image.PreviewGroup>
|
||||||
|
<Space wrap style={{ marginTop: 8 }}>
|
||||||
|
{signPhotoPreview.map((url, index) => (
|
||||||
|
<Image
|
||||||
|
key={`${index}-${url.slice(0, 32)}`}
|
||||||
|
src={url}
|
||||||
|
width={96}
|
||||||
|
height={96}
|
||||||
|
style={{ objectFit: 'cover', borderRadius: 6 }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
</Image.PreviewGroup>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
|||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||||
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
||||||
|
import { validateShippingAddress } from '@dukang/domain';
|
||||||
import ChinaRegionPicker from '../components/ChinaRegionPicker';
|
import ChinaRegionPicker from '../components/ChinaRegionPicker';
|
||||||
import { getToken, request } from '../lib/api';
|
import { getToken, request } from '../lib/api';
|
||||||
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
||||||
@@ -243,6 +244,13 @@ export default function ProxyOrderPage() {
|
|||||||
if (!allowOnline) return '该商品不支持线上购买';
|
if (!allowOnline) return '该商品不支持线上购买';
|
||||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||||
if (!addressDetail.trim()) return '请填写详细地址';
|
if (!addressDetail.trim()) return '请填写详细地址';
|
||||||
|
const shipping = validateShippingAddress({
|
||||||
|
province: region.province,
|
||||||
|
city: region.city,
|
||||||
|
district: region.district,
|
||||||
|
detail: addressDetail,
|
||||||
|
});
|
||||||
|
if (!shipping.ok) return shipping.message || '请完善收货地址';
|
||||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||||
} else if (!allowOnSite) {
|
} else if (!allowOnSite) {
|
||||||
return '该商品不支持现场提货';
|
return '该商品不支持现场提货';
|
||||||
|
|||||||
@@ -53,10 +53,10 @@ export default function OrderQtyControls({ value, unitLabel, onChange }: OrderQt
|
|||||||
onBlur={commit}
|
onBlur={commit}
|
||||||
onConfirm={commit}
|
onConfirm={commit}
|
||||||
/>
|
/>
|
||||||
<Text className="order-qty-unit">{unitLabel}</Text>
|
|
||||||
<View className="order-qty-btn" onClick={() => onChange(Math.min(MAX_QTY, current() + 1))}>
|
<View className="order-qty-btn" onClick={() => onChange(Math.min(MAX_QTY, current() + 1))}>
|
||||||
<Text>+</Text>
|
<Text>+</Text>
|
||||||
</View>
|
</View>
|
||||||
|
<Text className="order-qty-unit">{unitLabel}</Text>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import {
|
|||||||
getCitiesForPicker,
|
getCitiesForPicker,
|
||||||
getDistricts,
|
getDistricts,
|
||||||
getDistrictsForPicker,
|
getDistrictsForPicker,
|
||||||
|
getDistrictsForShippingPicker,
|
||||||
getProvincesForPicker,
|
getProvincesForPicker,
|
||||||
normalizeRegionSelection,
|
normalizeRegionSelection,
|
||||||
|
normalizeShippingRegionSelection,
|
||||||
toCityLevelRegion,
|
toCityLevelRegion,
|
||||||
type RegionSelection,
|
type RegionSelection,
|
||||||
} from '../lib/region-data';
|
} from '../lib/region-data';
|
||||||
@@ -18,6 +20,8 @@ type RegionPickerProps = {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onConfirm: (region: RegionSelection) => void;
|
onConfirm: (region: RegionSelection) => void;
|
||||||
levels?: 2 | 3;
|
levels?: 2 | 3;
|
||||||
|
/** filter:门店筛选可「全市」;shipping:收货地址禁止伪区县 */
|
||||||
|
mode?: 'filter' | 'shipping';
|
||||||
};
|
};
|
||||||
|
|
||||||
type PickerLevel = 'province' | 'city' | 'district';
|
type PickerLevel = 'province' | 'city' | 'district';
|
||||||
@@ -28,8 +32,13 @@ const ALL_TABS: Array<{ key: PickerLevel; label: string }> = [
|
|||||||
{ key: 'district', label: '区县' },
|
{ key: 'district', label: '区县' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function initialTab(value: RegionSelection, levels: 2 | 3): PickerLevel {
|
function initialTab(value: RegionSelection, levels: 2 | 3, mode: 'filter' | 'shipping'): PickerLevel {
|
||||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
const normalized =
|
||||||
|
levels === 2
|
||||||
|
? toCityLevelRegion(value)
|
||||||
|
: mode === 'shipping'
|
||||||
|
? normalizeShippingRegionSelection(value)
|
||||||
|
: normalizeRegionSelection(value);
|
||||||
if (levels === 2) {
|
if (levels === 2) {
|
||||||
return normalized.province && normalized.province !== REGION_ALL ? 'city' : 'province';
|
return normalized.province && normalized.province !== REGION_ALL ? 'city' : 'province';
|
||||||
}
|
}
|
||||||
@@ -54,24 +63,35 @@ export default function RegionPicker({
|
|||||||
onClose,
|
onClose,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
levels = 3,
|
levels = 3,
|
||||||
|
mode = 'filter',
|
||||||
}: RegionPickerProps) {
|
}: RegionPickerProps) {
|
||||||
const [draft, setDraft] = useState<RegionSelection>(value);
|
const [draft, setDraft] = useState<RegionSelection>(value);
|
||||||
const [activeTab, setActiveTab] = useState<PickerLevel>('province');
|
const [activeTab, setActiveTab] = useState<PickerLevel>('province');
|
||||||
|
|
||||||
const tabs = levels === 2 ? ALL_TABS.slice(0, 2) : ALL_TABS;
|
const tabs = levels === 2 ? ALL_TABS.slice(0, 2) : ALL_TABS;
|
||||||
|
const shipping = mode === 'shipping';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
const normalized =
|
||||||
|
levels === 2
|
||||||
|
? toCityLevelRegion(value)
|
||||||
|
: shipping
|
||||||
|
? normalizeShippingRegionSelection(value)
|
||||||
|
: normalizeRegionSelection(value);
|
||||||
setDraft(normalized);
|
setDraft(normalized);
|
||||||
setActiveTab(initialTab(value, levels));
|
setActiveTab(initialTab(value, levels, mode));
|
||||||
}, [open, value, levels]);
|
}, [open, value, levels, mode, shipping]);
|
||||||
|
|
||||||
const listItems = useMemo(() => {
|
const listItems = useMemo(() => {
|
||||||
if (activeTab === 'province') return getProvincesForPicker();
|
if (activeTab === 'province') return getProvincesForPicker();
|
||||||
if (activeTab === 'city') return getCitiesForPicker(draft.province);
|
if (activeTab === 'city') {
|
||||||
|
if (shipping) return getCities(draft.province);
|
||||||
|
return getCitiesForPicker(draft.province);
|
||||||
|
}
|
||||||
|
if (shipping) return getDistrictsForShippingPicker(draft.province, draft.city);
|
||||||
return getDistrictsForPicker(draft.province, draft.city);
|
return getDistrictsForPicker(draft.province, draft.city);
|
||||||
}, [activeTab, draft.province, draft.city]);
|
}, [activeTab, draft.province, draft.city, shipping]);
|
||||||
|
|
||||||
const selectedValue =
|
const selectedValue =
|
||||||
activeTab === 'province' ? draft.province : activeTab === 'city' ? draft.city : draft.district;
|
activeTab === 'province' ? draft.province : activeTab === 'city' ? draft.city : draft.district;
|
||||||
@@ -79,12 +99,19 @@ export default function RegionPicker({
|
|||||||
const canConfirm =
|
const canConfirm =
|
||||||
levels === 2
|
levels === 2
|
||||||
? Boolean(draft.province && draft.city)
|
? Boolean(draft.province && draft.city)
|
||||||
: Boolean(draft.province && draft.city && draft.district);
|
: shipping
|
||||||
|
? Boolean(
|
||||||
|
draft.province &&
|
||||||
|
draft.city &&
|
||||||
|
draft.district &&
|
||||||
|
draft.district !== REGION_ALL,
|
||||||
|
)
|
||||||
|
: Boolean(draft.province && draft.city && draft.district);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
function selectProvince(province: string) {
|
function selectProvince(province: string) {
|
||||||
if (province === REGION_ALL) {
|
if (!shipping && province === REGION_ALL) {
|
||||||
setDraft({ province: REGION_ALL, city: REGION_ALL, district: REGION_ALL });
|
setDraft({ province: REGION_ALL, city: REGION_ALL, district: REGION_ALL });
|
||||||
setActiveTab('city');
|
setActiveTab('city');
|
||||||
return;
|
return;
|
||||||
@@ -97,12 +124,16 @@ export default function RegionPicker({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const nextDistricts = getDistricts(province, city);
|
const nextDistricts = getDistricts(province, city);
|
||||||
setDraft({ province, city, district: nextDistricts[0] ?? '' });
|
setDraft({
|
||||||
|
province,
|
||||||
|
city,
|
||||||
|
district: shipping ? '' : (nextDistricts[0] ?? ''),
|
||||||
|
});
|
||||||
setActiveTab('city');
|
setActiveTab('city');
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectCity(city: string) {
|
function selectCity(city: string) {
|
||||||
if (city === REGION_ALL) {
|
if (!shipping && city === REGION_ALL) {
|
||||||
setDraft({ ...draft, city: REGION_ALL, district: REGION_ALL });
|
setDraft({ ...draft, city: REGION_ALL, district: REGION_ALL });
|
||||||
if (levels === 3) setActiveTab('district');
|
if (levels === 3) setActiveTab('district');
|
||||||
return;
|
return;
|
||||||
@@ -112,11 +143,16 @@ export default function RegionPicker({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const nextDistricts = getDistricts(draft.province, city);
|
const nextDistricts = getDistricts(draft.province, city);
|
||||||
setDraft({ ...draft, city, district: nextDistricts[0] ?? '' });
|
setDraft({
|
||||||
|
...draft,
|
||||||
|
city,
|
||||||
|
district: shipping ? '' : (nextDistricts[0] ?? ''),
|
||||||
|
});
|
||||||
setActiveTab('district');
|
setActiveTab('district');
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectDistrict(district: string) {
|
function selectDistrict(district: string) {
|
||||||
|
if (shipping && district === REGION_ALL) return;
|
||||||
setDraft({ ...draft, district });
|
setDraft({ ...draft, district });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +170,13 @@ export default function RegionPicker({
|
|||||||
|
|
||||||
function handleConfirm() {
|
function handleConfirm() {
|
||||||
if (!canConfirm) return;
|
if (!canConfirm) return;
|
||||||
const next = levels === 2 ? toCityLevelRegion(draft) : normalizeRegionSelection(draft);
|
const next =
|
||||||
|
levels === 2
|
||||||
|
? toCityLevelRegion(draft)
|
||||||
|
: shipping
|
||||||
|
? normalizeShippingRegionSelection(draft)
|
||||||
|
: normalizeRegionSelection(draft);
|
||||||
|
if (shipping && (!next.district || next.district === REGION_ALL)) return;
|
||||||
onConfirm(next);
|
onConfirm(next);
|
||||||
onClose();
|
onClose();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,12 @@ export function getDistrictsForPicker(province: string, city: string): string[]
|
|||||||
return [REGION_ALL, ...getDistricts(province, city)];
|
return [REGION_ALL, ...getDistricts(province, city)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 收货地址:不含「全市」 */
|
||||||
|
export function getDistrictsForShippingPicker(province: string, city: string): string[] {
|
||||||
|
if (province === REGION_ALL || city === REGION_ALL) return [];
|
||||||
|
return [...getDistricts(province, city)];
|
||||||
|
}
|
||||||
|
|
||||||
export function formatRegion(province: string, city: string, district: string): string {
|
export function formatRegion(province: string, city: string, district: string): string {
|
||||||
if (!province) return '';
|
if (!province) return '';
|
||||||
if (province === REGION_ALL) return REGION_ALL;
|
if (province === REGION_ALL) return REGION_ALL;
|
||||||
@@ -96,6 +102,35 @@ export const DEFAULT_REGION: RegionSelection = {
|
|||||||
district: REGION_ALL,
|
district: REGION_ALL,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 收货地址默认:不预填伪区县,迫使用户选真实区县 */
|
||||||
|
export const DEFAULT_SHIPPING_REGION: RegionSelection = {
|
||||||
|
province: '河南省',
|
||||||
|
city: '郑州市',
|
||||||
|
district: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 收货场景:区县必须在省市区树内且非全市 */
|
||||||
|
export function normalizeShippingRegionSelection(selection: RegionSelection): RegionSelection {
|
||||||
|
const province = PROVINCES.includes(selection.province)
|
||||||
|
? selection.province
|
||||||
|
: DEFAULT_SHIPPING_REGION.province;
|
||||||
|
const cities = getCities(province);
|
||||||
|
const city = cities.includes(selection.city) ? selection.city : (cities[0] ?? DEFAULT_SHIPPING_REGION.city);
|
||||||
|
const districts = getDistricts(province, city);
|
||||||
|
const district =
|
||||||
|
selection.district &&
|
||||||
|
selection.district !== REGION_ALL &&
|
||||||
|
districts.includes(selection.district)
|
||||||
|
? selection.district
|
||||||
|
: '';
|
||||||
|
return { province, city, district };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isShippingRegionComplete(selection: RegionSelection): boolean {
|
||||||
|
const n = normalizeShippingRegionSelection(selection);
|
||||||
|
return Boolean(n.province && n.city && n.district && n.district !== REGION_ALL);
|
||||||
|
}
|
||||||
|
|
||||||
export function regionFromGeo(province: string, city: string, district?: string): RegionSelection {
|
export function regionFromGeo(province: string, city: string, district?: string): RegionSelection {
|
||||||
const cityName = city.endsWith('市') ? city : `${city}市`;
|
const cityName = city.endsWith('市') ? city : `${city}市`;
|
||||||
const provinceInTree = PROVINCES.includes(province) ? province : DEFAULT_REGION.province;
|
const provinceInTree = PROVINCES.includes(province) ? province : DEFAULT_REGION.province;
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import {
|
||||||
|
REGION_ALL,
|
||||||
|
isShippingRegionComplete,
|
||||||
|
normalizeShippingRegionSelection,
|
||||||
|
type RegionSelection,
|
||||||
|
} from './region-data';
|
||||||
|
|
||||||
|
export const SHIPPING_DETAIL_MIN_LEN = 8;
|
||||||
|
export const SHIPPING_REGION_REQUIRED_MSG = '请选择具体区县';
|
||||||
|
export const SHIPPING_DETAIL_REQUIRED_MSG = '请填写详细地址';
|
||||||
|
export const SHIPPING_DETAIL_TOO_SHORT_MSG = '请填写更详细的收货地址(含街道门牌)';
|
||||||
|
|
||||||
|
export type ShippingAddressLike = {
|
||||||
|
province?: string | null;
|
||||||
|
city?: string | null;
|
||||||
|
district?: string | null;
|
||||||
|
detail?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isDirtyShippingAddress(addr: ShippingAddressLike): boolean {
|
||||||
|
return !validateClientShippingAddress(addr).ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateClientShippingAddress(addr: ShippingAddressLike): {
|
||||||
|
ok: boolean;
|
||||||
|
message?: string;
|
||||||
|
} {
|
||||||
|
const province = String(addr.province ?? '').trim();
|
||||||
|
const city = String(addr.city ?? '').trim();
|
||||||
|
const district = String(addr.district ?? '').trim();
|
||||||
|
const detail = String(addr.detail ?? '').trim();
|
||||||
|
|
||||||
|
if (!province || !city) return { ok: false, message: '请选择所在地区' };
|
||||||
|
if (!district || district === REGION_ALL || district === '全部') {
|
||||||
|
return { ok: false, message: SHIPPING_REGION_REQUIRED_MSG };
|
||||||
|
}
|
||||||
|
const regionOk = isShippingRegionComplete({ province, city, district });
|
||||||
|
if (!regionOk) {
|
||||||
|
return { ok: false, message: SHIPPING_REGION_REQUIRED_MSG };
|
||||||
|
}
|
||||||
|
if (!detail) return { ok: false, message: SHIPPING_DETAIL_REQUIRED_MSG };
|
||||||
|
if (detail.length < SHIPPING_DETAIL_MIN_LEN) {
|
||||||
|
return { ok: false, message: SHIPPING_DETAIL_TOO_SHORT_MSG };
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shippingDetailCityWideHint(detail: string | null | undefined): string | null {
|
||||||
|
const d = String(detail ?? '').trim();
|
||||||
|
if (!d.includes('全市')) return null;
|
||||||
|
if (/路|街|巷|号|大厦|广场|小区|村|镇|乡/.test(d)) return null;
|
||||||
|
return '详细地址含「全市」,建议改为具体街道门牌,以免配送拒单';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toShippingRegion(addr: ShippingAddressLike): RegionSelection {
|
||||||
|
return normalizeShippingRegionSelection({
|
||||||
|
province: String(addr.province ?? ''),
|
||||||
|
city: String(addr.city ?? ''),
|
||||||
|
district: String(addr.district ?? ''),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -7,12 +7,16 @@ import SubPageHeader from '../../components/SubPageHeader';
|
|||||||
import RegionPicker from '../../components/RegionPicker';
|
import RegionPicker from '../../components/RegionPicker';
|
||||||
import { buildAddressListUrl, readCheckoutContext } from '../../lib/checkout-nav';
|
import { buildAddressListUrl, readCheckoutContext } from '../../lib/checkout-nav';
|
||||||
import {
|
import {
|
||||||
DEFAULT_REGION,
|
DEFAULT_SHIPPING_REGION,
|
||||||
REGION_ALL,
|
REGION_ALL,
|
||||||
formatRegion,
|
formatRegion,
|
||||||
type RegionSelection,
|
type RegionSelection,
|
||||||
} from '../../lib/region-data';
|
} from '../../lib/region-data';
|
||||||
import { normalizePhoneInput, validateMobilePhone } from '../../lib/phone';
|
import { normalizePhoneInput, validateMobilePhone } from '../../lib/phone';
|
||||||
|
import {
|
||||||
|
shippingDetailCityWideHint,
|
||||||
|
validateClientShippingAddress,
|
||||||
|
} from '../../lib/shipping-address';
|
||||||
import { getStoredUserPhone, resolveDefaultUserPhone } from '../../lib/user-phone';
|
import { getStoredUserPhone, resolveDefaultUserPhone } from '../../lib/user-phone';
|
||||||
import { resolveUserCity } from '../../lib/user-location';
|
import { resolveUserCity } from '../../lib/user-location';
|
||||||
import { request, toast, type UserProfile } from '../../lib/api';
|
import { request, toast, type UserProfile } from '../../lib/api';
|
||||||
@@ -36,12 +40,13 @@ export default function AddressEditPage() {
|
|||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [locating, setLocating] = useState(false);
|
const [locating, setLocating] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
const [hint, setHint] = useState('');
|
||||||
const [form, setForm] = useState<AddressForm>(() => ({
|
const [form, setForm] = useState<AddressForm>(() => ({
|
||||||
receiverName: '',
|
receiverName: '',
|
||||||
phone: id ? '' : getStoredUserPhone(),
|
phone: id ? '' : getStoredUserPhone(),
|
||||||
province: DEFAULT_REGION.province,
|
province: DEFAULT_SHIPPING_REGION.province,
|
||||||
city: DEFAULT_REGION.city,
|
city: DEFAULT_SHIPPING_REGION.city,
|
||||||
district: DEFAULT_REGION.district,
|
district: DEFAULT_SHIPPING_REGION.district,
|
||||||
detail: '',
|
detail: '',
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
}));
|
}));
|
||||||
@@ -69,7 +74,7 @@ export default function AddressEditPage() {
|
|||||||
? resolved.region.district
|
? resolved.region.district
|
||||||
: resolved.district && resolved.district !== REGION_ALL
|
: resolved.district && resolved.district !== REGION_ALL
|
||||||
? resolved.district
|
? resolved.district
|
||||||
: DEFAULT_REGION.district;
|
: '';
|
||||||
setForm((prev) => ({
|
setForm((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
province: resolved.region.province || prev.province,
|
province: resolved.region.province || prev.province,
|
||||||
@@ -91,12 +96,13 @@ export default function AddressEditPage() {
|
|||||||
request<Array<Record<string, unknown>>>('/user/addresses').then((list) => {
|
request<Array<Record<string, unknown>>>('/user/addresses').then((list) => {
|
||||||
const found = list.find((a) => String(a.id) === id);
|
const found = list.find((a) => String(a.id) === id);
|
||||||
if (found) {
|
if (found) {
|
||||||
|
const district = String(found.district ?? '');
|
||||||
setForm({
|
setForm({
|
||||||
receiverName: String(found.receiverName ?? ''),
|
receiverName: String(found.receiverName ?? ''),
|
||||||
phone: String(found.phone ?? ''),
|
phone: String(found.phone ?? ''),
|
||||||
province: String(found.province ?? DEFAULT_REGION.province),
|
province: String(found.province ?? DEFAULT_SHIPPING_REGION.province),
|
||||||
city: String(found.city ?? DEFAULT_REGION.city),
|
city: String(found.city ?? DEFAULT_SHIPPING_REGION.city),
|
||||||
district: String(found.district ?? DEFAULT_REGION.district),
|
district: district === REGION_ALL ? '' : district,
|
||||||
detail: String(found.detail ?? ''),
|
detail: String(found.detail ?? ''),
|
||||||
isDefault: found.isDefault === 1 || found.isDefault === true,
|
isDefault: found.isDefault === 1 || found.isDefault === true,
|
||||||
});
|
});
|
||||||
@@ -104,14 +110,21 @@ export default function AddressEditPage() {
|
|||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
||||||
const regionText = formatRegion(form.province, form.city, form.district);
|
useEffect(() => {
|
||||||
|
setHint(shippingDetailCityWideHint(form.detail) ?? '');
|
||||||
|
}, [form.detail]);
|
||||||
|
|
||||||
|
const regionText =
|
||||||
|
form.province && form.city && form.district
|
||||||
|
? formatRegion(form.province, form.city, form.district)
|
||||||
|
: '';
|
||||||
|
|
||||||
function validateForm(): string | null {
|
function validateForm(): string | null {
|
||||||
if (!form.receiverName.trim()) return '请输入收货人姓名';
|
if (!form.receiverName.trim()) return '请输入收货人姓名';
|
||||||
const phoneCheck = validateMobilePhone(form.phone);
|
const phoneCheck = validateMobilePhone(form.phone);
|
||||||
if (!phoneCheck.ok) return phoneCheck.message ?? '请输入正确的手机号码';
|
if (!phoneCheck.ok) return phoneCheck.message ?? '请输入正确的手机号码';
|
||||||
if (!form.province || !form.city || !form.district) return '请选择所在地区';
|
const shipping = validateClientShippingAddress(form);
|
||||||
if (!form.detail.trim()) return '请输入详细地址';
|
if (!shipping.ok) return shipping.message ?? '请完善收货地址';
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,7 +214,7 @@ export default function AddressEditPage() {
|
|||||||
<Text>
|
<Text>
|
||||||
{locating && !isEdit
|
{locating && !isEdit
|
||||||
? '定位中…'
|
? '定位中…'
|
||||||
: regionText || '请选择省市区'}
|
: regionText || '请选择省 / 市 / 区县'}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
@@ -228,6 +241,7 @@ export default function AddressEditPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
{hint ? <Text className="address-form-hint">{hint}</Text> : null}
|
||||||
<View className="address-form-row">
|
<View className="address-form-row">
|
||||||
<Text>设为默认地址</Text>
|
<Text>设为默认地址</Text>
|
||||||
<Switch
|
<Switch
|
||||||
@@ -248,6 +262,7 @@ export default function AddressEditPage() {
|
|||||||
onClose={() => setPickerOpen(false)}
|
onClose={() => setPickerOpen(false)}
|
||||||
onConfirm={onRegionConfirm}
|
onConfirm={onRegionConfirm}
|
||||||
levels={3}
|
levels={3}
|
||||||
|
mode="shipping"
|
||||||
/>
|
/>
|
||||||
</PageShell>
|
</PageShell>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
buildOrderConfirmUrl,
|
buildOrderConfirmUrl,
|
||||||
readCheckoutContext,
|
readCheckoutContext,
|
||||||
} from '../../lib/checkout-nav';
|
} from '../../lib/checkout-nav';
|
||||||
|
import { isDirtyShippingAddress } from '../../lib/shipping-address';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
|
||||||
type Address = {
|
type Address = {
|
||||||
@@ -51,6 +52,11 @@ export default function AddressesPage() {
|
|||||||
|
|
||||||
function selectAddress(addr: Address) {
|
function selectAddress(addr: Address) {
|
||||||
if (!selectMode) return;
|
if (!selectMode) return;
|
||||||
|
if (isDirtyShippingAddress(addr)) {
|
||||||
|
toast('该地址缺少具体区县,请先完善');
|
||||||
|
Taro.navigateTo({ url: buildAddressEditUrl(addr.id, checkoutCtx) }).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
Taro.redirectTo({
|
Taro.redirectTo({
|
||||||
url: buildOrderConfirmUrl({
|
url: buildOrderConfirmUrl({
|
||||||
productId: checkoutCtx.productId,
|
productId: checkoutCtx.productId,
|
||||||
@@ -76,6 +82,12 @@ export default function AddressesPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sorted = [...list].sort((a, b) => {
|
||||||
|
const da = isDirtyShippingAddress(a) ? 0 : 1;
|
||||||
|
const db = isDirtyShippingAddress(b) ? 0 : 1;
|
||||||
|
return da - db;
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="sub" className="address-page" hasFixedFooter>
|
<PageShell variant="sub" className="address-page" hasFixedFooter>
|
||||||
<SubPageHeader title={selectMode ? '选择收货地址' : '地址管理'} />
|
<SubPageHeader title={selectMode ? '选择收货地址' : '地址管理'} />
|
||||||
@@ -84,46 +96,55 @@ export default function AddressesPage() {
|
|||||||
{!loading && list.length === 0 ? (
|
{!loading && list.length === 0 ? (
|
||||||
<View className="u-empty">暂无收货地址</View>
|
<View className="u-empty">暂无收货地址</View>
|
||||||
) : null}
|
) : null}
|
||||||
{list.map((a) => (
|
{sorted.map((a) => {
|
||||||
<View
|
const dirty = isDirtyShippingAddress(a);
|
||||||
key={a.id}
|
return (
|
||||||
className="address-item"
|
<View
|
||||||
onClick={() => selectAddress(a)}
|
key={a.id}
|
||||||
>
|
className={`address-item${dirty ? ' address-item--dirty' : ''}`}
|
||||||
<View className="address-item-head">
|
onClick={() => selectAddress(a)}
|
||||||
<Text className="address-item-name">{a.receiverName}</Text>
|
>
|
||||||
<Text className="address-item-phone">{a.phone}</Text>
|
<View className="address-item-head">
|
||||||
{a.isDefault === 1 || a.isDefault === true ? (
|
<Text className="address-item-name">{a.receiverName}</Text>
|
||||||
<Text className="address-default-tag">默认</Text>
|
<Text className="address-item-phone">{a.phone}</Text>
|
||||||
|
{dirty ? <Text className="address-need-fix-tag">需完善</Text> : null}
|
||||||
|
{a.isDefault === 1 || a.isDefault === true ? (
|
||||||
|
<Text className="address-default-tag">默认</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
<Text className="address-item-detail">{formatAddress(a)}</Text>
|
||||||
|
{dirty ? (
|
||||||
|
<Text className="address-item-warn">缺少具体区县,同城配送可能失败,请编辑完善</Text>
|
||||||
|
) : null}
|
||||||
|
{!selectMode || dirty ? (
|
||||||
|
<View className="address-item-actions">
|
||||||
|
<Text
|
||||||
|
className="address-action"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
Taro.navigateTo({ url: buildAddressEditUrl(a.id, checkoutCtx) }).catch((err) => {
|
||||||
|
toast(err instanceof Error ? err.message : '无法打开编辑页');
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{dirty ? '去完善' : '编辑'}
|
||||||
|
</Text>
|
||||||
|
{!selectMode ? (
|
||||||
|
<Text
|
||||||
|
className="address-action"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
void removeAddress(a.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
<Text className="address-item-detail">{formatAddress(a)}</Text>
|
);
|
||||||
{!selectMode ? (
|
})}
|
||||||
<View className="address-item-actions">
|
|
||||||
<Text
|
|
||||||
className="address-action"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
Taro.navigateTo({ url: buildAddressEditUrl(a.id, checkoutCtx) }).catch((err) => {
|
|
||||||
toast(err instanceof Error ? err.message : '无法打开编辑页');
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
编辑
|
|
||||||
</Text>
|
|
||||||
<Text
|
|
||||||
className="address-action"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
void removeAddress(a.id);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
删除
|
|
||||||
</Text>
|
|
||||||
</View>
|
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
</View>
|
||||||
<View
|
<View
|
||||||
className="address-fab"
|
className="address-fab"
|
||||||
|
|||||||
@@ -196,6 +196,17 @@ export default function HomePage() {
|
|||||||
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function goBuyOnline(productId: string) {
|
||||||
|
const returnPath = `/pages/order-confirm/index?productId=${productId}&qty=2`;
|
||||||
|
if (!isLoggedIn()) {
|
||||||
|
goLogin(returnPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ready = await ensurePayReady(returnPath);
|
||||||
|
if (!ready) return;
|
||||||
|
Taro.navigateTo({ url: returnPath });
|
||||||
|
}
|
||||||
|
|
||||||
async function goOnSitePickup(productId: string) {
|
async function goOnSitePickup(productId: string) {
|
||||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=2`;
|
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=2`;
|
||||||
if (!isLoggedIn()) {
|
if (!isLoggedIn()) {
|
||||||
@@ -348,7 +359,7 @@ export default function HomePage() {
|
|||||||
className="home-buy-btn"
|
className="home-buy-btn"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation?.();
|
e.stopPropagation?.();
|
||||||
openProductDetail(p.id);
|
void goBuyOnline(p.id);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
立即购买
|
立即购买
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import DeliveryHintHtml from '../../components/DeliveryHintHtml';
|
|||||||
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
||||||
import { loadLocalDeliveries, matchLocalDelivery, resolveLocalDeliveryHintHtml } from '../../lib/local-delivery';
|
import { loadLocalDeliveries, matchLocalDelivery, resolveLocalDeliveryHintHtml } from '../../lib/local-delivery';
|
||||||
import { getProductMainImage } from '../../lib/product-images';
|
import { getProductMainImage } from '../../lib/product-images';
|
||||||
|
import { isDirtyShippingAddress } from '../../lib/shipping-address';
|
||||||
import BenefitFigure from '../../components/BenefitFigure';
|
import BenefitFigure from '../../components/BenefitFigure';
|
||||||
import OrderQtyControls from '../../components/OrderQtyControls';
|
import OrderQtyControls from '../../components/OrderQtyControls';
|
||||||
|
|
||||||
@@ -177,7 +178,12 @@ export default function OrderConfirmPage() {
|
|||||||
const isCross =
|
const isCross =
|
||||||
forceCross || preview?.deliveryType === 'CROSS_CITY' || localCross;
|
forceCross || preview?.deliveryType === 'CROSS_CITY' || localCross;
|
||||||
const crossBlocked = isCross && !allowCross;
|
const crossBlocked = isCross && !allowCross;
|
||||||
const addressOk = preview ? preview.addressOk !== false && !crossBlocked : !crossBlocked;
|
const dirtyAddress = !!selectedAddress && isDirtyShippingAddress(selectedAddress);
|
||||||
|
const addressOk = dirtyAddress
|
||||||
|
? false
|
||||||
|
: preview
|
||||||
|
? preview.addressOk !== false && !crossBlocked
|
||||||
|
: !crossBlocked;
|
||||||
const unitLabel = preview?.saleUnit === 'BOX' ? '箱' : '瓶';
|
const unitLabel = preview?.saleUnit === 'BOX' ? '箱' : '瓶';
|
||||||
const minQty =
|
const minQty =
|
||||||
preview?.minQty ??
|
preview?.minQty ??
|
||||||
@@ -186,9 +192,11 @@ export default function OrderConfirmPage() {
|
|||||||
const canSubmit =
|
const canSubmit =
|
||||||
!!addressId && !!preview && quantityOk && addressOk && !loading && !previewLoading;
|
!!addressId && !!preview && quantityOk && addressOk && !loading && !previewLoading;
|
||||||
|
|
||||||
const addressHint = !addressOk
|
const addressHint = dirtyAddress
|
||||||
? preview?.addressMessage || CROSS_CITY_BLOCK_MSG
|
? '请完善收货地址(需选择具体区县)'
|
||||||
: '';
|
: !addressOk
|
||||||
|
? preview?.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||||
|
: '';
|
||||||
|
|
||||||
function updateQuantity(next: number) {
|
function updateQuantity(next: number) {
|
||||||
if (next < minQty) {
|
if (next < minQty) {
|
||||||
|
|||||||
@@ -38,6 +38,34 @@
|
|||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.address-need-fix-tag {
|
||||||
|
margin-left: 8px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(200, 120, 20, 0.12);
|
||||||
|
color: #b36b00;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.address-item--dirty {
|
||||||
|
border: 1px solid rgba(200, 120, 20, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.address-item-warn {
|
||||||
|
display: block;
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #b36b00;
|
||||||
|
}
|
||||||
|
|
||||||
|
.address-form-hint {
|
||||||
|
display: block;
|
||||||
|
margin: 0 var(--space-page) 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #b36b00;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
.address-item-detail {
|
.address-item-detail {
|
||||||
display: block;
|
display: block;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
|
|||||||
@@ -191,7 +191,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.order-qty-unit {
|
.order-qty-unit {
|
||||||
margin-right: 8px;
|
margin-left: 8px;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--color-on-surface);
|
color: var(--color-on-surface);
|
||||||
|
|||||||
@@ -34,6 +34,7 @@
|
|||||||
| 3.5.11 | 08-26 | 城市三种履约起购;企微通知补提交人/规格物流/核销用户(明文手机+备注);结算任务失败通知 + 提现通过/四账单(城市合伙人、笔数、累计金额) | [`v3.5.11`](./杜康好客-v3.5.11-开发文档.md) |
|
| 3.5.11 | 08-26 | 城市三种履约起购;企微通知补提交人/规格物流/核销用户(明文手机+备注);结算任务失败通知 + 提现通过/四账单(城市合伙人、笔数、累计金额) | [`v3.5.11`](./杜康好客-v3.5.11-开发文档.md) |
|
||||||
| 3.5.12 | 08-26 | 发布会订单大屏循环 BGM;HQ 日志/订单状态流转/用户行为时间线展示中文;修复删除门店分类被默认树回种;HQ 侧栏顺序(业务前 11 项,系统设置置底) | [`v3.5.12`](./杜康好客-v3.5.12-开发文档.md) |
|
| 3.5.12 | 08-26 | 发布会订单大屏循环 BGM;HQ 日志/订单状态流转/用户行为时间线展示中文;修复删除门店分类被默认树回种;HQ 侧栏顺序(业务前 11 项,系统设置置底) | [`v3.5.12`](./杜康好客-v3.5.12-开发文档.md) |
|
||||||
| 3.5.14 | 08-26 | 修复 C 端提交订单/支付成功日志误标 H5;线上 `order_submit`/`pay_success` 回填为小程序 | [`v3.5.14`](./杜康好客-v3.5.14-开发文档.md) |
|
| 3.5.14 | 08-26 | 修复 C 端提交订单/支付成功日志误标 H5;线上 `order_submit`/`pay_success` 回填为小程序 | [`v3.5.14`](./杜康好客-v3.5.14-开发文档.md) |
|
||||||
|
| 3.5.15 | 09-02 | 企微机器人「报告」:日报/周报/月报;Webhook 与消息推送分开 | [`v3.5.15`](./杜康好客-v3.5.15-开发文档.md) |
|
||||||
|
|
||||||
**4.0 起**不再写入本表,见 [`v4-PRD`](./杜康好客-v4-PRD.md)。
|
**4.0 起**不再写入本表,见 [`v4-PRD`](./杜康好客-v4-PRD.md)。
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@
|
|||||||
| **mini-user** | 购酒/权益/核销/门店/物流/版本门控 | 规则弹窗、发票、四类型工单、问卷 |
|
| **mini-user** | 购酒/权益/核销/门店/物流/版本门控 | 规则弹窗、发票、四类型工单、问卷 |
|
||||||
| **h5-shop** | 扫码核销、记录、营业、iOS 扫码 OAuth | 手机号核销、提现、子账号、弱网兜底 |
|
| **h5-shop** | 扫码核销、记录、营业、iOS 扫码 OAuth | 手机号核销、提现、子账号、弱网兜底 |
|
||||||
| **h5-partner** | 子账号、拓店、订单/账单、套餐 | 试核销100、负责人复核、代下单 |
|
| **h5-partner** | 子账号、拓店、订单/账单、套餐 | 试核销100、负责人复核、代下单 |
|
||||||
| **admin-web** | 商品/开城/门店/订单(含 Excel/PDF 导出)/权益/核销/结算/推广码 metrics/开发计划/技术支持 | 完整 SOP 审核 UI、发票、热力图 |
|
| **admin-web** | 商品/开城/门店/订单(含 Excel/PDF 导出)/权益/核销/结算/推广码 metrics/开发计划/技术支持/企微报告 | 完整 SOP 审核 UI、发票、热力图 |
|
||||||
| **后端** | 主模块、支付、权益、核销、payout、Courier 适配 | 30min 取消 job、部分 Wave3 |
|
| **后端** | 主模块、支付、权益、核销、payout、Courier 适配 | 30min 取消 job、部分 Wave3 |
|
||||||
|
|
||||||
## 3. 场景 SC-01~09
|
## 3. 场景 SC-01~09
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# 杜康好客 · v3.5.15 开发文档
|
||||||
|
|
||||||
|
> **2026-09-02** · ops / admin-web / domain / shared-types
|
||||||
|
> **主题**:企微机器人增加经营报告(日报 / 周报 / 月报)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 版本目标
|
||||||
|
|
||||||
|
| # | 任务 | 类型 | 交付 |
|
||||||
|
|---|------|------|------|
|
||||||
|
| 1 | 报告模块 | 需求 | HQ「企微机器人 → 报告」,与「消息推送」分开 |
|
||||||
|
| 2 | 三种报 | 需求 | 日报、周报、月报:存量 + 本期新增 |
|
||||||
|
| 3 | 推送 | 需求 | 企微群机器人 Webhook markdown;可预览 / 立即发送 / 定时 |
|
||||||
|
|
||||||
|
**不做**:并入消息推送条件、新权限键、城市范围裁剪、同比。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 规则
|
||||||
|
|
||||||
|
配置在报告页,每种报一份 Webhook / 启用 / 发送时刻(周报另选星期,月报另选每月几号)。不占用「消息推送」的事件条件。
|
||||||
|
|
||||||
|
口径(北京日历,与概览折线一致):
|
||||||
|
|
||||||
|
| 指标 | 存量 | 新增 |
|
||||||
|
|------|------|------|
|
||||||
|
| 用户数量 | `status=1` 且未合并,`createdAt` < 期末 | 区间内创建 |
|
||||||
|
| 合伙人数量 | 主账号 `is_primary=1` | 区间内创建 |
|
||||||
|
| 门店数量 | 全部门店 | 区间内创建 |
|
||||||
|
| 订单数量 | 按下单 `createdAt` | 区间内下单 |
|
||||||
|
| 订单金额 | 已付 `payAmount`(`paidAt`) | 区间内支付 |
|
||||||
|
| 核销单数量 / 金额 | `RedeemRecord` | 区间内核销 |
|
||||||
|
|
||||||
|
- **日报**:当天;默认 20:00 发送;新增文案「当日新增」。
|
||||||
|
- **周报**:上一自然周(周一~周日);默认周一 09:00。
|
||||||
|
- **月报**:上一自然月;默认每月 1 日 09:00。
|
||||||
|
|
||||||
|
错过发送时刻会在之后补发一次(按 `last_sent_period` 去重)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. API
|
||||||
|
|
||||||
|
`GET /admin/wecom-reports`
|
||||||
|
`GET/PUT /admin/wecom-reports/:kind`(`daily` \| `weekly` \| `monthly`)
|
||||||
|
`POST /admin/wecom-reports/:kind/preview`
|
||||||
|
`POST /admin/wecom-reports/:kind/send`
|
||||||
|
|
||||||
|
权限:`wecom_bots`。
|
||||||
|
|
||||||
|
表 `wecom_report_push`(`kind` 唯一)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 变更面
|
||||||
|
|
||||||
|
| 层 | 路径 |
|
||||||
|
|----|------|
|
||||||
|
| domain | `wecom-report.ts` |
|
||||||
|
| shared-types | `wecom-report.ts` |
|
||||||
|
| Prisma | `WecomReportPush`;`prisma/migrate-wecom-report.ts` |
|
||||||
|
| API | `admin-wecom-reports.*` |
|
||||||
|
| HQ | `WecomReportsPage.tsx`;侧栏「报告」 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [ ] 侧栏企微机器人下有「报告」,与消息推送分开
|
||||||
|
- [ ] 日报/周报/月报可分别填 Webhook、启停、时刻并保存
|
||||||
|
- [ ] 预览文案含用户/合伙人/门店/订单数量与金额/核销数量与金额的存量+新增
|
||||||
|
- [ ] 立即发送走该报自己的 Webhook,不触发消息推送事件
|
||||||
|
- [ ] 启用后到达时刻只发一次该周期
|
||||||
+5
-1
@@ -1,7 +1,7 @@
|
|||||||
# 杜康好客 · V3 编码手册(交付业务版)
|
# 杜康好客 · V3 编码手册(交付业务版)
|
||||||
|
|
||||||
> **事实源**:[`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md) · **审计**:[`杜康好客-v3-现状对照.md`](./杜康好客-v3-现状对照.md)
|
> **事实源**:[`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md) · **审计**:[`杜康好客-v3-现状对照.md`](./杜康好客-v3-现状对照.md)
|
||||||
> **佣金归属 / 关联码 / 合伙人账单明细(v4.0.1)· 活动图(v4.0.2)· 周结算与预付款(v4.0.9)**:[`杜康好客-v4-PRD.md`](./杜康好客-v4-PRD.md),冲突时 **V4 > V3**。
|
> **佣金归属 / 关联码 / 合伙人账单明细(v4.0.1)· 活动图(v4.0.2)· 周结算与预付款(v4.0.9)· HQ 概览(v4.0.14 / v4.0.15)**:[`杜康好客-v4-PRD.md`](./杜康好客-v4-PRD.md),冲突时 **V4 > V3**。
|
||||||
> V2/preV1 **非需求依据**。总部交付 = **`apps/admin-web`**(非 H5)。
|
> V2/preV1 **非需求依据**。总部交付 = **`apps/admin-web`**(非 H5)。
|
||||||
|
|
||||||
## 1. 交付目标(六条)
|
## 1. 交付目标(六条)
|
||||||
@@ -44,6 +44,10 @@ C 端购酒核销 · 门店扫码核销+打款 · 合伙人拓店履约 · WebAd
|
|||||||
|
|
||||||
**HQ 权限(v3.5.8)**:生效 =(角色 ∪ 追加)− 撤销。城市范围绑在账号上(空=全国;「城市门店服务」必须勾城)。门店 API 按 `cityIds` 强制过滤。城市门店服务可新增分类、不可删除;概览按权限与城市范围裁剪。
|
**HQ 权限(v3.5.8)**:生效 =(角色 ∪ 追加)− 撤销。城市范围绑在账号上(空=全国;「城市门店服务」必须勾城)。门店 API 按 `cityIds` 强制过滤。城市门店服务可新增分类、不可删除;概览按权限与城市范围裁剪。
|
||||||
|
|
||||||
|
**HQ 概览(v4.0.14 / v4.0.15)**:`GET /admin/dashboard/analytics` 支持日/周/月/季/年分桶;默认窗口为上一档起点~今天。全局筛城市+时间;日期快捷上周/上月/上季度;总量/增量单选分开展示。改粒度不改日期。查询右侧可下载当前折线图 PDF(不含 KPI/待办)。v4.0.15 起为多张全宽折线图:总量=桶末日存量,增量=桶内新增;用户线=推广码/关联合伙人/活动,门店线=关联合伙人,订单线=用户/关联合伙人/商品,核销线=门店/关联合伙人,合伙人单线。订单与核销同时出笔数和金额。关联合伙人=`assoc_partner_account_id`;活动=关联合伙人当前活动图。「查看」只带全局城市与日期。无权限模块后端不算不返回。时间按北京日历。
|
||||||
|
|
||||||
|
**HQ 企微报告(v3.5.15)**:企微机器人下「报告」与「消息推送」分开。日报/周报/月报各配 Webhook 与发送时刻;走群机器人 markdown。日报=当天存量+当日新增;周报/月报=上一自然周/月期末存量+本期新增。用户=有效未合并;合伙人=主账号;订单金额=已付 `payAmount`(`paidAt`);核销=`RedeemRecord`。
|
||||||
|
|
||||||
**HQ 列表(v3.5.9)**:主表不省略号、可横滑;最左序号;列设置(显隐/顺序)与列宽(拖表头)存 `hq_account.list_column_prefs`。主展示列下划线,点击进编辑或详情。门店列表「累计核销好客权益」= 该店 `RedeemRecord.amount` 合计。用户列表昵称只读(点击进详情);双击「备注」离开即保存(`hq_remark`);列表手机号不脱敏。
|
**HQ 列表(v3.5.9)**:主表不省略号、可横滑;最左序号;列设置(显隐/顺序)与列宽(拖表头)存 `hq_account.list_column_prefs`。主展示列下划线,点击进编辑或详情。门店列表「累计核销好客权益」= 该店 `RedeemRecord.amount` 合计。用户列表昵称只读(点击进详情);双击「备注」离开即保存(`hq_remark`);列表手机号不脱敏。
|
||||||
|
|
||||||
**C 端(v3.5.10)**:门店详情无顶栏分享按钮。同城送提示取开城仓库绑定承运商的 `delivery_hint_html`(`GET /catalog/local-deliveries`,按收货市是否开城);空则回退「同城配送,预计24小时内送到」。在线客服优先 `wx.openCustomerServiceChat`(`CUSTOMER_SERVICE_WECOM_URL` + `WECOM_CORP_ID`);未配 CorpID 回退小程序原生客服。
|
**C 端(v3.5.10)**:门店详情无顶栏分享按钮。同城送提示取开城仓库绑定承运商的 `delivery_hint_html`(`GET /catalog/local-deliveries`,按收货市是否开城);空则回退「同城配送,预计24小时内送到」。在线客服优先 `wx.openCustomerServiceChat`(`CUSTOMER_SERVICE_WECOM_URL` + `WECOM_CORP_ID`);未配 CorpID 回退小程序原生客服。
|
||||||
|
|||||||
+5
-3
@@ -1,8 +1,8 @@
|
|||||||
# 杜康好客 · V4 PRD
|
# 杜康好客 · V4 PRD
|
||||||
|
|
||||||
> **v4.0**(2026-08-29)· 关联码与分佣事实源;**v4.0.6** 酒厂对账;**v4.0.7** HQ 活动图快链与勾选导出;**v4.0.9** 合伙人 H5 周结算与用户管理
|
> **v4.0**(2026-08-29)· 关联码与分佣事实源;**v4.0.6** 酒厂对账;**v4.0.7** HQ 活动图快链与勾选导出;**v4.0.9** 合伙人 H5 周结算与用户管理;**v4.0.14** HQ 概览粒度;**v4.0.15** HQ 概览折线图
|
||||||
> 未改规则仍见 [`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md)。**冲突时 V4 > V3**(本主题:订单佣金归属、关联码、合伙人账单明细、活动图、酒厂对账、合伙人周结算)。
|
> 未改规则仍见 [`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md)。**冲突时 V4 > V3**(本主题:订单佣金归属、关联码、合伙人账单明细、活动图、酒厂对账、合伙人周结算、HQ 概览)。
|
||||||
> 实现:[`v4.0.1 开发文档`](./杜康好客-v4.0.1-开发文档.md) · [`v4.0.2 开发文档`](./杜康好客-v4.0.2-开发文档.md) · [`v4.0.6 开发文档`](./杜康好客-v4.0.6-开发文档.md) · [`v4.0.7 开发文档`](./杜康好客-v4.0.7-开发文档.md) · [`v4.0.9 开发文档`](./杜康好客-v4.0.9-开发文档.md) · 审计:[`v4-现状对照`](./杜康好客-v4-现状对照.md)
|
> 实现:[`v4.0.1 开发文档`](./杜康好客-v4.0.1-开发文档.md) · [`v4.0.2 开发文档`](./杜康好客-v4.0.2-开发文档.md) · [`v4.0.6 开发文档`](./杜康好客-v4.0.6-开发文档.md) · [`v4.0.7 开发文档`](./杜康好客-v4.0.7-开发文档.md) · [`v4.0.9 开发文档`](./杜康好客-v4.0.9-开发文档.md) · [`v4.0.14 开发文档`](./杜康好客-v4.0.14-开发文档.md) · [`v4.0.15 开发文档`](./杜康好客-v4.0.15-开发文档.md) · 审计:[`v4-现状对照`](./杜康好客-v4-现状对照.md)
|
||||||
|
|
||||||
## 0. 版本
|
## 0. 版本
|
||||||
|
|
||||||
@@ -13,6 +13,8 @@
|
|||||||
| 4.0.6 | 08-31 | 酒厂 T+3=每 3 天出一期;全部已完成已付订单(含现场提货);应付为 0 仍出账;核对补生成 | [`v4.0.6`](./杜康好客-v4.0.6-开发文档.md) |
|
| 4.0.6 | 08-31 | 酒厂 T+3=每 3 天出一期;全部已完成已付订单(含现场提货);应付为 0 仍出账;核对补生成 | [`v4.0.6`](./杜康好客-v4.0.6-开发文档.md) |
|
||||||
| 4.0.7 | 09-01 | HQ 城市合伙人活动图快链;指定一张活动图为单个或勾选主合伙人合成下载(PNG / zip) | [`v4.0.7`](./杜康好客-v4.0.7-开发文档.md) |
|
| 4.0.7 | 09-01 | HQ 城市合伙人活动图快链;指定一张活动图为单个或勾选主合伙人合成下载(PNG / zip) | [`v4.0.7`](./杜康好客-v4.0.7-开发文档.md) |
|
||||||
| 4.0.9 | 09-02 | 子账号默认启用;关联码已扫码计数;零元账单不同步;主账号自填银行账号;周账周一 08:00 出账;预付款预估;子账号用户管理(无活动图) | [`v4.0.9`](./杜康好客-v4.0.9-开发文档.md) |
|
| 4.0.9 | 09-02 | 子账号默认启用;关联码已扫码计数;零元账单不同步;主账号自填银行账号;周账周一 08:00 出账;预付款预估;子账号用户管理(无活动图) | [`v4.0.9`](./杜康好客-v4.0.9-开发文档.md) |
|
||||||
|
| 4.0.14 | 09-02 | HQ 概览:日/周/月/季/年、环比、全局城市/时间 + 五板块筛;订单/核销笔数与金额 | [`v4.0.14`](./杜康好客-v4.0.14-开发文档.md) |
|
||||||
|
| 4.0.15 | 09-02 | HQ 概览改为全宽折线图:粒度分桶、总量/增量、维度线条;查看快链只带全局筛选 | [`v4.0.15`](./杜康好客-v4.0.15-开发文档.md) |
|
||||||
|
|
||||||
## 1. 锚点(沿用 V3,佣金归属改写)
|
## 1. 锚点(沿用 V3,佣金归属改写)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
| 维度 | 结论 |
|
| 维度 | 结论 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| 版本线 | **v4.0.9** 合伙人 H5 周结算、预付款、子账号用户管理 |
|
| 版本线 | **v4.0.15** HQ 概览折线图(粒度分桶、总量/增量、维度线条) |
|
||||||
| 订单佣金 | 区县归属已删除;只认关联 / 代下单选择 |
|
| 订单佣金 | 区县归属已删除;只认关联 / 代下单选择 |
|
||||||
| 账单 | 酒订单 / 核销订单分列;合伙人改为周账(周一 08:00);零元不同步合伙人;酒厂含现场提货,零应付仍出账(无需打款) |
|
| 账单 | 酒订单 / 核销订单分列;合伙人改为周账(周一 08:00);零元不同步合伙人;酒厂含现场提货,零应付仍出账(无需打款) |
|
||||||
| 活动图 | HQ 上传底图/码栏/文案;合伙人选择写入库;HQ 可指定一张图为勾选主合伙人合成下载;子账号不可看活动图 |
|
| 活动图 | HQ 上传底图/码栏/文案;合伙人选择写入库;HQ 可指定一张图为勾选主合伙人合成下载;子账号不可看活动图 |
|
||||||
@@ -21,6 +21,9 @@
|
|||||||
| 4.0.6 | [`酒厂对账核对`](./杜康好客-v4.0.6-开发文档.md) | ✅ 已实现 |
|
| 4.0.6 | [`酒厂对账核对`](./杜康好客-v4.0.6-开发文档.md) | ✅ 已实现 |
|
||||||
| 4.0.7 | [`活动图快链与勾选导出`](./杜康好客-v4.0.7-开发文档.md) | ✅ 已实现 |
|
| 4.0.7 | [`活动图快链与勾选导出`](./杜康好客-v4.0.7-开发文档.md) | ✅ 已实现 |
|
||||||
| 4.0.9 | [`合伙人 H5 周结算与用户管理`](./杜康好客-v4.0.9-开发文档.md) | ✅ 已实现 |
|
| 4.0.9 | [`合伙人 H5 周结算与用户管理`](./杜康好客-v4.0.9-开发文档.md) | ✅ 已实现 |
|
||||||
|
| 4.0.13 | [`收货地址把关与拒单可感知`](./杜康好客-v4.0.13-开发文档.md) | ✅ 已实现 |
|
||||||
|
| 4.0.14 | [`HQ 概览粒度与环比`](./杜康好客-v4.0.14-开发文档.md) | ✅ 已实现 |
|
||||||
|
| 4.0.15 | [`HQ 概览折线图`](./杜康好客-v4.0.15-开发文档.md) | ✅ 已实现 |
|
||||||
|
|
||||||
| 日期 | 说明 |
|
| 日期 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
@@ -31,3 +34,6 @@
|
|||||||
| 2026-08-31 | v4.0.6:酒厂 T+3=每 3 天出一期(非每日);含现场提货;零应付仍出账;核对补生成 |
|
| 2026-08-31 | v4.0.6:酒厂 T+3=每 3 天出一期(非每日);含现场提货;零应付仍出账;核对补生成 |
|
||||||
| 2026-09-01 | v4.0.7:HQ 城市合伙人活动图快链;单张/勾选导出合成图(PNG / zip) |
|
| 2026-09-01 | v4.0.7:HQ 城市合伙人活动图快链;单张/勾选导出合成图(PNG / zip) |
|
||||||
| 2026-09-02 | v4.0.9:子账号默认启用;关联码已扫码;零元账单不同步;银行账号自填;周账周一 08:00;预付款预估;子账号用户管理无活动图 |
|
| 2026-09-02 | v4.0.9:子账号默认启用;关联码已扫码;零元账单不同步;银行账号自填;周账周一 08:00;预付款预估;子账号用户管理无活动图 |
|
||||||
|
| 2026-09-02 | v4.0.13:收货禁「全市」;脏地址下单拦截;小飞侠超区/推单失败挂 `fulfillmentHold`(不做仓/收件坐标) |
|
||||||
|
| 2026-09-02 | v4.0.14:HQ 概览日/周/月/季/年、环比;全局城市/时间 + 五板块筛;订单/核销笔数与金额 |
|
||||||
|
| 2026-09-02 | v4.0.15:HQ 概览改为全宽折线图;去掉板块筛;查看快链只带全局城市与日期 |
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# 杜康好客 · v4.0.13 开发文档
|
||||||
|
|
||||||
|
> **2026-09-02** · mini-user / iam / trade / fulfillment / admin-web / h5-partner / domain
|
||||||
|
> **主题**:收货地址严格把关(禁「全市」)+ 小飞侠拒单履约可感知
|
||||||
|
|
||||||
|
需求背景:订单 `DK2026090220803` 自动推小飞侠失败,原因 `超出服务区`;收货区县为门店筛选用伪值「全市」。
|
||||||
|
|
||||||
|
**不做(本版明确排除)**:仓坐标补全、收件 `chooseLocation` / `toCoordinate` 坐标链路。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 版本目标
|
||||||
|
|
||||||
|
| # | 任务 | 类型 | 交付 |
|
||||||
|
|---|------|------|------|
|
||||||
|
| 1 | 收货选区与门店筛选语义拆分 | 缺陷/体验 | `RegionPicker mode=shipping` 无「全市」 |
|
||||||
|
| 2 | 地址保存硬闸 | 缺陷 | 前后端拒伪区县;详细地址最短 8 字 |
|
||||||
|
| 3 | 下单/预览拦截脏地址 | 缺陷 | preview `addressOk=false`;确认页不可提交 |
|
||||||
|
| 4 | 地址簿存量提示 | 体验 | 「需完善」置顶;结账选址强制去编辑 |
|
||||||
|
| 5 | 推单失败可感知 | 缺陷 | `fulfillmentHold` + 原因码;HQ 标签/发货弹窗 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 规则
|
||||||
|
|
||||||
|
### 2.1 收货地址
|
||||||
|
|
||||||
|
- 伪区县:`全市`、`全部`、空 —— **禁止**写入 `user_address` / 下单快照 / 合伙人代下单。
|
||||||
|
- 详细地址:必填且长度 ≥ 8;含「全市」且无街道路牌关键词时前端软提示(不单独硬失败)。
|
||||||
|
- 门店列表筛选仍可使用「全市」(`mode=filter`)。
|
||||||
|
- 现场取货地址快照(`现场/现场/取货`)不走本校验。
|
||||||
|
|
||||||
|
### 2.2 履约拦截(推单失败)
|
||||||
|
|
||||||
|
| `fulfillment_hold_reason` | 含义 | HQ 展示 |
|
||||||
|
|---------------------------|------|---------|
|
||||||
|
| `LARGE_ORDER_GE_10_BOXES` | 大单≥10箱 | 大单 |
|
||||||
|
| `COURIER_OUT_OF_SERVICE` | 小飞侠返回超出服务区 | 超区 |
|
||||||
|
| `COURIER_DISPATCH_FAILED` | 其它自动推单失败 | 推单失败 |
|
||||||
|
|
||||||
|
- 失败后仍写 `MANUAL` 配送记录(待发货),**同时**挂 `fulfillmentHold`,避免静默像「没推过」。
|
||||||
|
- HQ 手动推小飞侠或填快递成功后仍清 hold(既有逻辑)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 变更面
|
||||||
|
|
||||||
|
| 层 | 路径 |
|
||||||
|
|----|------|
|
||||||
|
| domain | `packages/domain/src/shipping-address.ts` |
|
||||||
|
| shared-types | `FULFILLMENT_HOLD_REASON_LABELS` + 常量 |
|
||||||
|
| API | `UserAddressService`;`TradeService` preview/create/代下单;`FulfillmentService.markCourierDispatchHold` |
|
||||||
|
| C 端 | `RegionPicker`、`address-edit`、`addresses`、`order-confirm`、`shipping-address.ts` |
|
||||||
|
| 合伙人 | `ProxyOrderPage` 校验 |
|
||||||
|
| HQ | `OrdersPage` 拦截筛选文案与标签 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. API 行为变化
|
||||||
|
|
||||||
|
| 接口 | 变化 |
|
||||||
|
|------|------|
|
||||||
|
| `POST/PUT /user/addresses` | 伪区县 / 详情过短 → `400` |
|
||||||
|
| `POST /trade/orders/preview` | 脏地址 → `addressOk=false` + message |
|
||||||
|
| `POST /trade/orders` | 脏地址 → `400` |
|
||||||
|
| 合伙人代下单 | 同上校验 |
|
||||||
|
| 支付后自动推单 | 失败写 hold reason(库字段,无新 path) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [ ] 新增/编辑地址:区县列表无「全市」;选真实区县 + 足够详细地址可保存
|
||||||
|
- [ ] 保存「全市」或过短详情被拒(前端 toast + 后端 400)
|
||||||
|
- [ ] 历史脏地址在地址簿标「需完善」;结账选择时跳转编辑
|
||||||
|
- [ ] 确认订单页脏地址不可提交;preview 提示完善区县
|
||||||
|
- [ ] 合伙人代下单伪区县/过短详情被拒
|
||||||
|
- [ ] 模拟小飞侠「超出服务区」后:订单 `fulfillment_hold=1`、`reason=COURIER_OUT_OF_SERVICE`;HQ 列表「超区」、发货弹窗有说明
|
||||||
|
- [ ] 门店列表筛选「全市」行为不变
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 存量建议(运维,非代码)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 生产排查脏地址(只读)
|
||||||
|
SELECT id, user_id, province, city, district, detail, updated_at
|
||||||
|
FROM user_address
|
||||||
|
WHERE district IN ('全市','全部','') OR district IS NULL
|
||||||
|
ORDER BY id DESC LIMIT 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
可选:运营通知用户进「地址管理」完善;本版不自动改写历史行。
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# 杜康好客 · v4.0.14 开发文档
|
||||||
|
|
||||||
|
> **2026-09-02** · ops / admin-web / domain / shared-types
|
||||||
|
> **主题**:HQ 概览日/周/月/季/年分桶、环比、板块筛、订单/核销金额
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 版本目标
|
||||||
|
|
||||||
|
| # | 任务 | 类型 | 交付 |
|
||||||
|
|---|------|------|------|
|
||||||
|
| 1 | 时间粒度 | 体验 | `day/week/month/quarter/year` + 自选日期 |
|
||||||
|
| 2 | 环比 | 需求 | 整段按粒度回退一档;上期 0 且本期 0 为 `—`,本期 > 0 为 `+100%` |
|
||||||
|
| 3 | 筛选分层 | 体验 | 全局只筛城市 + 时间;五板块各自筛选 |
|
||||||
|
| 4 | 金额 | 需求 | 订单/核销同时出笔数与金额 |
|
||||||
|
| 5 | 权限 | 安全 | 无权限模块后端不算不返回;城市范围只看负责城 |
|
||||||
|
|
||||||
|
**不做**:同比、测试单开关、新权限键、Prisma 迁移。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 规则
|
||||||
|
|
||||||
|
### 2.1 筛选分层
|
||||||
|
|
||||||
|
**全局**:粒度 + 日期 + 城市。环比窗口仍按全局日期、按粒度回退一档。
|
||||||
|
|
||||||
|
**板块筛**(只影响本板块 KPI / 趋势该系列 / 城市该系列):
|
||||||
|
|
||||||
|
| 板块 | 筛选 | 口径 |
|
||||||
|
|------|------|------|
|
||||||
|
| 用户 | 推广码、关联合伙人、活动 | 推广码=`user_promo_attribution`;关联合伙人=`assoc_partner_account_id`;活动=关联合伙人当前所选活动图(`partner_account.activity_poster_id`) |
|
||||||
|
| 合伙人 | 无 | 仅全局 |
|
||||||
|
| 门店 | 合伙人 | 门店归属主合伙人 `store.partner_account_id` |
|
||||||
|
| 订单 | 推广码、关联合伙人、活动、商品 | 推广码=`order.promo_code_id`;关联合伙人/活动同用户(下单用户);商品=`order.product_id`。笔数=`createdAt`;金额=已付 `payAmount`(`paidAt`) |
|
||||||
|
| 核销单 | 门店、关联合伙人 | 门店=`redeem.store_id`;关联合伙人=核销用户 `assoc_partner_account_id`。笔数与 `RedeemRecord.amount` |
|
||||||
|
|
||||||
|
下拉:合伙人「企业-个人」;活动=活动图标题(需 `activity_posters`)。缺对应权限则忽略该筛。
|
||||||
|
|
||||||
|
### 2.2 模块口径
|
||||||
|
|
||||||
|
| 模块 | 权限键 | 数量 | 新增 | 金额 |
|
||||||
|
|------|--------|------|------|------|
|
||||||
|
| 用户 | `users` | 区间末日存量 | `createdAt` 落入区间 | 有 `orders` 时交叉付费用户 / 客单价(跟用户筛,不跟订单筛) |
|
||||||
|
| 合伙人 | `partners` | 主账号期末存量 | 区间新签 | 交叉:支付时归属 GMV / 名下门店核销额(仅全局) |
|
||||||
|
| 门店 | `stores` | 期末存量 | 区间新签 | 交叉:本板块门店筛下的核销额(需 `benefit`) |
|
||||||
|
| 订单 | `orders` | 区间下单笔数 | 同左 | 已付 `payAmount` |
|
||||||
|
| 核销单 | `benefit` | 区间核销笔数 | 同左 | `RedeemRecord.amount` |
|
||||||
|
|
||||||
|
时间一律北京日历。周=周一~周日;季=自然季;年=自然年。
|
||||||
|
|
||||||
|
默认窗口:日=昨天~今天;周=上周一~今天;月=上月 1 日~今天;季=上季首日~今天;年=去年 1 月 1 日~今天。
|
||||||
|
|
||||||
|
### 2.3 权限与城市
|
||||||
|
|
||||||
|
- 进页仍需 `dashboard`。
|
||||||
|
- 无权限模块:后端不算、响应省略。
|
||||||
|
- 城市范围:只统计负责城市;筛选项无「未选城」。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. API
|
||||||
|
|
||||||
|
`GET /admin/dashboard/analytics`
|
||||||
|
|
||||||
|
全局:`granularity`、`dateFrom`、`dateTo`、`cityId`(`none`=用户未选城)。
|
||||||
|
|
||||||
|
板块:`usersPromoCodeId`(`none`=无归因)、`usersPartnerAccountId`、`usersActivityPosterId`;`storesPartnerAccountId`;`ordersPromoCodeId`(`none`=无推广码)、`ordersPartnerAccountId`、`ordersActivityPosterId`、`ordersProductId`;`redeemsStoreId`、`redeemsPartnerAccountId`。
|
||||||
|
|
||||||
|
响应:`granularity`、`range`、`prevRange`、`modules`、`byPeriod`、`byCity`、`byProduct`、`byPartner`。
|
||||||
|
|
||||||
|
`GET /admin/dashboard/stats`、`/version` 不变。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 变更面
|
||||||
|
|
||||||
|
| 层 | 路径 |
|
||||||
|
|----|------|
|
||||||
|
| domain | `dashboard-period.ts`(分桶 / 上期 / 环比) |
|
||||||
|
| shared-types | `ops.ts` 概览 DTO |
|
||||||
|
| API | `admin-dashboard.service.ts`、`admin-dashboard-analytics.ts`、`admin-query.dto.ts` |
|
||||||
|
| HQ | `DashboardPage.tsx` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [ ] 全局只有城市与时间;五板块筛互不影响
|
||||||
|
- [ ] 日默认昨天~今天,环比为前天~昨天;周月季年按粒度回退一档
|
||||||
|
- [ ] 订单/核销同时展示笔数与金额
|
||||||
|
- [ ] 用户筛关联合伙人后只计 `assoc_partner_account_id`
|
||||||
|
- [ ] 客服(仅 users/orders):无合伙人/门店/核销卡
|
||||||
|
- [ ] 待办卡与超管发版区行为不变
|
||||||
|
- [ ] domain 周期/环比单测通过
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 杜康好客 · v4.0.15 开发文档
|
||||||
|
|
||||||
|
> **2026-09-02** · ops / admin-web / domain / shared-types
|
||||||
|
> **主题**:HQ 概览改为分指标折线图;全局筛选不变
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 版本目标
|
||||||
|
|
||||||
|
| # | 任务 | 类型 | 交付 |
|
||||||
|
|---|------|------|------|
|
||||||
|
| 1 | 横轴 | 体验 | 粒度 = 时间分桶(日/周/月/季/年) |
|
||||||
|
| 2 | 纵轴 | 需求 | 总量 / 增量;订单与核销再拆笔数与金额 |
|
||||||
|
| 3 | 线条 | 需求 | 用户:推广码 / 关联合伙人 / 活动;门店:关联合伙人;订单:用户 / 关联合伙人 / 商品;核销:门店 / 关联合伙人;合伙人无维度单线 |
|
||||||
|
| 4 | 布局 | 体验 | 一图一行、宽度拉满;改全局筛选全部重绘 |
|
||||||
|
| 5 | 快链 | 体验 | 「查看」只带全局城市 + 日期,不带线条维度 |
|
||||||
|
|
||||||
|
**不做**:同比、板块筛、环比卡、Prisma 迁移、新权限键。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 规则
|
||||||
|
|
||||||
|
**全局筛选**:粒度 + 日期 + 城市;日期旁快捷「上周 / 上月 / 上季度」;查询左侧总量 / 增量单选(互斥,只渲染对应折线图);查询右侧「下载PDF」只导出当前指标下的折线图(不含 KPI / 待办 / 版本)。改粒度**不**改日期区间。
|
||||||
|
|
||||||
|
**总量** = 该桶结束时的累计存量(含区间前基线)。**增量** = 落入该桶的新增/发生额。订单笔数按 `createdAt`,订单金额按已付 `payAmount`(`paidAt`);核销按 `RedeemRecord`。
|
||||||
|
|
||||||
|
**线条口径**(与 v4.0.14 归因一致):
|
||||||
|
|
||||||
|
| 板块 | 维度 | 字段 |
|
||||||
|
|------|------|------|
|
||||||
|
| 用户 | 推广码 | `user_promo_attribution`;空=自然量 |
|
||||||
|
| 用户 | 关联合伙人 | `assoc_partner_account_id`;空=未关联 |
|
||||||
|
| 用户 | 活动 | 关联合伙人当前 `activity_poster_id`;空=无活动 |
|
||||||
|
| 门店 | 关联合伙人 | `store.partner_account_id` |
|
||||||
|
| 订单 | 用户 | `order.user_id` |
|
||||||
|
| 订单 | 关联合伙人 | 下单用户 `assoc_partner_account_id` |
|
||||||
|
| 订单 | 商品 | `order.product_id` |
|
||||||
|
| 核销 | 门店 | `redeem.store_id` |
|
||||||
|
| 核销 | 关联合伙人 | 核销用户 `assoc_partner_account_id` |
|
||||||
|
|
||||||
|
高基数维度:按期末存量 Top 10,长尾并入「其他」;`none` 有数据则始终保留。
|
||||||
|
|
||||||
|
无对应权限则不返回该图;无任何维度权限时用户/门店/核销退回单线。城市范围只统计负责城。时间北京日历。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. API
|
||||||
|
|
||||||
|
`GET /admin/dashboard/analytics?granularity&dateFrom&dateTo&cityId`
|
||||||
|
|
||||||
|
响应:`granularity`、`range`、`periods[]`、`charts[]`(`key/title/unit/href/series`)。不再返回 `modules` / `byPeriod` / `byCity` / `byProduct` / `byPartner` / 板块筛参数。
|
||||||
|
|
||||||
|
`GET /admin/dashboard/stats`、`/version` 不变。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 变更面
|
||||||
|
|
||||||
|
| 层 | 路径 |
|
||||||
|
|----|------|
|
||||||
|
| domain | `dashboard-series.ts`(累计 / TopN) |
|
||||||
|
| shared-types | `ops.ts` 折线 DTO |
|
||||||
|
| API | `admin-dashboard-lines.ts`、`admin-dashboard.service.ts`、`admin-query.dto.ts` |
|
||||||
|
| HQ | `DashboardPage.tsx`;订单/合伙人列表消费快链城市与日期 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 验收
|
||||||
|
|
||||||
|
- [ ] 全局:粒度、日期、城市;日期快捷上周/上月/上季度;查询左侧总量/增量单选只出对应图
|
||||||
|
- [ ] 查询右侧下载 PDF:仅当前总量或增量折线图;不含 KPI / 待办 / 版本
|
||||||
|
- [ ] 改粒度不改日期区间;改全局筛选(除指标单选)全部折线重绘
|
||||||
|
- [ ] 每个指标×维度一张全宽折线图;合伙人仅单线
|
||||||
|
- [ ] 日粒度横轴为日期区间按日划分
|
||||||
|
- [ ] 「查看」只带 `cityId` + `createdFrom/createdTo`,不带推广码/合伙人/商品等
|
||||||
|
- [ ] 客服无合伙人/门店/核销图
|
||||||
|
- [ ] 待办卡与超管发版区不变
|
||||||
|
- [ ] domain 折线单测通过
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,127 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
defaultShanghaiRange,
|
||||||
|
eachShanghaiBuckets,
|
||||||
|
periodMomRatio,
|
||||||
|
previousShanghaiRangeByGrain,
|
||||||
|
shanghaiBucketKey,
|
||||||
|
shanghaiQuarterIndex,
|
||||||
|
shanghaiQuarterRange,
|
||||||
|
} from './dashboard-period';
|
||||||
|
import { shanghaiYmd } from './shanghai-date';
|
||||||
|
|
||||||
|
describe('shanghaiBucketKey', () => {
|
||||||
|
it('周跨年落到周一 2025-12-29', () => {
|
||||||
|
expect(shanghaiBucketKey(new Date('2026-01-02T04:00:00+08:00'), 'week')).toBe('2025-12-29');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Q4 → Q1 分属两年', () => {
|
||||||
|
expect(shanghaiBucketKey(new Date('2025-12-15T00:00:00+08:00'), 'quarter')).toBe('2025-Q4');
|
||||||
|
expect(shanghaiBucketKey(new Date('2026-01-02T00:00:00+08:00'), 'quarter')).toBe('2026-Q1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('eachShanghaiBuckets', () => {
|
||||||
|
it('周跨年包含 2025-12-29 与 2026-01-05', () => {
|
||||||
|
const keys = eachShanghaiBuckets(
|
||||||
|
new Date('2025-12-31T00:00:00+08:00'),
|
||||||
|
new Date('2026-01-06T00:00:00+08:00'),
|
||||||
|
'week',
|
||||||
|
).map((b) => b.key);
|
||||||
|
expect(keys).toEqual(['2025-12-29', '2026-01-05']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('季从 Q4 跨到 Q1', () => {
|
||||||
|
const keys = eachShanghaiBuckets(
|
||||||
|
new Date('2025-11-01T00:00:00+08:00'),
|
||||||
|
new Date('2026-02-01T00:00:00+08:00'),
|
||||||
|
'quarter',
|
||||||
|
).map((b) => b.key);
|
||||||
|
expect(keys).toEqual(['2025-Q4', '2026-Q1']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('previousShanghaiRangeByGrain', () => {
|
||||||
|
it('日:昨天~今天 的环比是 前天~昨天', () => {
|
||||||
|
const prev = previousShanghaiRangeByGrain(
|
||||||
|
new Date('2026-09-01T00:00:00+08:00'),
|
||||||
|
new Date('2026-09-02T00:00:00+08:00'),
|
||||||
|
'day',
|
||||||
|
);
|
||||||
|
expect(shanghaiYmd(prev.from)).toBe('2026-08-31');
|
||||||
|
expect(shanghaiYmd(prev.to)).toBe('2026-09-01');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('周:整段回退 7 天', () => {
|
||||||
|
const prev = previousShanghaiRangeByGrain(
|
||||||
|
new Date('2026-08-24T00:00:00+08:00'),
|
||||||
|
new Date('2026-09-02T00:00:00+08:00'),
|
||||||
|
'week',
|
||||||
|
);
|
||||||
|
expect(shanghaiYmd(prev.from)).toBe('2026-08-17');
|
||||||
|
expect(shanghaiYmd(prev.to)).toBe('2026-08-26');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('月:整段回退 1 个月', () => {
|
||||||
|
const prev = previousShanghaiRangeByGrain(
|
||||||
|
new Date('2026-08-01T00:00:00+08:00'),
|
||||||
|
new Date('2026-09-02T00:00:00+08:00'),
|
||||||
|
'month',
|
||||||
|
);
|
||||||
|
expect(shanghaiYmd(prev.from)).toBe('2026-07-01');
|
||||||
|
expect(shanghaiYmd(prev.to)).toBe('2026-08-02');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('periodMomRatio', () => {
|
||||||
|
it('上期为 0:本期 0 为 null,本期 > 0 为 1', () => {
|
||||||
|
expect(periodMomRatio(0, 0)).toBeNull();
|
||||||
|
expect(periodMomRatio(8, 0)).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('常规环比', () => {
|
||||||
|
expect(periodMomRatio(12, 10)).toBeCloseTo(0.2);
|
||||||
|
expect(periodMomRatio(8, 10)).toBeCloseTo(-0.2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('shanghaiQuarterRange', () => {
|
||||||
|
it('Q1 为 1/1~4/1(不含)', () => {
|
||||||
|
const { start, endExclusive } = shanghaiQuarterRange(2026, 1);
|
||||||
|
expect(shanghaiYmd(start)).toBe('2026-01-01');
|
||||||
|
expect(shanghaiYmd(endExclusive)).toBe('2026-04-01');
|
||||||
|
expect(shanghaiQuarterIndex(start)).toEqual({ year: 2026, quarter: 1 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('defaultShanghaiRange', () => {
|
||||||
|
it('日:昨天~今天', () => {
|
||||||
|
const r = defaultShanghaiRange('day', new Date('2026-09-02T12:00:00+08:00'));
|
||||||
|
expect(shanghaiYmd(r.from)).toBe('2026-09-01');
|
||||||
|
expect(shanghaiYmd(r.to)).toBe('2026-09-02');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('周:上周一~今天', () => {
|
||||||
|
const r = defaultShanghaiRange('week', new Date('2026-09-02T12:00:00+08:00'));
|
||||||
|
expect(shanghaiYmd(r.from)).toBe('2026-08-24');
|
||||||
|
expect(shanghaiYmd(r.to)).toBe('2026-09-02');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('月:上月1日~今天', () => {
|
||||||
|
const r = defaultShanghaiRange('month', new Date('2026-09-02T12:00:00+08:00'));
|
||||||
|
expect(shanghaiYmd(r.from)).toBe('2026-08-01');
|
||||||
|
expect(shanghaiYmd(r.to)).toBe('2026-09-02');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('季:上季首日~今天', () => {
|
||||||
|
const r = defaultShanghaiRange('quarter', new Date('2026-09-02T12:00:00+08:00'));
|
||||||
|
expect(shanghaiYmd(r.from)).toBe('2026-04-01');
|
||||||
|
expect(shanghaiYmd(r.to)).toBe('2026-09-02');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('年:去年1月1日~今天', () => {
|
||||||
|
const r = defaultShanghaiRange('year', new Date('2026-09-02T12:00:00+08:00'));
|
||||||
|
expect(shanghaiYmd(r.from)).toBe('2025-01-01');
|
||||||
|
expect(shanghaiYmd(r.to)).toBe('2026-09-02');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
import {
|
||||||
|
addShanghaiDays,
|
||||||
|
parseShanghaiYmd,
|
||||||
|
shanghaiMonthRange,
|
||||||
|
shanghaiWeekRange,
|
||||||
|
shanghaiYearMonth,
|
||||||
|
shanghaiYmd,
|
||||||
|
startOfShanghaiDay,
|
||||||
|
} from './shanghai-date';
|
||||||
|
|
||||||
|
export const DASHBOARD_GRANULARITIES = ['day', 'week', 'month', 'quarter', 'year'] as const;
|
||||||
|
export type DashboardGranularity = (typeof DASHBOARD_GRANULARITIES)[number];
|
||||||
|
|
||||||
|
function pad2(n: number): string {
|
||||||
|
return String(n).padStart(2, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shanghaiQuarterIndex(d: Date): { year: number; quarter: number } {
|
||||||
|
const [y, m] = shanghaiYmd(d).split('-').map(Number);
|
||||||
|
return { year: y, quarter: Math.ceil(m / 3) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shanghaiQuarterRange(
|
||||||
|
year: number,
|
||||||
|
quarter: number,
|
||||||
|
): { start: Date; endExclusive: Date } {
|
||||||
|
const startMonth = (quarter - 1) * 3 + 1;
|
||||||
|
const endMonth = startMonth + 3;
|
||||||
|
const endYear = endMonth > 12 ? year + 1 : year;
|
||||||
|
const em = endMonth > 12 ? endMonth - 12 : endMonth;
|
||||||
|
return {
|
||||||
|
start: new Date(`${year}-${pad2(startMonth)}-01T00:00:00+08:00`),
|
||||||
|
endExclusive: new Date(`${endYear}-${pad2(em)}-01T00:00:00+08:00`),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shanghaiBucketKey(d: Date, grain: DashboardGranularity): string {
|
||||||
|
const ymd = shanghaiYmd(d);
|
||||||
|
const [y, m] = ymd.split('-').map(Number);
|
||||||
|
switch (grain) {
|
||||||
|
case 'day':
|
||||||
|
return ymd;
|
||||||
|
case 'week':
|
||||||
|
return shanghaiYmd(shanghaiWeekRange(d).start);
|
||||||
|
case 'month':
|
||||||
|
return `${y}-${pad2(m)}`;
|
||||||
|
case 'quarter':
|
||||||
|
return `${y}-Q${Math.ceil(m / 3)}`;
|
||||||
|
case 'year':
|
||||||
|
return String(y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shanghaiBucketLabel(key: string, grain: DashboardGranularity): string {
|
||||||
|
switch (grain) {
|
||||||
|
case 'day':
|
||||||
|
return key.slice(5);
|
||||||
|
case 'week':
|
||||||
|
return `${key.slice(5)}周`;
|
||||||
|
default:
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ShanghaiBucket = {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
start: Date;
|
||||||
|
endExclusive: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function eachShanghaiBuckets(
|
||||||
|
from: Date,
|
||||||
|
to: Date,
|
||||||
|
grain: DashboardGranularity,
|
||||||
|
): ShanghaiBucket[] {
|
||||||
|
const startDay = startOfShanghaiDay(from);
|
||||||
|
const endDay = startOfShanghaiDay(to);
|
||||||
|
const out: ShanghaiBucket[] = [];
|
||||||
|
|
||||||
|
if (grain === 'day') {
|
||||||
|
for (let d = startDay; d.getTime() <= endDay.getTime(); d = addShanghaiDays(d, 1)) {
|
||||||
|
const key = shanghaiYmd(d);
|
||||||
|
out.push({
|
||||||
|
key,
|
||||||
|
label: shanghaiBucketLabel(key, grain),
|
||||||
|
start: d,
|
||||||
|
endExclusive: addShanghaiDays(d, 1),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (grain === 'week') {
|
||||||
|
let { start } = shanghaiWeekRange(startDay);
|
||||||
|
const lastStart = shanghaiWeekRange(endDay).start;
|
||||||
|
while (start.getTime() <= lastStart.getTime()) {
|
||||||
|
const key = shanghaiYmd(start);
|
||||||
|
const endExclusive = addShanghaiDays(start, 7);
|
||||||
|
out.push({ key, label: shanghaiBucketLabel(key, grain), start, endExclusive });
|
||||||
|
start = endExclusive;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (grain === 'month') {
|
||||||
|
let { year, month } = shanghaiYearMonth(startDay);
|
||||||
|
const end = shanghaiYearMonth(endDay);
|
||||||
|
while (year < end.year || (year === end.year && month <= end.month)) {
|
||||||
|
const range = shanghaiMonthRange(year, month);
|
||||||
|
const key = `${year}-${pad2(month)}`;
|
||||||
|
out.push({ key, label: key, start: range.start, endExclusive: range.endExclusive });
|
||||||
|
month += 1;
|
||||||
|
if (month > 12) {
|
||||||
|
month = 1;
|
||||||
|
year += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (grain === 'quarter') {
|
||||||
|
let { year, quarter } = shanghaiQuarterIndex(startDay);
|
||||||
|
const end = shanghaiQuarterIndex(endDay);
|
||||||
|
while (year < end.year || (year === end.year && quarter <= end.quarter)) {
|
||||||
|
const range = shanghaiQuarterRange(year, quarter);
|
||||||
|
const key = `${year}-Q${quarter}`;
|
||||||
|
out.push({ key, label: key, start: range.start, endExclusive: range.endExclusive });
|
||||||
|
quarter += 1;
|
||||||
|
if (quarter > 4) {
|
||||||
|
quarter = 1;
|
||||||
|
year += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
let year = Number(shanghaiYmd(startDay).slice(0, 4));
|
||||||
|
const endYear = Number(shanghaiYmd(endDay).slice(0, 4));
|
||||||
|
while (year <= endYear) {
|
||||||
|
out.push({
|
||||||
|
key: String(year),
|
||||||
|
label: String(year),
|
||||||
|
start: new Date(`${year}-01-01T00:00:00+08:00`),
|
||||||
|
endExclusive: new Date(`${year + 1}-01-01T00:00:00+08:00`),
|
||||||
|
});
|
||||||
|
year += 1;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按粒度把日期往前挪一档(日/周/月/季/年),用于环比窗口 */
|
||||||
|
export function addShanghaiGrain(d: Date, grain: DashboardGranularity, delta: number): Date {
|
||||||
|
const start = startOfShanghaiDay(d);
|
||||||
|
switch (grain) {
|
||||||
|
case 'day':
|
||||||
|
return addShanghaiDays(start, delta);
|
||||||
|
case 'week':
|
||||||
|
return addShanghaiDays(start, delta * 7);
|
||||||
|
case 'month':
|
||||||
|
return addShanghaiMonths(start, delta);
|
||||||
|
case 'quarter':
|
||||||
|
return addShanghaiMonths(start, delta * 3);
|
||||||
|
case 'year':
|
||||||
|
return addShanghaiMonths(start, delta * 12);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addShanghaiMonths(d: Date, delta: number): Date {
|
||||||
|
const [y, m, day] = shanghaiYmd(d).split('-').map(Number);
|
||||||
|
const utc = new Date(Date.UTC(y, m - 1 + delta, 1));
|
||||||
|
const ty = utc.getUTCFullYear();
|
||||||
|
const tm = utc.getUTCMonth() + 1;
|
||||||
|
const last = new Date(Date.UTC(ty, tm, 0)).getUTCDate();
|
||||||
|
return parseShanghaiYmd(`${ty}-${pad2(tm)}-${pad2(Math.min(day, last))}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 整段起止按粒度回退一档:日窗口昨天~今天 → 前天~昨天 */
|
||||||
|
export function previousShanghaiRangeByGrain(
|
||||||
|
from: Date,
|
||||||
|
to: Date,
|
||||||
|
grain: DashboardGranularity,
|
||||||
|
): { from: Date; to: Date } {
|
||||||
|
return {
|
||||||
|
from: addShanghaiGrain(from, grain, -1),
|
||||||
|
to: addShanghaiGrain(to, grain, -1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 环比:(本期 − 上期) / 上期;上期 0 且本期 0 → null;上期 0 且本期 > 0 → 1 */
|
||||||
|
export function periodMomRatio(curr: number, prev: number): number | null {
|
||||||
|
if (prev === 0) return curr === 0 ? null : 1;
|
||||||
|
return (curr - prev) / prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 默认窗口 = 上一档起点 ~ 今天(日=昨天~今天,周=上周一~今天,以此类推) */
|
||||||
|
export function defaultShanghaiRange(
|
||||||
|
grain: DashboardGranularity,
|
||||||
|
anchor = new Date(),
|
||||||
|
): { from: Date; to: Date } {
|
||||||
|
const to = startOfShanghaiDay(anchor);
|
||||||
|
switch (grain) {
|
||||||
|
case 'day':
|
||||||
|
return { from: addShanghaiDays(to, -1), to };
|
||||||
|
case 'week': {
|
||||||
|
const thisMonday = shanghaiWeekRange(to).start;
|
||||||
|
return { from: addShanghaiDays(thisMonday, -7), to };
|
||||||
|
}
|
||||||
|
case 'month': {
|
||||||
|
const { year, month } = shanghaiYearMonth(to);
|
||||||
|
const prev = month === 1 ? { year: year - 1, month: 12 } : { year, month: month - 1 };
|
||||||
|
return { from: shanghaiMonthRange(prev.year, prev.month).start, to };
|
||||||
|
}
|
||||||
|
case 'quarter': {
|
||||||
|
const { year, quarter } = shanghaiQuarterIndex(to);
|
||||||
|
let y = year;
|
||||||
|
let q = quarter - 1;
|
||||||
|
if (q <= 0) {
|
||||||
|
q = 4;
|
||||||
|
y -= 1;
|
||||||
|
}
|
||||||
|
return { from: shanghaiQuarterRange(y, q).start, to };
|
||||||
|
}
|
||||||
|
case 'year': {
|
||||||
|
const y = Number(shanghaiYmd(to).slice(0, 4));
|
||||||
|
return { from: new Date(`${y - 1}-01-01T00:00:00+08:00`), to };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultShanghaiRangeYmds(
|
||||||
|
grain: DashboardGranularity,
|
||||||
|
anchor = new Date(),
|
||||||
|
): { from: string; to: string } {
|
||||||
|
const r = defaultShanghaiRange(grain, anchor);
|
||||||
|
return { from: shanghaiYmd(r.from), to: shanghaiYmd(r.to) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
DASHBOARD_SERIES_ALL,
|
||||||
|
DASHBOARD_SERIES_NONE,
|
||||||
|
DASHBOARD_SERIES_OTHER,
|
||||||
|
buildDimensionLines,
|
||||||
|
buildSingleLine,
|
||||||
|
cumulativeValues,
|
||||||
|
normalizeSeriesId,
|
||||||
|
pickTopSeriesIds,
|
||||||
|
} from './dashboard-series';
|
||||||
|
|
||||||
|
describe('normalizeSeriesId', () => {
|
||||||
|
it('空值归 none', () => {
|
||||||
|
expect(normalizeSeriesId(null)).toBe(DASHBOARD_SERIES_NONE);
|
||||||
|
expect(normalizeSeriesId('')).toBe(DASHBOARD_SERIES_NONE);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cumulativeValues', () => {
|
||||||
|
it('带期初存量按桶累加', () => {
|
||||||
|
expect(cumulativeValues([1, 2, 3], 10)).toEqual([11, 13, 16]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pickTopSeriesIds', () => {
|
||||||
|
it('保留 none,其余按权重取 TopN', () => {
|
||||||
|
const { keep, rest } = pickTopSeriesIds(
|
||||||
|
[
|
||||||
|
{ id: 'none', weight: 1 },
|
||||||
|
{ id: 'a', weight: 9 },
|
||||||
|
{ id: 'b', weight: 8 },
|
||||||
|
{ id: 'c', weight: 1 },
|
||||||
|
],
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
expect(keep).toEqual(['none', 'a', 'b']);
|
||||||
|
expect(rest).toEqual(['c']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildDimensionLines', () => {
|
||||||
|
it('总量为期初+增量累计,长尾并入其他', () => {
|
||||||
|
const { total, increment } = buildDimensionLines({
|
||||||
|
periodKeys: ['d1', 'd2'],
|
||||||
|
points: [
|
||||||
|
{ seriesId: 'a', period: 'd1', value: 2 },
|
||||||
|
{ seriesId: 'a', period: 'd2', value: 1 },
|
||||||
|
{ seriesId: 'b', period: 'd1', value: 4 },
|
||||||
|
{ seriesId: 'c', period: 'd2', value: 1 },
|
||||||
|
{ seriesId: 'none', period: 'd1', value: 3 },
|
||||||
|
],
|
||||||
|
baselines: [
|
||||||
|
{ seriesId: 'a', value: 10 },
|
||||||
|
{ seriesId: 'b', value: 1 },
|
||||||
|
],
|
||||||
|
names: new Map([
|
||||||
|
['a', '码A'],
|
||||||
|
['b', '码B'],
|
||||||
|
['c', '码C'],
|
||||||
|
]),
|
||||||
|
noneLabel: '自然量',
|
||||||
|
topN: 1,
|
||||||
|
});
|
||||||
|
expect(increment.map((s) => s.id)).toEqual(['none', 'a', DASHBOARD_SERIES_OTHER]);
|
||||||
|
expect(increment.find((s) => s.id === 'a')?.values).toEqual([2, 1]);
|
||||||
|
expect(total.find((s) => s.id === 'a')?.values).toEqual([12, 13]);
|
||||||
|
expect(increment.find((s) => s.id === DASHBOARD_SERIES_OTHER)?.values).toEqual([4, 1]);
|
||||||
|
expect(total.find((s) => s.id === DASHBOARD_SERIES_OTHER)?.values).toEqual([5, 6]);
|
||||||
|
expect(increment.find((s) => s.id === 'none')?.name).toBe('自然量');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildSingleLine', () => {
|
||||||
|
it('无维度时只有一条 all', () => {
|
||||||
|
const { increment, total } = buildSingleLine({
|
||||||
|
periodKeys: ['d1', 'd2'],
|
||||||
|
points: [
|
||||||
|
{ seriesId: 'x', period: 'd1', value: 2 },
|
||||||
|
{ seriesId: 'y', period: 'd2', value: 3 },
|
||||||
|
],
|
||||||
|
baseline: 5,
|
||||||
|
name: '合伙人',
|
||||||
|
});
|
||||||
|
expect(increment).toEqual({ id: DASHBOARD_SERIES_ALL, name: '合伙人', values: [2, 3] });
|
||||||
|
expect(total.values).toEqual([7, 10]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
export const DASHBOARD_LINE_TOP_N = 10;
|
||||||
|
export const DASHBOARD_SERIES_NONE = 'none';
|
||||||
|
export const DASHBOARD_SERIES_OTHER = 'other';
|
||||||
|
export const DASHBOARD_SERIES_ALL = 'all';
|
||||||
|
|
||||||
|
export type DashboardSeriesPoint = {
|
||||||
|
seriesId: string;
|
||||||
|
period: string;
|
||||||
|
value: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardNamedSeries = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
values: number[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function normalizeSeriesId(raw: string | number | bigint | null | undefined): string {
|
||||||
|
if (raw == null) return DASHBOARD_SERIES_NONE;
|
||||||
|
const s = String(raw).trim();
|
||||||
|
return s ? s : DASHBOARD_SERIES_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function periodValueMap(
|
||||||
|
periodKeys: string[],
|
||||||
|
points: DashboardSeriesPoint[],
|
||||||
|
): Map<string, number[]> {
|
||||||
|
const index = new Map(periodKeys.map((k, i) => [k, i]));
|
||||||
|
const map = new Map<string, number[]>();
|
||||||
|
const ensure = (id: string) => {
|
||||||
|
let arr = map.get(id);
|
||||||
|
if (!arr) {
|
||||||
|
arr = periodKeys.map(() => 0);
|
||||||
|
map.set(id, arr);
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
};
|
||||||
|
for (const p of points) {
|
||||||
|
const i = index.get(p.period);
|
||||||
|
if (i === undefined) continue;
|
||||||
|
ensure(p.seriesId)[i] += p.value;
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cumulativeValues(increments: number[], baseline = 0): number[] {
|
||||||
|
let acc = baseline;
|
||||||
|
return increments.map((n) => {
|
||||||
|
acc += n;
|
||||||
|
return acc;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function seriesEndWeight(increments: number[], baseline = 0): number {
|
||||||
|
return baseline + increments.reduce((sum, n) => sum + n, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickTopSeriesIds(
|
||||||
|
weights: Array<{ id: string; weight: number }>,
|
||||||
|
topN = DASHBOARD_LINE_TOP_N,
|
||||||
|
reserved: string[] = [DASHBOARD_SERIES_NONE],
|
||||||
|
): { keep: string[]; rest: string[] } {
|
||||||
|
const reservedSet = new Set(reserved);
|
||||||
|
const reservedIds = weights
|
||||||
|
.filter((w) => reservedSet.has(w.id) && w.weight !== 0)
|
||||||
|
.map((w) => w.id);
|
||||||
|
const ranked = weights
|
||||||
|
.filter((w) => !reservedSet.has(w.id))
|
||||||
|
.sort((a, b) => b.weight - a.weight || a.id.localeCompare(b.id));
|
||||||
|
return {
|
||||||
|
keep: [...reservedIds, ...ranked.slice(0, topN).map((w) => w.id)],
|
||||||
|
rest: ranked.slice(topN).map((w) => w.id),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sumSeries(
|
||||||
|
incrementMap: Map<string, number[]>,
|
||||||
|
baselineMap: Map<string, number>,
|
||||||
|
ids: string[],
|
||||||
|
periodLen: number,
|
||||||
|
): { increments: number[]; baseline: number } {
|
||||||
|
const increments = Array.from({ length: periodLen }, () => 0);
|
||||||
|
let baseline = 0;
|
||||||
|
for (const id of ids) {
|
||||||
|
const arr = incrementMap.get(id);
|
||||||
|
if (arr) {
|
||||||
|
for (let i = 0; i < periodLen; i += 1) increments[i] += arr[i] ?? 0;
|
||||||
|
}
|
||||||
|
baseline += baselineMap.get(id) ?? 0;
|
||||||
|
}
|
||||||
|
return { increments, baseline };
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyRound(values: number[], round?: (n: number) => number): number[] {
|
||||||
|
return round ? values.map(round) : values;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildDimensionLines(opts: {
|
||||||
|
periodKeys: string[];
|
||||||
|
points: DashboardSeriesPoint[];
|
||||||
|
baselines?: Array<{ seriesId: string; value: number }>;
|
||||||
|
names?: Map<string, string>;
|
||||||
|
noneLabel: string;
|
||||||
|
otherLabel?: string;
|
||||||
|
topN?: number;
|
||||||
|
round?: (n: number) => number;
|
||||||
|
}): { total: DashboardNamedSeries[]; increment: DashboardNamedSeries[] } {
|
||||||
|
const periodLen = opts.periodKeys.length;
|
||||||
|
const incrementMap = periodValueMap(opts.periodKeys, opts.points);
|
||||||
|
const baselineMap = new Map<string, number>();
|
||||||
|
for (const row of opts.baselines ?? []) {
|
||||||
|
const id = normalizeSeriesId(row.seriesId);
|
||||||
|
baselineMap.set(id, (baselineMap.get(id) ?? 0) + row.value);
|
||||||
|
if (!incrementMap.has(id)) incrementMap.set(id, opts.periodKeys.map(() => 0));
|
||||||
|
}
|
||||||
|
for (const id of incrementMap.keys()) {
|
||||||
|
if (!baselineMap.has(id)) baselineMap.set(id, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const weights = [...incrementMap.keys()].map((id) => ({
|
||||||
|
id,
|
||||||
|
weight: seriesEndWeight(incrementMap.get(id) ?? [], baselineMap.get(id) ?? 0),
|
||||||
|
}));
|
||||||
|
const { keep, rest } = pickTopSeriesIds(weights, opts.topN ?? DASHBOARD_LINE_TOP_N);
|
||||||
|
const nameOf = (id: string) => {
|
||||||
|
if (id === DASHBOARD_SERIES_NONE) return opts.noneLabel;
|
||||||
|
if (id === DASHBOARD_SERIES_OTHER) return opts.otherLabel ?? '其他';
|
||||||
|
return opts.names?.get(id) || `#${id}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const orderedIds = [...keep];
|
||||||
|
if (rest.length) orderedIds.push(DASHBOARD_SERIES_OTHER);
|
||||||
|
|
||||||
|
const total: DashboardNamedSeries[] = [];
|
||||||
|
const increment: DashboardNamedSeries[] = [];
|
||||||
|
for (const id of orderedIds) {
|
||||||
|
const packed =
|
||||||
|
id === DASHBOARD_SERIES_OTHER
|
||||||
|
? sumSeries(incrementMap, baselineMap, rest, periodLen)
|
||||||
|
: {
|
||||||
|
increments: incrementMap.get(id) ?? opts.periodKeys.map(() => 0),
|
||||||
|
baseline: baselineMap.get(id) ?? 0,
|
||||||
|
};
|
||||||
|
increment.push({
|
||||||
|
id,
|
||||||
|
name: nameOf(id),
|
||||||
|
values: applyRound(packed.increments, opts.round),
|
||||||
|
});
|
||||||
|
total.push({
|
||||||
|
id,
|
||||||
|
name: nameOf(id),
|
||||||
|
values: applyRound(cumulativeValues(packed.increments, packed.baseline), opts.round),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { total, increment };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSingleLine(opts: {
|
||||||
|
periodKeys: string[];
|
||||||
|
points: DashboardSeriesPoint[];
|
||||||
|
baseline?: number;
|
||||||
|
name: string;
|
||||||
|
round?: (n: number) => number;
|
||||||
|
}): { total: DashboardNamedSeries; increment: DashboardNamedSeries } {
|
||||||
|
const merged: DashboardSeriesPoint[] = opts.points.map((p) => ({
|
||||||
|
...p,
|
||||||
|
seriesId: DASHBOARD_SERIES_ALL,
|
||||||
|
}));
|
||||||
|
const incrementMap = periodValueMap(opts.periodKeys, merged);
|
||||||
|
const increments = incrementMap.get(DASHBOARD_SERIES_ALL) ?? opts.periodKeys.map(() => 0);
|
||||||
|
const baseline = opts.baseline ?? 0;
|
||||||
|
return {
|
||||||
|
increment: {
|
||||||
|
id: DASHBOARD_SERIES_ALL,
|
||||||
|
name: opts.name,
|
||||||
|
values: applyRound(increments, opts.round),
|
||||||
|
},
|
||||||
|
total: {
|
||||||
|
id: DASHBOARD_SERIES_ALL,
|
||||||
|
name: opts.name,
|
||||||
|
values: applyRound(cumulativeValues(increments, baseline), opts.round),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -410,3 +410,7 @@ export * from './dev-plan';
|
|||||||
export * from './support-ticket';
|
export * from './support-ticket';
|
||||||
export * from './phone';
|
export * from './phone';
|
||||||
export * from './shanghai-date';
|
export * from './shanghai-date';
|
||||||
|
export * from './dashboard-period';
|
||||||
|
export * from './dashboard-series';
|
||||||
|
export * from './wecom-report';
|
||||||
|
export * from './shipping-address';
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
isConcreteShippingDistrict,
|
||||||
|
isPseudoShippingDistrict,
|
||||||
|
shippingDetailCityWideHint,
|
||||||
|
validateShippingAddress,
|
||||||
|
} from './shipping-address';
|
||||||
|
|
||||||
|
describe('shipping address', () => {
|
||||||
|
it('rejects pseudo districts', () => {
|
||||||
|
expect(isPseudoShippingDistrict('全市')).toBe(true);
|
||||||
|
expect(isPseudoShippingDistrict('全部')).toBe(true);
|
||||||
|
expect(isPseudoShippingDistrict('')).toBe(true);
|
||||||
|
expect(isConcreteShippingDistrict('金水区')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires concrete district and detail length', () => {
|
||||||
|
expect(
|
||||||
|
validateShippingAddress({
|
||||||
|
province: '河南省',
|
||||||
|
city: '郑州市',
|
||||||
|
district: '全市',
|
||||||
|
detail: '上馆子信阳菜尚购生活广场店',
|
||||||
|
}).ok,
|
||||||
|
).toBe(false);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
validateShippingAddress({
|
||||||
|
province: '河南省',
|
||||||
|
city: '郑州市',
|
||||||
|
district: '金水区',
|
||||||
|
detail: '短',
|
||||||
|
}).message,
|
||||||
|
).toMatch(/详细/);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
validateShippingAddress({
|
||||||
|
province: '河南省',
|
||||||
|
city: '郑州市',
|
||||||
|
district: '金水区',
|
||||||
|
detail: '沙口路8号院尚购生活广场',
|
||||||
|
}).ok,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('soft-hints bare 全市 in detail', () => {
|
||||||
|
expect(shippingDetailCityWideHint('河南省郑州市全市上馆子')).toBeTruthy();
|
||||||
|
expect(shippingDetailCityWideHint('金水区沙口路8号')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
/** 门店筛选用伪区县,禁止写入收货地址 */
|
||||||
|
export const PSEUDO_SHIPPING_DISTRICTS = ['全市', '全部'] as const;
|
||||||
|
|
||||||
|
export const SHIPPING_DETAIL_MIN_LEN = 8;
|
||||||
|
|
||||||
|
export const SHIPPING_REGION_REQUIRED_MSG = '请选择具体区县';
|
||||||
|
export const SHIPPING_DETAIL_REQUIRED_MSG = '请填写详细地址';
|
||||||
|
export const SHIPPING_DETAIL_TOO_SHORT_MSG = '请填写更详细的收货地址(含街道门牌)';
|
||||||
|
|
||||||
|
export type ShippingAddressFields = {
|
||||||
|
province?: string | null;
|
||||||
|
city?: string | null;
|
||||||
|
district?: string | null;
|
||||||
|
detail?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ShippingAddressValidation = {
|
||||||
|
ok: boolean;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function trim(v: string | null | undefined): string {
|
||||||
|
return String(v ?? '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPseudoShippingDistrict(district: string | null | undefined): boolean {
|
||||||
|
const d = trim(district);
|
||||||
|
if (!d) return true;
|
||||||
|
return (PSEUDO_SHIPPING_DISTRICTS as readonly string[]).includes(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 区县是否可作为收货地址(非空且非全市/全部) */
|
||||||
|
export function isConcreteShippingDistrict(district: string | null | undefined): boolean {
|
||||||
|
return !isPseudoShippingDistrict(district);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验收货省市区 + 详细地址。
|
||||||
|
* - 现场取货等特殊值请勿调用本函数
|
||||||
|
* - 不依赖完整省市区树;前端另做树内白名单
|
||||||
|
*/
|
||||||
|
export function validateShippingAddress(
|
||||||
|
input: ShippingAddressFields,
|
||||||
|
options?: { requireDetail?: boolean },
|
||||||
|
): ShippingAddressValidation {
|
||||||
|
const province = trim(input.province);
|
||||||
|
const city = trim(input.city);
|
||||||
|
const district = trim(input.district);
|
||||||
|
const detail = trim(input.detail);
|
||||||
|
const requireDetail = options?.requireDetail !== false;
|
||||||
|
|
||||||
|
if (!province || !city) {
|
||||||
|
return { ok: false, message: '请选择所在地区' };
|
||||||
|
}
|
||||||
|
if (!isConcreteShippingDistrict(district)) {
|
||||||
|
return { ok: false, message: SHIPPING_REGION_REQUIRED_MSG };
|
||||||
|
}
|
||||||
|
if (requireDetail) {
|
||||||
|
if (!detail) {
|
||||||
|
return { ok: false, message: SHIPPING_DETAIL_REQUIRED_MSG };
|
||||||
|
}
|
||||||
|
if (detail.length < SHIPPING_DETAIL_MIN_LEN) {
|
||||||
|
return { ok: false, message: SHIPPING_DETAIL_TOO_SHORT_MSG };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 详细地址含「全市」时的软提示(不单独作为硬失败条件) */
|
||||||
|
export function shippingDetailCityWideHint(detail: string | null | undefined): string | null {
|
||||||
|
const d = trim(detail);
|
||||||
|
if (!d.includes('全市')) return null;
|
||||||
|
if (/路|街|巷|号|大厦|广场|小区|村|镇|乡/.test(d)) return null;
|
||||||
|
return '详细地址含「全市」,建议改为具体街道门牌,以免配送拒单';
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
formatWecomReportMarkdown,
|
||||||
|
wecomReportCutoff,
|
||||||
|
wecomReportDueAt,
|
||||||
|
wecomReportPeriod,
|
||||||
|
wecomReportShouldFire,
|
||||||
|
} from './wecom-report';
|
||||||
|
|
||||||
|
const emptyStats = {
|
||||||
|
usersTotal: 10,
|
||||||
|
usersIncrement: 2,
|
||||||
|
partnersTotal: 3,
|
||||||
|
partnersIncrement: 1,
|
||||||
|
storesTotal: 4,
|
||||||
|
storesIncrement: 0,
|
||||||
|
ordersTotal: 20,
|
||||||
|
ordersIncrement: 5,
|
||||||
|
orderAmountTotal: 1000,
|
||||||
|
orderAmountIncrement: 80.5,
|
||||||
|
redeemsTotal: 8,
|
||||||
|
redeemsIncrement: 3,
|
||||||
|
redeemAmountTotal: 200,
|
||||||
|
redeemAmountIncrement: 40,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('wecomReportPeriod', () => {
|
||||||
|
it('daily is the Shanghai calendar day', () => {
|
||||||
|
const p = wecomReportPeriod('daily', new Date('2026-09-02T20:00:00+08:00'));
|
||||||
|
expect(p.periodKey).toBe('2026-09-02');
|
||||||
|
expect(p.incrementLabel).toBe('当日新增');
|
||||||
|
expect(p.start.toISOString()).toBe(new Date('2026-09-02T00:00:00+08:00').toISOString());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('weekly is the previous natural week', () => {
|
||||||
|
const p = wecomReportPeriod('weekly', new Date('2026-09-02T09:00:00+08:00'));
|
||||||
|
expect(p.periodKey).toBe('2026-08-24');
|
||||||
|
expect(p.rangeLabel).toBe('2026-08-24 ~ 2026-08-30');
|
||||||
|
expect(p.incrementLabel).toBe('本期新增');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('monthly is the previous natural month', () => {
|
||||||
|
const p = wecomReportPeriod('monthly', new Date('2026-09-01T09:00:00+08:00'));
|
||||||
|
expect(p.periodKey).toBe('2026-08');
|
||||||
|
expect(p.title).toBe('月报(2026年8月)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('wecomReportCutoff', () => {
|
||||||
|
it('caps an in-progress daily period at now', () => {
|
||||||
|
const now = new Date('2026-09-02T20:00:00+08:00');
|
||||||
|
const p = wecomReportPeriod('daily', now);
|
||||||
|
expect(wecomReportCutoff(p, now).getTime()).toBe(now.getTime());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses period end for a completed week', () => {
|
||||||
|
const now = new Date('2026-09-02T09:00:00+08:00');
|
||||||
|
const p = wecomReportPeriod('weekly', now);
|
||||||
|
expect(wecomReportCutoff(p, now).getTime()).toBe(p.endExclusive.getTime());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('wecomReportShouldFire', () => {
|
||||||
|
const base = {
|
||||||
|
enabled: true,
|
||||||
|
sendHour: 20,
|
||||||
|
sendMinute: 0,
|
||||||
|
sendWeekday: 1,
|
||||||
|
sendMonthDay: 1,
|
||||||
|
lastSentPeriod: null as string | null,
|
||||||
|
};
|
||||||
|
|
||||||
|
it('does not fire before due time', () => {
|
||||||
|
expect(
|
||||||
|
wecomReportShouldFire('daily', base, new Date('2026-09-02T19:59:00+08:00')),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fires after due time if this period not sent', () => {
|
||||||
|
expect(
|
||||||
|
wecomReportShouldFire('daily', base, new Date('2026-09-02T20:00:00+08:00')),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not fire twice for the same period', () => {
|
||||||
|
expect(
|
||||||
|
wecomReportShouldFire(
|
||||||
|
'daily',
|
||||||
|
{ ...base, lastSentPeriod: '2026-09-02' },
|
||||||
|
new Date('2026-09-02T21:00:00+08:00'),
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('weekly fires Monday 09:00 for last week', () => {
|
||||||
|
expect(
|
||||||
|
wecomReportShouldFire(
|
||||||
|
'weekly',
|
||||||
|
{ ...base, sendHour: 9, sendMinute: 0, sendWeekday: 1 },
|
||||||
|
new Date('2026-09-07T09:00:00+08:00'),
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('wecomReportDueAt', () => {
|
||||||
|
it('monthly clamps to last day of month', () => {
|
||||||
|
const due = wecomReportDueAt(
|
||||||
|
'monthly',
|
||||||
|
{
|
||||||
|
enabled: true,
|
||||||
|
sendHour: 9,
|
||||||
|
sendMinute: 0,
|
||||||
|
sendWeekday: 1,
|
||||||
|
sendMonthDay: 31,
|
||||||
|
lastSentPeriod: null,
|
||||||
|
},
|
||||||
|
new Date('2026-09-10T00:00:00+08:00'),
|
||||||
|
);
|
||||||
|
expect(due.toISOString()).toBe(new Date('2026-09-30T09:00:00+08:00').toISOString());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('formatWecomReportMarkdown', () => {
|
||||||
|
it('renders stock plus increment lines', () => {
|
||||||
|
const p = wecomReportPeriod('daily', new Date('2026-09-02T20:00:00+08:00'));
|
||||||
|
const md = formatWecomReportMarkdown(p, emptyStats);
|
||||||
|
expect(md).toContain('**杜康好客 · 日报(2026-09-02)**');
|
||||||
|
expect(md).toContain('用户数量:10(当日新增 2)');
|
||||||
|
expect(md).toContain('订单金额:1000.00(当日新增 80.50)');
|
||||||
|
expect(md).toContain('核销单数量:8(当日新增 3)');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import {
|
||||||
|
addShanghaiDays,
|
||||||
|
previousShanghaiMonth,
|
||||||
|
previousShanghaiWeek,
|
||||||
|
shanghaiMonthRange,
|
||||||
|
shanghaiWeekRange,
|
||||||
|
shanghaiWeekday,
|
||||||
|
shanghaiYearMonth,
|
||||||
|
shanghaiYmd,
|
||||||
|
startOfShanghaiDay,
|
||||||
|
} from './shanghai-date';
|
||||||
|
|
||||||
|
export const WECOM_REPORT_KINDS = ['daily', 'weekly', 'monthly'] as const;
|
||||||
|
export type WecomReportKind = (typeof WECOM_REPORT_KINDS)[number];
|
||||||
|
|
||||||
|
export function isWecomReportKind(v: string): v is WecomReportKind {
|
||||||
|
return (WECOM_REPORT_KINDS as readonly string[]).includes(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WecomReportStats = {
|
||||||
|
usersTotal: number;
|
||||||
|
usersIncrement: number;
|
||||||
|
partnersTotal: number;
|
||||||
|
partnersIncrement: number;
|
||||||
|
storesTotal: number;
|
||||||
|
storesIncrement: number;
|
||||||
|
ordersTotal: number;
|
||||||
|
ordersIncrement: number;
|
||||||
|
orderAmountTotal: number;
|
||||||
|
orderAmountIncrement: number;
|
||||||
|
redeemsTotal: number;
|
||||||
|
redeemsIncrement: number;
|
||||||
|
redeemAmountTotal: number;
|
||||||
|
redeemAmountIncrement: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WecomReportPeriod = {
|
||||||
|
kind: WecomReportKind;
|
||||||
|
start: Date;
|
||||||
|
endExclusive: Date;
|
||||||
|
periodKey: string;
|
||||||
|
title: string;
|
||||||
|
rangeLabel: string;
|
||||||
|
incrementLabel: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WecomReportSchedule = {
|
||||||
|
enabled: boolean;
|
||||||
|
sendHour: number;
|
||||||
|
sendMinute: number;
|
||||||
|
/** 1=周一 … 7=周日,仅周报 */
|
||||||
|
sendWeekday: number;
|
||||||
|
/** 1–31,仅月报 */
|
||||||
|
sendMonthDay: number;
|
||||||
|
lastSentPeriod: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function pad2(n: number): string {
|
||||||
|
return String(n).padStart(2, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
function shanghaiDateTime(ymd: string, hour: number, minute: number): Date {
|
||||||
|
return new Date(`${ymd}T${pad2(hour)}:${pad2(minute)}:00+08:00`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastDayOfShanghaiMonth(year: number, month: number): number {
|
||||||
|
return Number(shanghaiYmd(new Date(shanghaiMonthRange(year, month).endExclusive.getTime() - 1)).slice(8, 10));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 日报=当天;周报=上一自然周;月报=上一自然月(北京日历) */
|
||||||
|
export function wecomReportPeriod(kind: WecomReportKind, now = new Date()): WecomReportPeriod {
|
||||||
|
if (kind === 'daily') {
|
||||||
|
const start = startOfShanghaiDay(now);
|
||||||
|
const ymd = shanghaiYmd(start);
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
start,
|
||||||
|
endExclusive: addShanghaiDays(start, 1),
|
||||||
|
periodKey: ymd,
|
||||||
|
title: `日报(${ymd})`,
|
||||||
|
rangeLabel: ymd,
|
||||||
|
incrementLabel: '当日新增',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (kind === 'weekly') {
|
||||||
|
const { start, endExclusive } = previousShanghaiWeek(now);
|
||||||
|
const from = shanghaiYmd(start);
|
||||||
|
const to = shanghaiYmd(new Date(endExclusive.getTime() - 1));
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
start,
|
||||||
|
endExclusive,
|
||||||
|
periodKey: from,
|
||||||
|
title: `周报(${from} ~ ${to})`,
|
||||||
|
rangeLabel: `${from} ~ ${to}`,
|
||||||
|
incrementLabel: '本期新增',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { year, month } = previousShanghaiMonth(now);
|
||||||
|
const { start, endExclusive } = shanghaiMonthRange(year, month);
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
start,
|
||||||
|
endExclusive,
|
||||||
|
periodKey: `${year}-${pad2(month)}`,
|
||||||
|
title: `月报(${year}年${month}月)`,
|
||||||
|
rangeLabel: `${shanghaiYmd(start)} ~ ${shanghaiYmd(new Date(endExclusive.getTime() - 1))}`,
|
||||||
|
incrementLabel: '本期新增',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 进行中的周期截到 now,已结束的周期用期末 */
|
||||||
|
export function wecomReportCutoff(period: WecomReportPeriod, now = new Date()): Date {
|
||||||
|
return now.getTime() < period.endExclusive.getTime() ? now : period.endExclusive;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wecomReportDueAt(kind: WecomReportKind, schedule: WecomReportSchedule, now = new Date()): Date {
|
||||||
|
const hour = Math.min(23, Math.max(0, Math.floor(schedule.sendHour)));
|
||||||
|
const minute = Math.min(59, Math.max(0, Math.floor(schedule.sendMinute)));
|
||||||
|
if (kind === 'daily') {
|
||||||
|
return shanghaiDateTime(shanghaiYmd(now), hour, minute);
|
||||||
|
}
|
||||||
|
if (kind === 'weekly') {
|
||||||
|
const { start } = shanghaiWeekRange(now);
|
||||||
|
const iso = Math.min(7, Math.max(1, Math.floor(schedule.sendWeekday) || 1));
|
||||||
|
const day = addShanghaiDays(start, iso - 1);
|
||||||
|
return shanghaiDateTime(shanghaiYmd(day), hour, minute);
|
||||||
|
}
|
||||||
|
const { year, month } = shanghaiYearMonth(now);
|
||||||
|
const last = lastDayOfShanghaiMonth(year, month);
|
||||||
|
const day = Math.min(last, Math.max(1, Math.floor(schedule.sendMonthDay) || 1));
|
||||||
|
return shanghaiDateTime(`${year}-${pad2(month)}-${pad2(day)}`, hour, minute);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wecomReportShouldFire(
|
||||||
|
kind: WecomReportKind,
|
||||||
|
schedule: WecomReportSchedule,
|
||||||
|
now = new Date(),
|
||||||
|
): boolean {
|
||||||
|
if (!schedule.enabled) return false;
|
||||||
|
const period = wecomReportPeriod(kind, now);
|
||||||
|
if (schedule.lastSentPeriod === period.periodKey) return false;
|
||||||
|
return now.getTime() >= wecomReportDueAt(kind, schedule, now).getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtCount(n: number): string {
|
||||||
|
return Math.round(n).toLocaleString('zh-CN');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtMoney(n: number): string {
|
||||||
|
return Number(n || 0).toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function line(label: string, total: number, inc: number, incLabel: string, money = false): string {
|
||||||
|
const fmt = money ? fmtMoney : fmtCount;
|
||||||
|
return `${label}:${fmt(total)}(${incLabel} ${fmt(inc)})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatWecomReportMarkdown(period: WecomReportPeriod, stats: WecomReportStats): string {
|
||||||
|
const inc = period.incrementLabel;
|
||||||
|
return [
|
||||||
|
`**杜康好客 · ${period.title}**`,
|
||||||
|
`统计区间:${period.rangeLabel}(北京时间)`,
|
||||||
|
'',
|
||||||
|
line('用户数量', stats.usersTotal, stats.usersIncrement, inc),
|
||||||
|
line('合伙人数量', stats.partnersTotal, stats.partnersIncrement, inc),
|
||||||
|
line('门店数量', stats.storesTotal, stats.storesIncrement, inc),
|
||||||
|
line('订单数量', stats.ordersTotal, stats.ordersIncrement, inc),
|
||||||
|
line('订单金额', stats.orderAmountTotal, stats.orderAmountIncrement, inc, true),
|
||||||
|
line('核销单数量', stats.redeemsTotal, stats.redeemsIncrement, inc),
|
||||||
|
line('核销单金额', stats.redeemAmountTotal, stats.redeemAmountIncrement, inc, true),
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 仅用于单测:避免把 shanghaiWeekday 的周日=0 与 ISO 周一=1 搞混 */
|
||||||
|
export function wecomReportIsoWeekday(d: Date): number {
|
||||||
|
const wd = shanghaiWeekday(d);
|
||||||
|
return wd === 0 ? 7 : wd;
|
||||||
|
}
|
||||||
@@ -41,6 +41,7 @@ export interface FulfillmentProviderDto {
|
|||||||
capabilities?: {
|
capabilities?: {
|
||||||
createShipment?: boolean;
|
createShipment?: boolean;
|
||||||
getTrack?: boolean;
|
getTrack?: boolean;
|
||||||
|
getSignPhotos?: boolean;
|
||||||
callback?: boolean;
|
callback?: boolean;
|
||||||
cancel?: boolean;
|
cancel?: boolean;
|
||||||
} | null;
|
} | null;
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ export * from './fulfillment-provider';
|
|||||||
export * from './system-config';
|
export * from './system-config';
|
||||||
export * from './wecom-bot';
|
export * from './wecom-bot';
|
||||||
export * from './wecom-message-push';
|
export * from './wecom-message-push';
|
||||||
|
export * from './wecom-report';
|
||||||
export * from './llm-config';
|
export * from './llm-config';
|
||||||
export * from './knowledge-base';
|
export * from './knowledge-base';
|
||||||
export * from './legal';
|
export * from './legal';
|
||||||
|
|||||||
@@ -68,3 +68,38 @@ export interface DeployTriggerResult {
|
|||||||
started?: boolean;
|
started?: boolean;
|
||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DASHBOARD_GRANULARITIES = ['day', 'week', 'month', 'quarter', 'year'] as const;
|
||||||
|
export type DashboardGranularity = (typeof DASHBOARD_GRANULARITIES)[number];
|
||||||
|
|
||||||
|
export type DashboardDateRange = { from: string; to: string };
|
||||||
|
|
||||||
|
export type DashboardLineHref =
|
||||||
|
| 'users'
|
||||||
|
| 'partners'
|
||||||
|
| 'stores'
|
||||||
|
| 'orders'
|
||||||
|
| 'redeems';
|
||||||
|
|
||||||
|
export type DashboardLineUnit = 'count' | 'amount';
|
||||||
|
|
||||||
|
export type DashboardLineSeries = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
values: number[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardLineChart = {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
unit: DashboardLineUnit;
|
||||||
|
href: DashboardLineHref;
|
||||||
|
series: DashboardLineSeries[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DashboardAnalytics = {
|
||||||
|
granularity: DashboardGranularity;
|
||||||
|
range: DashboardDateRange;
|
||||||
|
periods: Array<{ key: string; label: string }>;
|
||||||
|
charts: DashboardLineChart[];
|
||||||
|
};
|
||||||
|
|||||||
@@ -99,11 +99,16 @@ export interface OrderTrackDto {
|
|||||||
queryError?: string | null;
|
queryError?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
/** 履约拦截原因(大单 / 承运商拒单等) */
|
||||||
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
||||||
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
||||||
|
COURIER_OUT_OF_SERVICE: '小飞侠超出服务区,待改址后重推或自配送',
|
||||||
|
COURIER_DISPATCH_FAILED: '自动推配送失败,待总部确认重推或自配送',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const FULFILLMENT_HOLD_COURIER_OUT_OF_SERVICE = 'COURIER_OUT_OF_SERVICE';
|
||||||
|
export const FULFILLMENT_HOLD_COURIER_DISPATCH_FAILED = 'COURIER_DISPATCH_FAILED';
|
||||||
|
|
||||||
export type PartnerProxyDeliveryMode = 'ADDRESS' | 'ON_SITE_PICKUP';
|
export type PartnerProxyDeliveryMode = 'ADDRESS' | 'ON_SITE_PICKUP';
|
||||||
|
|
||||||
export type PartnerProxyOrderProductOption = {
|
export type PartnerProxyOrderProductOption = {
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
export const WECOM_REPORT_KINDS = ['daily', 'weekly', 'monthly'] as const;
|
||||||
|
export type WecomReportKind = (typeof WECOM_REPORT_KINDS)[number];
|
||||||
|
|
||||||
|
export const WECOM_REPORT_KIND_LABELS: Record<WecomReportKind, string> = {
|
||||||
|
daily: '日报',
|
||||||
|
weekly: '周报',
|
||||||
|
monthly: '月报',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WECOM_REPORT_WEEKDAY_OPTIONS: Array<{ value: number; label: string }> = [
|
||||||
|
{ value: 1, label: '周一' },
|
||||||
|
{ value: 2, label: '周二' },
|
||||||
|
{ value: 3, label: '周三' },
|
||||||
|
{ value: 4, label: '周四' },
|
||||||
|
{ value: 5, label: '周五' },
|
||||||
|
{ value: 6, label: '周六' },
|
||||||
|
{ value: 7, label: '周日' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export type WecomReportStatsDto = {
|
||||||
|
usersTotal: number;
|
||||||
|
usersIncrement: number;
|
||||||
|
partnersTotal: number;
|
||||||
|
partnersIncrement: number;
|
||||||
|
storesTotal: number;
|
||||||
|
storesIncrement: number;
|
||||||
|
ordersTotal: number;
|
||||||
|
ordersIncrement: number;
|
||||||
|
orderAmountTotal: number;
|
||||||
|
orderAmountIncrement: number;
|
||||||
|
redeemsTotal: number;
|
||||||
|
redeemsIncrement: number;
|
||||||
|
redeemAmountTotal: number;
|
||||||
|
redeemAmountIncrement: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WecomReportPushDto = {
|
||||||
|
id: string;
|
||||||
|
kind: WecomReportKind;
|
||||||
|
name: string;
|
||||||
|
webhookUrl: string;
|
||||||
|
webhookUrlMasked: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId: string | null;
|
||||||
|
sendHour: number;
|
||||||
|
sendMinute: number;
|
||||||
|
sendWeekday: number;
|
||||||
|
sendMonthDay: number;
|
||||||
|
lastSentPeriod: string | null;
|
||||||
|
lastSentAt: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdateWecomReportPushRequest = {
|
||||||
|
name?: string;
|
||||||
|
webhookUrl?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
mentionWecomUserId?: string | null;
|
||||||
|
sendHour?: number;
|
||||||
|
sendMinute?: number;
|
||||||
|
sendWeekday?: number;
|
||||||
|
sendMonthDay?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WecomReportPreviewDto = {
|
||||||
|
kind: WecomReportKind;
|
||||||
|
periodKey: string;
|
||||||
|
title: string;
|
||||||
|
rangeLabel: string;
|
||||||
|
markdown: string;
|
||||||
|
stats: WecomReportStatsDto;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WecomReportSendResultDto = {
|
||||||
|
ok: boolean;
|
||||||
|
message: string;
|
||||||
|
periodKey: string;
|
||||||
|
};
|
||||||
Generated
+153
@@ -50,6 +50,9 @@ importers:
|
|||||||
element-china-area-data:
|
element-china-area-data:
|
||||||
specifier: ^6.1.0
|
specifier: ^6.1.0
|
||||||
version: 6.1.0
|
version: 6.1.0
|
||||||
|
jspdf:
|
||||||
|
specifier: ^4.2.1
|
||||||
|
version: 4.2.1
|
||||||
react:
|
react:
|
||||||
specifier: ^18.3.1
|
specifier: ^18.3.1
|
||||||
version: 18.3.1
|
version: 18.3.1
|
||||||
@@ -2811,6 +2814,9 @@ packages:
|
|||||||
'@types/node@25.9.5':
|
'@types/node@25.9.5':
|
||||||
resolution: {integrity: sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==}
|
resolution: {integrity: sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==}
|
||||||
|
|
||||||
|
'@types/pako@2.0.4':
|
||||||
|
resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==}
|
||||||
|
|
||||||
'@types/pdfkit@0.17.6':
|
'@types/pdfkit@0.17.6':
|
||||||
resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==}
|
resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==}
|
||||||
|
|
||||||
@@ -2826,6 +2832,9 @@ packages:
|
|||||||
'@types/qs@6.15.1':
|
'@types/qs@6.15.1':
|
||||||
resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}
|
resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}
|
||||||
|
|
||||||
|
'@types/raf@3.4.3':
|
||||||
|
resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==}
|
||||||
|
|
||||||
'@types/range-parser@1.2.7':
|
'@types/range-parser@1.2.7':
|
||||||
resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}
|
resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}
|
||||||
|
|
||||||
@@ -2856,6 +2865,9 @@ packages:
|
|||||||
'@types/serve-static@1.15.10':
|
'@types/serve-static@1.15.10':
|
||||||
resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==}
|
resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==}
|
||||||
|
|
||||||
|
'@types/trusted-types@2.0.7':
|
||||||
|
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||||
|
|
||||||
'@types/validator@13.15.10':
|
'@types/validator@13.15.10':
|
||||||
resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==}
|
resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==}
|
||||||
|
|
||||||
@@ -3313,6 +3325,10 @@ packages:
|
|||||||
bare-url@2.5.2:
|
bare-url@2.5.2:
|
||||||
resolution: {integrity: sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==}
|
resolution: {integrity: sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==}
|
||||||
|
|
||||||
|
base64-arraybuffer@1.0.2:
|
||||||
|
resolution: {integrity: sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==}
|
||||||
|
engines: {node: '>= 0.6.0'}
|
||||||
|
|
||||||
base64-js@0.0.8:
|
base64-js@0.0.8:
|
||||||
resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==}
|
resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -3476,6 +3492,10 @@ packages:
|
|||||||
caniuse-lite@1.0.30001799:
|
caniuse-lite@1.0.30001799:
|
||||||
resolution: {integrity: sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==}
|
resolution: {integrity: sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==}
|
||||||
|
|
||||||
|
canvg@3.0.11:
|
||||||
|
resolution: {integrity: sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==}
|
||||||
|
engines: {node: '>=10.0.0'}
|
||||||
|
|
||||||
capital-case@1.0.4:
|
capital-case@1.0.4:
|
||||||
resolution: {integrity: sha512-ds37W8CytHgwnhGGTi88pcPyR15qoNkOpYwmMMfnWqqWgESapLqvDx6huFjQ5vqWSn2Z06173XNA7LtMOeUh1A==}
|
resolution: {integrity: sha512-ds37W8CytHgwnhGGTi88pcPyR15qoNkOpYwmMMfnWqqWgESapLqvDx6huFjQ5vqWSn2Z06173XNA7LtMOeUh1A==}
|
||||||
|
|
||||||
@@ -3749,6 +3769,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-8HFEBPKhOpJPEPu70wJJetjKta86Gw9+CCyCnB3sui2qQfOvRyqBy4IKLKKAwdMpWb2lHXWk9Wb4Z6AmaUT1Pg==}
|
resolution: {integrity: sha512-8HFEBPKhOpJPEPu70wJJetjKta86Gw9+CCyCnB3sui2qQfOvRyqBy4IKLKKAwdMpWb2lHXWk9Wb4Z6AmaUT1Pg==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
|
|
||||||
|
css-line-break@2.1.0:
|
||||||
|
resolution: {integrity: sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==}
|
||||||
|
|
||||||
css-tree@3.2.1:
|
css-tree@3.2.1:
|
||||||
resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
|
resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
|
||||||
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
|
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
|
||||||
@@ -3906,6 +3929,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-ilXFf9Moz47ABjFpDiA5s1w9lpb4EFSp7+5iiJSbfyYDM+bpZdAgLlSr7fW4aXhVe/E+F6QCv0EvRVFEd5CsWg==}
|
resolution: {integrity: sha512-ilXFf9Moz47ABjFpDiA5s1w9lpb4EFSp7+5iiJSbfyYDM+bpZdAgLlSr7fW4aXhVe/E+F6QCv0EvRVFEd5CsWg==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
|
dompurify@3.4.14:
|
||||||
|
resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==}
|
||||||
|
|
||||||
dot-case@3.0.4:
|
dot-case@3.0.4:
|
||||||
resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==}
|
resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==}
|
||||||
|
|
||||||
@@ -4190,6 +4216,9 @@ packages:
|
|||||||
fast-levenshtein@2.0.6:
|
fast-levenshtein@2.0.6:
|
||||||
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
|
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
|
||||||
|
|
||||||
|
fast-png@6.4.0:
|
||||||
|
resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==}
|
||||||
|
|
||||||
fast-safe-stringify@2.1.1:
|
fast-safe-stringify@2.1.1:
|
||||||
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
||||||
|
|
||||||
@@ -4591,6 +4620,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-ztqyC3kLto0e9WbNp0aeP+M3kTt+nbaIveGmUxAtZa+8iFgKLUOD4YKM5j+f3QD89bra7UeumolZHKuOXnTmeQ==}
|
resolution: {integrity: sha512-ztqyC3kLto0e9WbNp0aeP+M3kTt+nbaIveGmUxAtZa+8iFgKLUOD4YKM5j+f3QD89bra7UeumolZHKuOXnTmeQ==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
html2canvas@1.4.1:
|
||||||
|
resolution: {integrity: sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==}
|
||||||
|
engines: {node: '>=8.0.0'}
|
||||||
|
|
||||||
http-cache-semantics@3.8.1:
|
http-cache-semantics@3.8.1:
|
||||||
resolution: {integrity: sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w==}
|
resolution: {integrity: sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w==}
|
||||||
|
|
||||||
@@ -4687,6 +4720,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-TcdjPibTksa1NQximqep2r17ISRiNE9fwlfbg3F8ANdvP5/yrFTew86VcO//jk4QTaMlbjypPBq76HN2zaKfZQ==}
|
resolution: {integrity: sha512-TcdjPibTksa1NQximqep2r17ISRiNE9fwlfbg3F8ANdvP5/yrFTew86VcO//jk4QTaMlbjypPBq76HN2zaKfZQ==}
|
||||||
engines: {node: '>=4'}
|
engines: {node: '>=4'}
|
||||||
|
|
||||||
|
iobuffer@5.4.0:
|
||||||
|
resolution: {integrity: sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==}
|
||||||
|
|
||||||
ioredis@5.10.1:
|
ioredis@5.10.1:
|
||||||
resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}
|
resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}
|
||||||
engines: {node: '>=12.22.0'}
|
engines: {node: '>=12.22.0'}
|
||||||
@@ -4906,6 +4942,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==}
|
resolution: {integrity: sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==}
|
||||||
engines: {node: '>=12', npm: '>=6'}
|
engines: {node: '>=12', npm: '>=6'}
|
||||||
|
|
||||||
|
jspdf@4.2.1:
|
||||||
|
resolution: {integrity: sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==}
|
||||||
|
|
||||||
jstoxml@2.2.9:
|
jstoxml@2.2.9:
|
||||||
resolution: {integrity: sha512-OYWlK0j+roh+eyaMROlNbS5cd5R25Y+IUpdl7cNdB8HNrkgwQzIS7L9MegxOiWNBj9dQhA/yAxiMwCC5mwNoBw==}
|
resolution: {integrity: sha512-OYWlK0j+roh+eyaMROlNbS5cd5R25Y+IUpdl7cNdB8HNrkgwQzIS7L9MegxOiWNBj9dQhA/yAxiMwCC5mwNoBw==}
|
||||||
|
|
||||||
@@ -5476,6 +5515,9 @@ packages:
|
|||||||
pako@1.0.11:
|
pako@1.0.11:
|
||||||
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
|
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
|
||||||
|
|
||||||
|
pako@2.2.0:
|
||||||
|
resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==}
|
||||||
|
|
||||||
param-case@2.1.1:
|
param-case@2.1.1:
|
||||||
resolution: {integrity: sha512-eQE845L6ot89sk2N8liD8HAuH4ca6Vvr7VWAWwt7+kvvG5aBcPmmphQ68JsEG2qa9n1TykS2DLeMt363AAH8/w==}
|
resolution: {integrity: sha512-eQE845L6ot89sk2N8liD8HAuH4ca6Vvr7VWAWwt7+kvvG5aBcPmmphQ68JsEG2qa9n1TykS2DLeMt363AAH8/w==}
|
||||||
|
|
||||||
@@ -5563,6 +5605,9 @@ packages:
|
|||||||
pend@1.2.0:
|
pend@1.2.0:
|
||||||
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
|
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
|
||||||
|
|
||||||
|
performance-now@2.1.0:
|
||||||
|
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
|
||||||
|
|
||||||
picocolors@1.1.1:
|
picocolors@1.1.1:
|
||||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||||
|
|
||||||
@@ -5788,6 +5833,9 @@ packages:
|
|||||||
queue-microtask@1.2.3:
|
queue-microtask@1.2.3:
|
||||||
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
||||||
|
|
||||||
|
raf@3.4.1:
|
||||||
|
resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
|
||||||
|
|
||||||
randombytes@2.1.0:
|
randombytes@2.1.0:
|
||||||
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
|
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
|
||||||
|
|
||||||
@@ -6190,6 +6238,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
|
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
|
||||||
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
|
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
|
||||||
|
|
||||||
|
rgbcolor@1.0.1:
|
||||||
|
resolution: {integrity: sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==}
|
||||||
|
engines: {node: '>= 0.8.15'}
|
||||||
|
|
||||||
rimraf@2.7.1:
|
rimraf@2.7.1:
|
||||||
resolution: {integrity: sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==}
|
resolution: {integrity: sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==}
|
||||||
deprecated: Rimraf versions prior to v4 are no longer supported
|
deprecated: Rimraf versions prior to v4 are no longer supported
|
||||||
@@ -6433,6 +6485,10 @@ packages:
|
|||||||
stackback@0.0.2:
|
stackback@0.0.2:
|
||||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||||
|
|
||||||
|
stackblur-canvas@2.7.0:
|
||||||
|
resolution: {integrity: sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==}
|
||||||
|
engines: {node: '>=0.1.14'}
|
||||||
|
|
||||||
standard-as-callback@2.1.0:
|
standard-as-callback@2.1.0:
|
||||||
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
|
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
|
||||||
|
|
||||||
@@ -6547,6 +6603,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
|
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
|
|
||||||
|
svg-pathdata@6.0.3:
|
||||||
|
resolution: {integrity: sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==}
|
||||||
|
engines: {node: '>=12.0.0'}
|
||||||
|
|
||||||
svg-tags@1.0.0:
|
svg-tags@1.0.0:
|
||||||
resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==}
|
resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==}
|
||||||
|
|
||||||
@@ -6634,6 +6694,9 @@ packages:
|
|||||||
text-decoder@1.2.7:
|
text-decoder@1.2.7:
|
||||||
resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}
|
resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}
|
||||||
|
|
||||||
|
text-segmentation@1.0.3:
|
||||||
|
resolution: {integrity: sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==}
|
||||||
|
|
||||||
text-table@0.2.0:
|
text-table@0.2.0:
|
||||||
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
|
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
|
||||||
|
|
||||||
@@ -6930,6 +6993,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
|
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
|
||||||
engines: {node: '>= 0.4.0'}
|
engines: {node: '>= 0.4.0'}
|
||||||
|
|
||||||
|
utrie@1.0.2:
|
||||||
|
resolution: {integrity: sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==}
|
||||||
|
|
||||||
uuid@8.3.2:
|
uuid@8.3.2:
|
||||||
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
|
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
|
||||||
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
|
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
|
||||||
@@ -9830,6 +9896,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 7.24.6
|
undici-types: 7.24.6
|
||||||
|
|
||||||
|
'@types/pako@2.0.4': {}
|
||||||
|
|
||||||
'@types/pdfkit@0.17.6':
|
'@types/pdfkit@0.17.6':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 20.19.43
|
'@types/node': 20.19.43
|
||||||
@@ -9847,6 +9915,9 @@ snapshots:
|
|||||||
|
|
||||||
'@types/qs@6.15.1': {}
|
'@types/qs@6.15.1': {}
|
||||||
|
|
||||||
|
'@types/raf@3.4.3':
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@types/range-parser@1.2.7': {}
|
'@types/range-parser@1.2.7': {}
|
||||||
|
|
||||||
'@types/react-dom@18.3.7(@types/react@18.3.31)':
|
'@types/react-dom@18.3.7(@types/react@18.3.31)':
|
||||||
@@ -9885,6 +9956,9 @@ snapshots:
|
|||||||
'@types/node': 20.19.43
|
'@types/node': 20.19.43
|
||||||
'@types/send': 0.17.6
|
'@types/send': 0.17.6
|
||||||
|
|
||||||
|
'@types/trusted-types@2.0.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@types/validator@13.15.10': {}
|
'@types/validator@13.15.10': {}
|
||||||
|
|
||||||
'@types/xml2js@0.4.14':
|
'@types/xml2js@0.4.14':
|
||||||
@@ -10552,6 +10626,9 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
bare-path: 3.1.1
|
bare-path: 3.1.1
|
||||||
|
|
||||||
|
base64-arraybuffer@1.0.2:
|
||||||
|
optional: true
|
||||||
|
|
||||||
base64-js@0.0.8: {}
|
base64-js@0.0.8: {}
|
||||||
|
|
||||||
base64-js@1.5.1: {}
|
base64-js@1.5.1: {}
|
||||||
@@ -10745,6 +10822,18 @@ snapshots:
|
|||||||
|
|
||||||
caniuse-lite@1.0.30001799: {}
|
caniuse-lite@1.0.30001799: {}
|
||||||
|
|
||||||
|
canvg@3.0.11:
|
||||||
|
dependencies:
|
||||||
|
'@babel/runtime': 7.29.7
|
||||||
|
'@types/raf': 3.4.3
|
||||||
|
core-js: 3.49.0
|
||||||
|
raf: 3.4.1
|
||||||
|
regenerator-runtime: 0.13.11
|
||||||
|
rgbcolor: 1.0.1
|
||||||
|
stackblur-canvas: 2.7.0
|
||||||
|
svg-pathdata: 6.0.3
|
||||||
|
optional: true
|
||||||
|
|
||||||
capital-case@1.0.4:
|
capital-case@1.0.4:
|
||||||
dependencies:
|
dependencies:
|
||||||
no-case: 3.0.4
|
no-case: 3.0.4
|
||||||
@@ -11049,6 +11138,11 @@ snapshots:
|
|||||||
|
|
||||||
css-functions-list@3.3.3: {}
|
css-functions-list@3.3.3: {}
|
||||||
|
|
||||||
|
css-line-break@2.1.0:
|
||||||
|
dependencies:
|
||||||
|
utrie: 1.0.2
|
||||||
|
optional: true
|
||||||
|
|
||||||
css-tree@3.2.1:
|
css-tree@3.2.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
mdn-data: 2.27.1
|
mdn-data: 2.27.1
|
||||||
@@ -11191,6 +11285,11 @@ snapshots:
|
|||||||
xml: 1.0.1
|
xml: 1.0.1
|
||||||
xml-js: 1.6.11
|
xml-js: 1.6.11
|
||||||
|
|
||||||
|
dompurify@3.4.14:
|
||||||
|
optionalDependencies:
|
||||||
|
'@types/trusted-types': 2.0.7
|
||||||
|
optional: true
|
||||||
|
|
||||||
dot-case@3.0.4:
|
dot-case@3.0.4:
|
||||||
dependencies:
|
dependencies:
|
||||||
no-case: 3.0.4
|
no-case: 3.0.4
|
||||||
@@ -11597,6 +11696,12 @@ snapshots:
|
|||||||
|
|
||||||
fast-levenshtein@2.0.6: {}
|
fast-levenshtein@2.0.6: {}
|
||||||
|
|
||||||
|
fast-png@6.4.0:
|
||||||
|
dependencies:
|
||||||
|
'@types/pako': 2.0.4
|
||||||
|
iobuffer: 5.4.0
|
||||||
|
pako: 2.2.0
|
||||||
|
|
||||||
fast-safe-stringify@2.1.1: {}
|
fast-safe-stringify@2.1.1: {}
|
||||||
|
|
||||||
fast-uri@3.1.2: {}
|
fast-uri@3.1.2: {}
|
||||||
@@ -12051,6 +12156,12 @@ snapshots:
|
|||||||
|
|
||||||
html-tags@3.3.1: {}
|
html-tags@3.3.1: {}
|
||||||
|
|
||||||
|
html2canvas@1.4.1:
|
||||||
|
dependencies:
|
||||||
|
css-line-break: 2.1.0
|
||||||
|
text-segmentation: 1.0.3
|
||||||
|
optional: true
|
||||||
|
|
||||||
http-cache-semantics@3.8.1: {}
|
http-cache-semantics@3.8.1: {}
|
||||||
|
|
||||||
http-cache-semantics@4.2.0: {}
|
http-cache-semantics@4.2.0: {}
|
||||||
@@ -12178,6 +12289,8 @@ snapshots:
|
|||||||
from2: 2.3.0
|
from2: 2.3.0
|
||||||
p-is-promise: 1.1.0
|
p-is-promise: 1.1.0
|
||||||
|
|
||||||
|
iobuffer@5.4.0: {}
|
||||||
|
|
||||||
ioredis@5.10.1:
|
ioredis@5.10.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@ioredis/commands': 1.5.1
|
'@ioredis/commands': 1.5.1
|
||||||
@@ -12382,6 +12495,17 @@ snapshots:
|
|||||||
ms: 2.1.3
|
ms: 2.1.3
|
||||||
semver: 7.8.5
|
semver: 7.8.5
|
||||||
|
|
||||||
|
jspdf@4.2.1:
|
||||||
|
dependencies:
|
||||||
|
'@babel/runtime': 7.29.7
|
||||||
|
fast-png: 6.4.0
|
||||||
|
fflate: 0.8.3
|
||||||
|
optionalDependencies:
|
||||||
|
canvg: 3.0.11
|
||||||
|
core-js: 3.49.0
|
||||||
|
dompurify: 3.4.14
|
||||||
|
html2canvas: 1.4.1
|
||||||
|
|
||||||
jstoxml@2.2.9: {}
|
jstoxml@2.2.9: {}
|
||||||
|
|
||||||
jszip@3.10.1:
|
jszip@3.10.1:
|
||||||
@@ -12884,6 +13008,8 @@ snapshots:
|
|||||||
|
|
||||||
pako@1.0.11: {}
|
pako@1.0.11: {}
|
||||||
|
|
||||||
|
pako@2.2.0: {}
|
||||||
|
|
||||||
param-case@2.1.1:
|
param-case@2.1.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
no-case: 2.3.2
|
no-case: 2.3.2
|
||||||
@@ -12968,6 +13094,9 @@ snapshots:
|
|||||||
|
|
||||||
pend@1.2.0: {}
|
pend@1.2.0: {}
|
||||||
|
|
||||||
|
performance-now@2.1.0:
|
||||||
|
optional: true
|
||||||
|
|
||||||
picocolors@1.1.1: {}
|
picocolors@1.1.1: {}
|
||||||
|
|
||||||
picomatch@2.3.2: {}
|
picomatch@2.3.2: {}
|
||||||
@@ -13161,6 +13290,11 @@ snapshots:
|
|||||||
|
|
||||||
queue-microtask@1.2.3: {}
|
queue-microtask@1.2.3: {}
|
||||||
|
|
||||||
|
raf@3.4.1:
|
||||||
|
dependencies:
|
||||||
|
performance-now: 2.1.0
|
||||||
|
optional: true
|
||||||
|
|
||||||
randombytes@2.1.0:
|
randombytes@2.1.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
safe-buffer: 5.2.1
|
safe-buffer: 5.2.1
|
||||||
@@ -13658,6 +13792,9 @@ snapshots:
|
|||||||
|
|
||||||
reusify@1.1.0: {}
|
reusify@1.1.0: {}
|
||||||
|
|
||||||
|
rgbcolor@1.0.1:
|
||||||
|
optional: true
|
||||||
|
|
||||||
rimraf@2.7.1:
|
rimraf@2.7.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
glob: 7.2.3
|
glob: 7.2.3
|
||||||
@@ -13984,6 +14121,9 @@ snapshots:
|
|||||||
|
|
||||||
stackback@0.0.2: {}
|
stackback@0.0.2: {}
|
||||||
|
|
||||||
|
stackblur-canvas@2.7.0:
|
||||||
|
optional: true
|
||||||
|
|
||||||
standard-as-callback@2.1.0: {}
|
standard-as-callback@2.1.0: {}
|
||||||
|
|
||||||
statuses@1.5.0: {}
|
statuses@1.5.0: {}
|
||||||
@@ -14133,6 +14273,9 @@ snapshots:
|
|||||||
|
|
||||||
supports-preserve-symlinks-flag@1.0.0: {}
|
supports-preserve-symlinks-flag@1.0.0: {}
|
||||||
|
|
||||||
|
svg-pathdata@6.0.3:
|
||||||
|
optional: true
|
||||||
|
|
||||||
svg-tags@1.0.0: {}
|
svg-tags@1.0.0: {}
|
||||||
|
|
||||||
swiper@11.1.15: {}
|
swiper@11.1.15: {}
|
||||||
@@ -14222,6 +14365,11 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- react-native-b4a
|
- react-native-b4a
|
||||||
|
|
||||||
|
text-segmentation@1.0.3:
|
||||||
|
dependencies:
|
||||||
|
utrie: 1.0.2
|
||||||
|
optional: true
|
||||||
|
|
||||||
text-table@0.2.0: {}
|
text-table@0.2.0: {}
|
||||||
|
|
||||||
thenify-all@1.6.0:
|
thenify-all@1.6.0:
|
||||||
@@ -14502,6 +14650,11 @@ snapshots:
|
|||||||
|
|
||||||
utils-merge@1.0.1: {}
|
utils-merge@1.0.1: {}
|
||||||
|
|
||||||
|
utrie@1.0.2:
|
||||||
|
dependencies:
|
||||||
|
base64-arraybuffer: 1.0.2
|
||||||
|
optional: true
|
||||||
|
|
||||||
uuid@8.3.2: {}
|
uuid@8.3.2: {}
|
||||||
|
|
||||||
v8-compile-cache-lib@3.0.1: {}
|
v8-compile-cache-lib@3.0.1: {}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
||||||
"prisma:seed-wecom-push": "ts-node --transpile-only prisma/seed-wecom-message-push.ts",
|
"prisma:seed-wecom-push": "ts-node --transpile-only prisma/seed-wecom-message-push.ts",
|
||||||
"prisma:migrate-wecom-push": "ts-node --transpile-only prisma/migrate-wecom-message-push.ts",
|
"prisma:migrate-wecom-push": "ts-node --transpile-only prisma/migrate-wecom-message-push.ts",
|
||||||
|
"prisma:migrate-wecom-report": "ts-node --transpile-only prisma/migrate-wecom-report.ts",
|
||||||
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
||||||
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts",
|
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts",
|
||||||
"prisma:merge-spu-dk000007-008": "ts-node --transpile-only prisma/merge-spu-dk000007-008.ts",
|
"prisma:merge-spu-dk000007-008": "ts-node --transpile-only prisma/merge-spu-dk000007-008.ts",
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* 创建 wecom_report_push(若不存在)并写入日/周/月默认行。
|
||||||
|
* 不依赖 Prisma Client 新 model,可在 generate 之前执行。
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
const PLACEHOLDER = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=PENDING';
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
await prisma.$executeRawUnsafe(`
|
||||||
|
CREATE TABLE IF NOT EXISTS wecom_report_push (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
kind VARCHAR(16) NOT NULL,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
webhook_url VARCHAR(512) NOT NULL,
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
mention_wecom_user_id VARCHAR(64) NULL,
|
||||||
|
send_hour INT NOT NULL DEFAULT 20,
|
||||||
|
send_minute INT NOT NULL DEFAULT 0,
|
||||||
|
send_weekday INT NOT NULL DEFAULT 1,
|
||||||
|
send_month_day INT NOT NULL DEFAULT 1,
|
||||||
|
last_sent_period VARCHAR(16) NULL,
|
||||||
|
last_sent_at DATETIME(3) NULL,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
UNIQUE KEY wecom_report_push_kind_key (kind)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
`);
|
||||||
|
|
||||||
|
const seeds: Array<[string, string, number]> = [
|
||||||
|
['daily', '经营日报', 20],
|
||||||
|
['weekly', '经营周报', 9],
|
||||||
|
['monthly', '经营月报', 9],
|
||||||
|
];
|
||||||
|
for (const [kind, name, hour] of seeds) {
|
||||||
|
await prisma.$executeRaw`
|
||||||
|
INSERT IGNORE INTO wecom_report_push
|
||||||
|
(kind, name, webhook_url, enabled, send_hour, send_minute, send_weekday, send_month_day)
|
||||||
|
VALUES
|
||||||
|
(${kind}, ${name}, ${PLACEHOLDER}, 0, ${hour}, 0, 1, 1)
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
console.log('migrate-wecom-report done');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -546,6 +546,26 @@ model WecomPushTemplate {
|
|||||||
@@map("wecom_push_template")
|
@@map("wecom_push_template")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 企微群机器人经营报告推送(日报 / 周报 / 月报,与事件消息推送分开)
|
||||||
|
model WecomReportPush {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
kind String @unique @db.VarChar(16)
|
||||||
|
name String @db.VarChar(64)
|
||||||
|
webhookUrl String @map("webhook_url") @db.VarChar(512)
|
||||||
|
enabled Boolean @default(false)
|
||||||
|
mentionWecomUserId String? @map("mention_wecom_user_id") @db.VarChar(64)
|
||||||
|
sendHour Int @default(20) @map("send_hour")
|
||||||
|
sendMinute Int @default(0) @map("send_minute")
|
||||||
|
sendWeekday Int @default(1) @map("send_weekday")
|
||||||
|
sendMonthDay Int @default(1) @map("send_month_day")
|
||||||
|
lastSentPeriod String? @map("last_sent_period") @db.VarChar(16)
|
||||||
|
lastSentAt DateTime? @map("last_sent_at") @db.DateTime(3)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@map("wecom_report_push")
|
||||||
|
}
|
||||||
|
|
||||||
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
||||||
model LlmApiConfig {
|
model LlmApiConfig {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
|||||||
@@ -95,6 +95,8 @@ export const HqOperationAction = {
|
|||||||
WECOM_MESSAGE_PUSH_UPDATE: 'WECOM_MESSAGE_PUSH_UPDATE',
|
WECOM_MESSAGE_PUSH_UPDATE: 'WECOM_MESSAGE_PUSH_UPDATE',
|
||||||
WECOM_MESSAGE_PUSH_DELETE: 'WECOM_MESSAGE_PUSH_DELETE',
|
WECOM_MESSAGE_PUSH_DELETE: 'WECOM_MESSAGE_PUSH_DELETE',
|
||||||
WECOM_MESSAGE_PUSH_TEST: 'WECOM_MESSAGE_PUSH_TEST',
|
WECOM_MESSAGE_PUSH_TEST: 'WECOM_MESSAGE_PUSH_TEST',
|
||||||
|
WECOM_REPORT_UPDATE: 'WECOM_REPORT_UPDATE',
|
||||||
|
WECOM_REPORT_SEND: 'WECOM_REPORT_SEND',
|
||||||
LLM_CONFIG_CREATE: 'LLM_CONFIG_CREATE',
|
LLM_CONFIG_CREATE: 'LLM_CONFIG_CREATE',
|
||||||
LLM_CONFIG_UPDATE: 'LLM_CONFIG_UPDATE',
|
LLM_CONFIG_UPDATE: 'LLM_CONFIG_UPDATE',
|
||||||
LLM_CONFIG_DELETE: 'LLM_CONFIG_DELETE',
|
LLM_CONFIG_DELETE: 'LLM_CONFIG_DELETE',
|
||||||
@@ -230,6 +232,8 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
|||||||
[HqOperationAction.WECOM_MESSAGE_PUSH_UPDATE]: '编辑企微消息推送',
|
[HqOperationAction.WECOM_MESSAGE_PUSH_UPDATE]: '编辑企微消息推送',
|
||||||
[HqOperationAction.WECOM_MESSAGE_PUSH_DELETE]: '删除企微消息推送',
|
[HqOperationAction.WECOM_MESSAGE_PUSH_DELETE]: '删除企微消息推送',
|
||||||
[HqOperationAction.WECOM_MESSAGE_PUSH_TEST]: '测试企微消息推送',
|
[HqOperationAction.WECOM_MESSAGE_PUSH_TEST]: '测试企微消息推送',
|
||||||
|
[HqOperationAction.WECOM_REPORT_UPDATE]: '编辑企微经营报告',
|
||||||
|
[HqOperationAction.WECOM_REPORT_SEND]: '发送企微经营报告',
|
||||||
[HqOperationAction.LLM_CONFIG_CREATE]: '创建语言模型配置',
|
[HqOperationAction.LLM_CONFIG_CREATE]: '创建语言模型配置',
|
||||||
[HqOperationAction.LLM_CONFIG_UPDATE]: '更新语言模型配置',
|
[HqOperationAction.LLM_CONFIG_UPDATE]: '更新语言模型配置',
|
||||||
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
||||||
|
|||||||
@@ -47,13 +47,27 @@ export function sceneForXfxCmd(cmd: string) {
|
|||||||
return CMD_SCENE[cmd] ?? `XFX_CMD_${cmd}`;
|
return CMD_SCENE[cmd] ?? `XFX_CMD_${cmd}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 签收照等大字段入库前截断,避免撑爆 JSON / 影响后续业务返回 */
|
||||||
|
function sanitizeCourierResponseBody(scene: string, body: unknown): Record<string, unknown> | undefined {
|
||||||
|
if (body === undefined) return undefined;
|
||||||
|
if (typeof body !== 'object' || body === null) {
|
||||||
|
return { value: body };
|
||||||
|
}
|
||||||
|
const root = { ...(body as Record<string, unknown>) };
|
||||||
|
if (scene === 'GET_SIGN_PHOTOS' && Array.isArray(root.data)) {
|
||||||
|
const photos = root.data as unknown[];
|
||||||
|
root.data = photos.map((item) => {
|
||||||
|
if (typeof item !== 'string') return item;
|
||||||
|
if (item.length <= 120) return item;
|
||||||
|
return `${item.slice(0, 80)}…(len=${item.length})`;
|
||||||
|
});
|
||||||
|
root.dataCount = photos.length;
|
||||||
|
}
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
export async function logCourierCall(prisma: PrismaService, input: LogCourierCallInput) {
|
export async function logCourierCall(prisma: PrismaService, input: LogCourierCallInput) {
|
||||||
const responseBody =
|
const responseBody = sanitizeCourierResponseBody(input.scene, input.responseBody);
|
||||||
input.responseBody === undefined
|
|
||||||
? undefined
|
|
||||||
: typeof input.responseBody === 'object' && input.responseBody !== null
|
|
||||||
? (input.responseBody as Record<string, unknown>)
|
|
||||||
: { value: input.responseBody };
|
|
||||||
|
|
||||||
const row = await prisma.logThirdParty.create({
|
const row = await prisma.logThirdParty.create({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -140,6 +140,7 @@ export class FulfillmentProviderService {
|
|||||||
? JSON.stringify({
|
? JSON.stringify({
|
||||||
createShipment: true,
|
createShipment: true,
|
||||||
getTrack: true,
|
getTrack: true,
|
||||||
|
getSignPhotos: true,
|
||||||
callback: true,
|
callback: true,
|
||||||
cancel: true,
|
cancel: true,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { BadRequestException, Injectable, Logger, NotFoundException, Inject, forwardRef } from '@nestjs/common';
|
import { BadRequestException, Injectable, Logger, NotFoundException, Inject, forwardRef } from '@nestjs/common';
|
||||||
import type { CityWarehouse, FulfillmentProvider, Order } from '@prisma/client';
|
import type { CityWarehouse, FulfillmentProvider, Order } from '@prisma/client';
|
||||||
import { isXfxProviderCode } from '@dukang/shared-types';
|
import {
|
||||||
|
FULFILLMENT_HOLD_COURIER_DISPATCH_FAILED,
|
||||||
|
FULFILLMENT_HOLD_COURIER_OUT_OF_SERVICE,
|
||||||
|
isXfxProviderCode,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
BOTTLES_PER_BOX,
|
BOTTLES_PER_BOX,
|
||||||
XFX_AUTO_DISPATCH_MAX_BOXES,
|
XFX_AUTO_DISPATCH_MAX_BOXES,
|
||||||
@@ -29,6 +33,7 @@ export type ManualShipInput = {
|
|||||||
export type HqLogisticsShipInput = ManualShipInput;
|
export type HqLogisticsShipInput = ManualShipInput;
|
||||||
|
|
||||||
export const FULFILLMENT_HOLD_LARGE_ORDER = 'LARGE_ORDER_GE_10_BOXES';
|
export const FULFILLMENT_HOLD_LARGE_ORDER = 'LARGE_ORDER_GE_10_BOXES';
|
||||||
|
export { FULFILLMENT_HOLD_COURIER_OUT_OF_SERVICE, FULFILLMENT_HOLD_COURIER_DISPATCH_FAILED };
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class FulfillmentService {
|
export class FulfillmentService {
|
||||||
@@ -138,6 +143,7 @@ export class FulfillmentService {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : String(err);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
await this.logDispatchFailure(order, provider, message);
|
await this.logDispatchFailure(order, provider, message);
|
||||||
|
await this.markCourierDispatchHold(order.id, message);
|
||||||
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -213,6 +219,7 @@ export class FulfillmentService {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : String(err);
|
const message = err instanceof Error ? err.message : String(err);
|
||||||
await this.logDispatchFailure(order, provider, message);
|
await this.logDispatchFailure(order, provider, message);
|
||||||
|
await this.markCourierDispatchHold(order.id, message);
|
||||||
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,8 +313,9 @@ export class FulfillmentService {
|
|||||||
trackingNumber: order.delivery.trackingNo ?? undefined,
|
trackingNumber: order.delivery.trackingNo ?? undefined,
|
||||||
outNumber: order.orderNo,
|
outNumber: order.orderNo,
|
||||||
};
|
};
|
||||||
|
const cachedSignPhotoUrl = order.delivery.signPhotoResource?.url ?? null;
|
||||||
|
|
||||||
const [trackResult, signPhotoDataUris] = await Promise.all([
|
const [trackResult, signPhotoResult] = await Promise.all([
|
||||||
this.courier
|
this.courier
|
||||||
.getTrack(shipmentQuery, options)
|
.getTrack(shipmentQuery, options)
|
||||||
.then((nodes) => ({ nodes: Array.isArray(nodes) ? nodes : [], error: null as string | null }))
|
.then((nodes) => ({ nodes: Array.isArray(nodes) ? nodes : [], error: null as string | null }))
|
||||||
@@ -315,12 +323,30 @@ export class FulfillmentService {
|
|||||||
nodes: [] as TrackNode[],
|
nodes: [] as TrackNode[],
|
||||||
error: err instanceof Error ? err.message : '查询路由失败',
|
error: err instanceof Error ? err.message : '查询路由失败',
|
||||||
})),
|
})),
|
||||||
this.courier.getSignPhotos(shipmentQuery, options).catch(() => [] as string[]),
|
cachedSignPhotoUrl
|
||||||
|
? Promise.resolve({ dataUris: [] as string[], error: null as string | null })
|
||||||
|
: this.courier
|
||||||
|
.getSignPhotos(shipmentQuery, options)
|
||||||
|
.then((dataUris) => ({
|
||||||
|
dataUris: Array.isArray(dataUris) ? dataUris : [],
|
||||||
|
error: null as string | null,
|
||||||
|
}))
|
||||||
|
.catch((err: unknown) => ({
|
||||||
|
dataUris: [] as string[],
|
||||||
|
error: err instanceof Error ? err.message : '查询签收照片失败',
|
||||||
|
})),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
base.nodes = this.sortTrackNodesOldestFirst(trackResult.nodes);
|
base.nodes = this.sortTrackNodesOldestFirst(trackResult.nodes);
|
||||||
base.queryError = trackResult.error;
|
base.queryError = trackResult.error;
|
||||||
base.signPhotoUrls = await this.resolveSignPhotoUrls(order, signPhotoDataUris);
|
if (cachedSignPhotoUrl) {
|
||||||
|
base.signPhotoUrls = [cachedSignPhotoUrl];
|
||||||
|
} else {
|
||||||
|
base.signPhotoUrls = await this.resolveSignPhotoUrls(order, signPhotoResult.dataUris);
|
||||||
|
if (base.signPhotoUrls.length === 0 && signPhotoResult.error && !base.queryError) {
|
||||||
|
base.queryError = signPhotoResult.error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (this.shouldFetchEstimatedArrival(order.status, base.nodes)) {
|
if (this.shouldFetchEstimatedArrival(order.status, base.nodes)) {
|
||||||
const toAddress = this.buildReceiverAddress(order);
|
const toAddress = this.buildReceiverAddress(order);
|
||||||
@@ -424,43 +450,62 @@ export class FulfillmentService {
|
|||||||
},
|
},
|
||||||
dataUris: string[],
|
dataUris: string[],
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
if (!order.delivery || dataUris.length === 0) {
|
if (!order.delivery) return [];
|
||||||
return order.delivery?.signPhotoResource?.url ? [order.delivery.signPhotoResource.url] : [];
|
if (order.delivery.signPhotoResource?.url) {
|
||||||
|
return [order.delivery.signPhotoResource.url];
|
||||||
}
|
}
|
||||||
|
if (dataUris.length === 0) return [];
|
||||||
|
|
||||||
const urls: string[] = [];
|
const urls: string[] = [];
|
||||||
let firstResourceId: bigint | null = order.delivery.signPhotoResourceId;
|
let firstResourceId: bigint | null = order.delivery.signPhotoResourceId;
|
||||||
|
|
||||||
for (let i = 0; i < dataUris.length; i += 1) {
|
for (let i = 0; i < dataUris.length; i += 1) {
|
||||||
const parsed = this.parseDataUri(dataUris[i]);
|
const raw = dataUris[i];
|
||||||
|
const parsed = this.parseDataUri(raw);
|
||||||
if (!parsed) continue;
|
if (!parsed) continue;
|
||||||
|
|
||||||
const result = await this.oss.putObject({
|
try {
|
||||||
bizType: 'SIGN_PHOTO',
|
if (!this.oss.isEnabled()) {
|
||||||
mediaType: 'IMAGE',
|
throw new Error('OSS 未配置');
|
||||||
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
}
|
||||||
buffer: parsed.buffer,
|
const result = await this.oss.putObject({
|
||||||
mimeType: parsed.mimeType,
|
bizType: 'SIGN_PHOTO',
|
||||||
});
|
mediaType: 'IMAGE',
|
||||||
urls.push(result.url);
|
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
||||||
|
buffer: parsed.buffer,
|
||||||
if (!firstResourceId) {
|
mimeType: parsed.mimeType,
|
||||||
const resource = await this.prisma.commonResource.create({
|
|
||||||
data: {
|
|
||||||
ownerType: 'ORDER',
|
|
||||||
ownerId: order.id,
|
|
||||||
bizType: 'SIGN_PHOTO',
|
|
||||||
mediaType: 'IMAGE',
|
|
||||||
ossBucket: result.bucket,
|
|
||||||
ossKey: result.ossKey,
|
|
||||||
url: result.url,
|
|
||||||
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
|
||||||
fileSize: BigInt(parsed.buffer.length),
|
|
||||||
mimeType: parsed.mimeType,
|
|
||||||
status: 'ACTIVE',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
firstResourceId = resource.id;
|
urls.push(result.url);
|
||||||
|
|
||||||
|
if (!firstResourceId) {
|
||||||
|
const resource = await this.prisma.commonResource.create({
|
||||||
|
data: {
|
||||||
|
ownerType: 'ORDER',
|
||||||
|
ownerId: order.id,
|
||||||
|
bizType: 'SIGN_PHOTO',
|
||||||
|
mediaType: 'IMAGE',
|
||||||
|
ossBucket: result.bucket,
|
||||||
|
ossKey: result.ossKey,
|
||||||
|
url: result.url,
|
||||||
|
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
||||||
|
fileSize: BigInt(parsed.buffer.length),
|
||||||
|
mimeType: parsed.mimeType,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
firstResourceId = resource.id;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// OSS 失败不丢图:回退 data URI,保证 C 端 / HQ 仍可预览
|
||||||
|
this.logger.warn(
|
||||||
|
`签收照上传 OSS 失败,回退 dataURI:orderId=${order.id} err=${
|
||||||
|
err instanceof Error ? err.message : String(err)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
const dataUri = raw.startsWith('data:')
|
||||||
|
? raw
|
||||||
|
: `data:${parsed.mimeType};base64,${parsed.buffer.toString('base64')}`;
|
||||||
|
urls.push(dataUri);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,6 +604,22 @@ export class FulfillmentService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 自动推单失败:挂履约拦截,HQ 可见,避免静默 MANUAL 像「没推单」 */
|
||||||
|
private async markCourierDispatchHold(orderId: bigint, error: string) {
|
||||||
|
const outOfService = /超出服务区/.test(error);
|
||||||
|
const reason = outOfService
|
||||||
|
? FULFILLMENT_HOLD_COURIER_OUT_OF_SERVICE
|
||||||
|
: FULFILLMENT_HOLD_COURIER_DISPATCH_FAILED;
|
||||||
|
this.logger.warn(`承运商推单失败挂起:orderId=${orderId} reason=${reason} err=${error}`);
|
||||||
|
await this.prisma.order.update({
|
||||||
|
where: { id: orderId },
|
||||||
|
data: {
|
||||||
|
fulfillmentHold: true,
|
||||||
|
fulfillmentHoldReason: reason,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async buildQueryUrlFromTemplate(warehouseId: bigint | null, trackingNo: string) {
|
private async buildQueryUrlFromTemplate(warehouseId: bigint | null, trackingNo: string) {
|
||||||
if (!warehouseId) return undefined;
|
if (!warehouseId) return undefined;
|
||||||
const wh = await this.prisma.cityWarehouse.findUnique({ where: { id: warehouseId } });
|
const wh = await this.prisma.cityWarehouse.findUnique({ where: { id: warehouseId } });
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import { validateShippingAddress } from '@dukang/domain';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
|
|
||||||
@@ -27,7 +28,25 @@ export class UserAddressService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private assertShippingFields(body: Record<string, unknown>, existing?: {
|
||||||
|
province: string;
|
||||||
|
city: string;
|
||||||
|
district: string;
|
||||||
|
detail: string;
|
||||||
|
}) {
|
||||||
|
const check = validateShippingAddress({
|
||||||
|
province: body.province != null ? String(body.province) : existing?.province,
|
||||||
|
city: body.city != null ? String(body.city) : existing?.city,
|
||||||
|
district: body.district != null ? String(body.district) : existing?.district,
|
||||||
|
detail: body.detail != null ? String(body.detail) : existing?.detail,
|
||||||
|
});
|
||||||
|
if (!check.ok) {
|
||||||
|
throw new BadRequestException(check.message || '收货地址不完整');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async create(userId: bigint, body: Record<string, unknown>) {
|
async create(userId: bigint, body: Record<string, unknown>) {
|
||||||
|
this.assertShippingFields(body);
|
||||||
const isDefault = body.isDefault ? 1 : 0;
|
const isDefault = body.isDefault ? 1 : 0;
|
||||||
const address = await this.prisma.$transaction(async (tx) => {
|
const address = await this.prisma.$transaction(async (tx) => {
|
||||||
if (isDefault) {
|
if (isDefault) {
|
||||||
@@ -52,6 +71,7 @@ export class UserAddressService {
|
|||||||
async update(userId: bigint, id: bigint, body: Record<string, unknown>) {
|
async update(userId: bigint, id: bigint, body: Record<string, unknown>) {
|
||||||
const existing = await this.prisma.userAddress.findFirst({ where: { id, userId } });
|
const existing = await this.prisma.userAddress.findFirst({ where: { id, userId } });
|
||||||
if (!existing) throw new NotFoundException('地址不存在');
|
if (!existing) throw new NotFoundException('地址不存在');
|
||||||
|
this.assertShippingFields(body, existing);
|
||||||
const address = await this.prisma.$transaction(async (tx) => {
|
const address = await this.prisma.$transaction(async (tx) => {
|
||||||
if (body.isDefault) {
|
if (body.isDefault) {
|
||||||
await tx.userAddress.updateMany({ where: { userId }, data: { isDefault: 0 } });
|
await tx.userAddress.updateMany({ where: { userId }, data: { isDefault: 0 } });
|
||||||
|
|||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import type { DashboardGranularity } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
const COL_ALLOW = new Set([
|
||||||
|
'u.created_at',
|
||||||
|
'o.created_at',
|
||||||
|
'o.paid_at',
|
||||||
|
'p.created_at',
|
||||||
|
's.created_at',
|
||||||
|
'r.created_at',
|
||||||
|
]);
|
||||||
|
|
||||||
|
const SERIES_COL_ALLOW = new Set([
|
||||||
|
'promo.promo_code_id',
|
||||||
|
'u.assoc_partner_account_id',
|
||||||
|
'ap.activity_poster_id',
|
||||||
|
's.partner_account_id',
|
||||||
|
'o.user_id',
|
||||||
|
'o.product_id',
|
||||||
|
'r.store_id',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function sqlSeriesId(column: string): Prisma.Sql {
|
||||||
|
if (!SERIES_COL_ALLOW.has(column)) throw new Error(`bad series col ${column}`);
|
||||||
|
return Prisma.sql`COALESCE(CAST(${Prisma.raw(column)} AS CHAR), 'none')`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shanghaiSqlBucket(column: string, grain: DashboardGranularity): Prisma.Sql {
|
||||||
|
if (!COL_ALLOW.has(column)) throw new Error(`bad column ${column}`);
|
||||||
|
const col = Prisma.raw(column);
|
||||||
|
switch (grain) {
|
||||||
|
case 'day':
|
||||||
|
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y-%m-%d')`;
|
||||||
|
case 'week':
|
||||||
|
return Prisma.sql`DATE_FORMAT(DATE_SUB(DATE(CONVERT_TZ(${col}, '+00:00', '+08:00')), INTERVAL WEEKDAY(DATE(CONVERT_TZ(${col}, '+00:00', '+08:00'))) DAY), '%Y-%m-%d')`;
|
||||||
|
case 'month':
|
||||||
|
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y-%m')`;
|
||||||
|
case 'quarter':
|
||||||
|
return Prisma.sql`CONCAT(YEAR(CONVERT_TZ(${col}, '+00:00', '+08:00')), '-Q', QUARTER(CONVERT_TZ(${col}, '+00:00', '+08:00')))`;
|
||||||
|
case 'year':
|
||||||
|
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y')`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CityFilter =
|
||||||
|
| { kind: 'all' }
|
||||||
|
| { kind: 'none' }
|
||||||
|
| { kind: 'empty' }
|
||||||
|
| { kind: 'ids'; ids: bigint[]; codes: string[] };
|
||||||
|
|
||||||
|
export function sqlAnd(parts: Prisma.Sql[]): Prisma.Sql {
|
||||||
|
return parts.length ? Prisma.join(parts, ' AND ') : Prisma.sql`1=1`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sqlInBigints(columnSql: Prisma.Sql, ids: bigint[]): Prisma.Sql {
|
||||||
|
if (!ids.length) return Prisma.sql`1=0`;
|
||||||
|
return Prisma.sql`${columnSql} IN (${Prisma.join(ids)})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sqlInStrings(columnSql: Prisma.Sql, values: string[]): Prisma.Sql {
|
||||||
|
if (!values.length) return Prisma.sql`1=0`;
|
||||||
|
return Prisma.sql`${columnSql} IN (${Prisma.join(values)})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sqlRange(columnSql: Prisma.Sql, start: Date, endExclusive: Date): Prisma.Sql {
|
||||||
|
return Prisma.sql`${columnSql} >= ${start} AND ${columnSql} < ${endExclusive}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PromoPick = { none?: boolean; id?: bigint };
|
||||||
|
|
||||||
|
export type UserWhereOpts = {
|
||||||
|
city: CityFilter;
|
||||||
|
promo?: PromoPick;
|
||||||
|
assocPartnerId?: bigint;
|
||||||
|
activityPosterId?: bigint;
|
||||||
|
createdStart?: Date | null;
|
||||||
|
createdEndExclusive?: Date | null;
|
||||||
|
createdLte?: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OrderWhereOpts = {
|
||||||
|
city: CityFilter;
|
||||||
|
promo?: PromoPick;
|
||||||
|
assocPartnerId?: bigint;
|
||||||
|
activityPosterId?: bigint;
|
||||||
|
productId?: bigint;
|
||||||
|
createdStart?: Date | null;
|
||||||
|
createdEndExclusive?: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function sqlAssocPartnerUsers(assocPartnerId: bigint): Prisma.Sql {
|
||||||
|
return Prisma.sql`SELECT id FROM user_user WHERE assoc_partner_account_id = ${assocPartnerId} AND status = 1 AND merged_into_user_id IS NULL`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sqlActivityPosterUsers(activityPosterId: bigint): Prisma.Sql {
|
||||||
|
return Prisma.sql`SELECT u.id FROM user_user u INNER JOIN partner_account p ON p.id = u.assoc_partner_account_id WHERE p.activity_poster_id = ${activityPosterId} AND p.is_primary = 1 AND u.status = 1 AND u.merged_into_user_id IS NULL`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sqlActivityPosterPartners(activityPosterId: bigint): Prisma.Sql {
|
||||||
|
return Prisma.sql`SELECT id FROM partner_account WHERE activity_poster_id = ${activityPosterId} AND is_primary = 1`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyPromo(parts: Prisma.Sql[], columnSql: Prisma.Sql, promo?: PromoPick) {
|
||||||
|
if (promo?.none) parts.push(Prisma.sql`${columnSql} IS NULL`);
|
||||||
|
else if (promo?.id !== undefined) parts.push(Prisma.sql`${columnSql} = ${promo.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function userSqlWhere(opts: UserWhereOpts): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [
|
||||||
|
Prisma.sql`u.status = 1`,
|
||||||
|
Prisma.sql`u.merged_into_user_id IS NULL`,
|
||||||
|
];
|
||||||
|
if (opts.createdStart && opts.createdEndExclusive) {
|
||||||
|
parts.push(sqlRange(Prisma.sql`u.created_at`, opts.createdStart, opts.createdEndExclusive));
|
||||||
|
} else if (opts.createdLte) {
|
||||||
|
parts.push(Prisma.sql`u.created_at <= ${opts.createdLte}`);
|
||||||
|
}
|
||||||
|
if (opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (opts.city.kind === 'none') {
|
||||||
|
parts.push(Prisma.sql`(pref.id IS NULL OR pref.selected_city_code IS NULL)`);
|
||||||
|
} else if (opts.city.kind === 'ids') {
|
||||||
|
parts.push(sqlInStrings(Prisma.sql`pref.selected_city_code`, opts.city.codes));
|
||||||
|
}
|
||||||
|
if (opts.promo?.none) parts.push(Prisma.sql`promo.id IS NULL`);
|
||||||
|
else if (opts.promo?.id !== undefined) parts.push(Prisma.sql`promo.promo_code_id = ${opts.promo.id}`);
|
||||||
|
if (opts.assocPartnerId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`u.assoc_partner_account_id = ${opts.assocPartnerId}`);
|
||||||
|
}
|
||||||
|
if (opts.activityPosterId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`u.assoc_partner_account_id IN (${sqlActivityPosterPartners(opts.activityPosterId)})`);
|
||||||
|
}
|
||||||
|
return sqlAnd(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function orderSqlWhere(opts: OrderWhereOpts): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [];
|
||||||
|
if (opts.createdStart && opts.createdEndExclusive) {
|
||||||
|
parts.push(sqlRange(Prisma.sql`o.created_at`, opts.createdStart, opts.createdEndExclusive));
|
||||||
|
}
|
||||||
|
if (opts.city.kind === 'none' || opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (opts.city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`o.city_id`, opts.city.ids));
|
||||||
|
applyPromo(parts, Prisma.sql`o.promo_code_id`, opts.promo);
|
||||||
|
if (opts.assocPartnerId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`o.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||||
|
}
|
||||||
|
if (opts.activityPosterId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`o.user_id IN (${sqlActivityPosterUsers(opts.activityPosterId)})`);
|
||||||
|
}
|
||||||
|
if (opts.productId !== undefined) parts.push(Prisma.sql`o.product_id = ${opts.productId}`);
|
||||||
|
return sqlAnd(parts.length ? parts : [Prisma.sql`1=1`]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function paidOrderSqlWhere(
|
||||||
|
opts: OrderWhereOpts & {
|
||||||
|
paidStart: Date;
|
||||||
|
paidEndExclusive: Date;
|
||||||
|
partnerIdAtPay?: bigint;
|
||||||
|
},
|
||||||
|
): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [
|
||||||
|
Prisma.sql`o.pay_status = 'PAID'`,
|
||||||
|
sqlRange(Prisma.sql`o.paid_at`, opts.paidStart, opts.paidEndExclusive),
|
||||||
|
];
|
||||||
|
if (opts.city.kind === 'none' || opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (opts.city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`o.city_id`, opts.city.ids));
|
||||||
|
applyPromo(parts, Prisma.sql`o.promo_code_id`, opts.promo);
|
||||||
|
if (opts.partnerIdAtPay !== undefined) {
|
||||||
|
parts.push(Prisma.sql`o.partner_account_id_at_pay = ${opts.partnerIdAtPay}`);
|
||||||
|
}
|
||||||
|
if (opts.assocPartnerId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`o.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||||
|
}
|
||||||
|
if (opts.activityPosterId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`o.user_id IN (${sqlActivityPosterUsers(opts.activityPosterId)})`);
|
||||||
|
}
|
||||||
|
if (opts.productId !== undefined) parts.push(Prisma.sql`o.product_id = ${opts.productId}`);
|
||||||
|
return sqlAnd(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function partnerSqlWhere(
|
||||||
|
city: CityFilter,
|
||||||
|
partnerId: bigint | undefined,
|
||||||
|
createdStart: Date | null,
|
||||||
|
createdEndExclusive: Date | null,
|
||||||
|
createdLte: Date | null,
|
||||||
|
): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [Prisma.sql`p.is_primary = 1`];
|
||||||
|
if (createdStart && createdEndExclusive) {
|
||||||
|
parts.push(sqlRange(Prisma.sql`p.created_at`, createdStart, createdEndExclusive));
|
||||||
|
} else if (createdLte) {
|
||||||
|
parts.push(Prisma.sql`p.created_at <= ${createdLte}`);
|
||||||
|
}
|
||||||
|
if (city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (city.kind === 'none') parts.push(Prisma.sql`p.city_id IS NULL`);
|
||||||
|
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`p.city_id`, city.ids));
|
||||||
|
if (partnerId !== undefined) parts.push(Prisma.sql`p.id = ${partnerId}`);
|
||||||
|
return sqlAnd(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function storeSqlWhere(
|
||||||
|
city: CityFilter,
|
||||||
|
partnerId: bigint | undefined,
|
||||||
|
createdStart: Date | null,
|
||||||
|
createdEndExclusive: Date | null,
|
||||||
|
createdLte: Date | null,
|
||||||
|
): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [];
|
||||||
|
if (createdStart && createdEndExclusive) {
|
||||||
|
parts.push(sqlRange(Prisma.sql`s.created_at`, createdStart, createdEndExclusive));
|
||||||
|
} else if (createdLte) {
|
||||||
|
parts.push(Prisma.sql`s.created_at <= ${createdLte}`);
|
||||||
|
}
|
||||||
|
if (city.kind === 'none' || city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`s.city_id`, city.ids));
|
||||||
|
if (partnerId !== undefined) parts.push(Prisma.sql`s.partner_account_id = ${partnerId}`);
|
||||||
|
return sqlAnd(parts.length ? parts : [Prisma.sql`1=1`]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redeemSqlWhere(
|
||||||
|
city: CityFilter,
|
||||||
|
createdStart: Date,
|
||||||
|
createdEndExclusive: Date,
|
||||||
|
opts?: { storeId?: bigint; assocPartnerId?: bigint; storePartnerId?: bigint },
|
||||||
|
): Prisma.Sql {
|
||||||
|
const parts: Prisma.Sql[] = [
|
||||||
|
sqlRange(Prisma.sql`r.created_at`, createdStart, createdEndExclusive),
|
||||||
|
];
|
||||||
|
if (city.kind === 'none' || city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||||
|
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`s.city_id`, city.ids));
|
||||||
|
if (opts?.storeId !== undefined) parts.push(Prisma.sql`r.store_id = ${opts.storeId}`);
|
||||||
|
if (opts?.storePartnerId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`s.partner_account_id = ${opts.storePartnerId}`);
|
||||||
|
}
|
||||||
|
if (opts?.assocPartnerId !== undefined) {
|
||||||
|
parts.push(Prisma.sql`r.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||||
|
}
|
||||||
|
return sqlAnd(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function money(v: unknown): number {
|
||||||
|
if (v == null) return 0;
|
||||||
|
const n = typeof v === 'number' ? v : Number(v);
|
||||||
|
return Math.round(n * 100) / 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toCount(v: unknown): number {
|
||||||
|
if (v == null) return 0;
|
||||||
|
return typeof v === 'number' ? v : Number(v);
|
||||||
|
}
|
||||||
@@ -0,0 +1,909 @@
|
|||||||
|
import type {
|
||||||
|
DashboardLineChart,
|
||||||
|
DashboardLineHref,
|
||||||
|
DashboardLineUnit,
|
||||||
|
DashboardGranularity,
|
||||||
|
HqPermissionKey,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import {
|
||||||
|
buildDimensionLines,
|
||||||
|
buildSingleLine,
|
||||||
|
normalizeSeriesId,
|
||||||
|
shanghaiYmd,
|
||||||
|
type DashboardNamedSeries,
|
||||||
|
type DashboardSeriesPoint,
|
||||||
|
} from '@dukang/domain';
|
||||||
|
import type { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import {
|
||||||
|
type CityFilter,
|
||||||
|
money,
|
||||||
|
orderSqlWhere,
|
||||||
|
paidOrderSqlWhere,
|
||||||
|
partnerSqlWhere,
|
||||||
|
redeemSqlWhere,
|
||||||
|
shanghaiSqlBucket,
|
||||||
|
sqlSeriesId,
|
||||||
|
storeSqlWhere,
|
||||||
|
toCount,
|
||||||
|
userSqlWhere,
|
||||||
|
} from './admin-dashboard-analytics';
|
||||||
|
|
||||||
|
const EPOCH = new Date(0);
|
||||||
|
|
||||||
|
type AggRow = {
|
||||||
|
period: string | Date;
|
||||||
|
series_id: string | null;
|
||||||
|
series_name: string | null;
|
||||||
|
value: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
type BaseRow = {
|
||||||
|
series_id: string | null;
|
||||||
|
series_name: string | null;
|
||||||
|
value: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LineQueryCtx = {
|
||||||
|
prisma: PrismaService;
|
||||||
|
grain: DashboardGranularity;
|
||||||
|
city: CityFilter;
|
||||||
|
rangeStart: Date;
|
||||||
|
rangeEndExclusive: Date;
|
||||||
|
periodKeys: string[];
|
||||||
|
can: (key: HqPermissionKey) => boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function namesFrom(rows: Array<{ series_id: string | null; series_name: string | null }>): Map<string, string> {
|
||||||
|
const map = new Map<string, string>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const id = normalizeSeriesId(row.series_id);
|
||||||
|
const name = (row.series_name || '').trim();
|
||||||
|
if (id !== 'none' && name) map.set(id, name);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
function periodKey(raw: string | Date): string {
|
||||||
|
if (raw instanceof Date) return shanghaiYmd(raw);
|
||||||
|
return String(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPoints(rows: AggRow[], asMoney: boolean): DashboardSeriesPoint[] {
|
||||||
|
return rows.map((row) => ({
|
||||||
|
seriesId: normalizeSeriesId(row.series_id),
|
||||||
|
period: periodKey(row.period),
|
||||||
|
value: asMoney ? money(row.value) : toCount(row.value),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBaselines(rows: BaseRow[], asMoney: boolean): Array<{ seriesId: string; value: number }> {
|
||||||
|
return rows.map((row) => ({
|
||||||
|
seriesId: normalizeSeriesId(row.series_id),
|
||||||
|
value: asMoney ? money(row.value) : toCount(row.value),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pairCharts(
|
||||||
|
href: DashboardLineHref,
|
||||||
|
unit: DashboardLineUnit,
|
||||||
|
totalKey: string,
|
||||||
|
totalTitle: string,
|
||||||
|
incKey: string,
|
||||||
|
incTitle: string,
|
||||||
|
lines: { total: DashboardNamedSeries[]; increment: DashboardNamedSeries[] },
|
||||||
|
): DashboardLineChart[] {
|
||||||
|
return [
|
||||||
|
{ key: totalKey, title: totalTitle, unit, href, series: lines.total },
|
||||||
|
{ key: incKey, title: incTitle, unit, href, series: lines.increment },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function pairSingle(
|
||||||
|
href: DashboardLineHref,
|
||||||
|
unit: DashboardLineUnit,
|
||||||
|
totalKey: string,
|
||||||
|
totalTitle: string,
|
||||||
|
incKey: string,
|
||||||
|
incTitle: string,
|
||||||
|
line: { total: DashboardNamedSeries; increment: DashboardNamedSeries },
|
||||||
|
): DashboardLineChart[] {
|
||||||
|
return pairCharts(href, unit, totalKey, totalTitle, incKey, incTitle, {
|
||||||
|
total: [line.total],
|
||||||
|
increment: [line.increment],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeNames(...maps: Array<Map<string, string>>): Map<string, string> {
|
||||||
|
const out = new Map<string, string>();
|
||||||
|
for (const map of maps) {
|
||||||
|
for (const [k, v] of map) out.set(k, v);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function beforeRange(rangeStart: Date): Date {
|
||||||
|
return new Date(rangeStart.getTime() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadDashboardLineCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const jobs: Array<Promise<DashboardLineChart[]>> = [];
|
||||||
|
if (ctx.can('users')) jobs.push(loadUserCharts(ctx));
|
||||||
|
if (ctx.can('partners')) jobs.push(loadPartnerCharts(ctx));
|
||||||
|
if (ctx.can('stores')) jobs.push(loadStoreCharts(ctx));
|
||||||
|
if (ctx.can('orders')) jobs.push(loadOrderCharts(ctx));
|
||||||
|
if (ctx.can('benefit')) jobs.push(loadRedeemCharts(ctx));
|
||||||
|
const groups = await Promise.all(jobs);
|
||||||
|
return groups.flat();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUserCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const out: DashboardLineChart[] = [];
|
||||||
|
const dims: Array<Promise<DashboardLineChart[]>> = [];
|
||||||
|
if (ctx.can('promo_codes')) dims.push(loadUserPromo(ctx));
|
||||||
|
if (ctx.can('partners')) dims.push(loadUserPartner(ctx));
|
||||||
|
if (ctx.can('activity_posters')) dims.push(loadUserActivity(ctx));
|
||||||
|
if (dims.length) {
|
||||||
|
out.push(...(await Promise.all(dims)).flat());
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||||
|
NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairSingle(
|
||||||
|
'users',
|
||||||
|
'count',
|
||||||
|
'users.total',
|
||||||
|
'用户总量',
|
||||||
|
'users.increment',
|
||||||
|
'用户增量',
|
||||||
|
buildSingleLine({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baseline: toCount(base[0]?.value),
|
||||||
|
name: '用户',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUserPromo(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('promo.promo_code_id')} AS series_id,
|
||||||
|
MAX(CONCAT(pc.name, '(', pc.code, ')')) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN user_promo_attribution promo ON promo.user_id = u.id
|
||||||
|
LEFT JOIN common_promo_code pc ON pc.id = promo.promo_code_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('promo.promo_code_id')} AS series_id,
|
||||||
|
MAX(CONCAT(pc.name, '(', pc.code, ')')) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN user_promo_attribution promo ON promo.user_id = u.id
|
||||||
|
LEFT JOIN common_promo_code pc ON pc.id = promo.promo_code_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairCharts(
|
||||||
|
'users',
|
||||||
|
'count',
|
||||||
|
'users.total.promo',
|
||||||
|
'用户总量 · 推广码',
|
||||||
|
'users.increment.promo',
|
||||||
|
'用户增量 · 推广码',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baselines: toBaselines(base, false),
|
||||||
|
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||||
|
noneLabel: '自然量',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUserPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairCharts(
|
||||||
|
'users',
|
||||||
|
'count',
|
||||||
|
'users.total.partner',
|
||||||
|
'用户总量 · 关联合伙人',
|
||||||
|
'users.increment.partner',
|
||||||
|
'用户增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baselines: toBaselines(base, false),
|
||||||
|
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||||
|
noneLabel: '未关联',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUserActivity(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('ap.activity_poster_id')} AS series_id,
|
||||||
|
MAX(poster.title) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN partner_account ap ON ap.id = u.assoc_partner_account_id
|
||||||
|
LEFT JOIN activity_poster poster ON poster.id = ap.activity_poster_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('ap.activity_poster_id')} AS series_id,
|
||||||
|
MAX(poster.title) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_user u
|
||||||
|
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||||
|
LEFT JOIN partner_account ap ON ap.id = u.assoc_partner_account_id
|
||||||
|
LEFT JOIN activity_poster poster ON poster.id = ap.activity_poster_id
|
||||||
|
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairCharts(
|
||||||
|
'users',
|
||||||
|
'count',
|
||||||
|
'users.total.activity',
|
||||||
|
'用户总量 · 活动',
|
||||||
|
'users.increment.activity',
|
||||||
|
'用户增量 · 活动',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baselines: toBaselines(base, false),
|
||||||
|
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||||
|
noneLabel: '无活动',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPartnerCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('p.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||||
|
NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM partner_account p
|
||||||
|
WHERE ${partnerSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||||
|
GROUP BY period
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM partner_account p
|
||||||
|
WHERE ${partnerSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairSingle(
|
||||||
|
'partners',
|
||||||
|
'count',
|
||||||
|
'partners.total',
|
||||||
|
'合伙人总量',
|
||||||
|
'partners.increment',
|
||||||
|
'合伙人增量',
|
||||||
|
buildSingleLine({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baseline: toCount(base[0]?.value),
|
||||||
|
name: '合伙人',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadStoreCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
if (!ctx.can('partners')) {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('s.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||||
|
NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM store_store s
|
||||||
|
WHERE ${storeSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||||
|
GROUP BY period
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||||
|
FROM store_store s
|
||||||
|
WHERE ${storeSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairSingle(
|
||||||
|
'stores',
|
||||||
|
'count',
|
||||||
|
'stores.total',
|
||||||
|
'门店总量',
|
||||||
|
'stores.increment',
|
||||||
|
'门店增量',
|
||||||
|
buildSingleLine({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baseline: toCount(base[0]?.value),
|
||||||
|
name: '门店',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('s.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('s.partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM store_store s
|
||||||
|
LEFT JOIN partner_account p ON p.id = s.partner_account_id
|
||||||
|
WHERE ${storeSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('s.partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM store_store s
|
||||||
|
LEFT JOIN partner_account p ON p.id = s.partner_account_id
|
||||||
|
WHERE ${storeSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return pairCharts(
|
||||||
|
'stores',
|
||||||
|
'count',
|
||||||
|
'stores.total.partner',
|
||||||
|
'门店总量 · 关联合伙人',
|
||||||
|
'stores.increment.partner',
|
||||||
|
'门店增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc, false),
|
||||||
|
baselines: toBaselines(base, false),
|
||||||
|
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||||
|
noneLabel: '未关联',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOrderCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const user = await loadOrderUser(ctx);
|
||||||
|
const partner = ctx.can('partners') ? await loadOrderPartner(ctx) : [];
|
||||||
|
const product = await loadOrderProduct(ctx);
|
||||||
|
const take = (charts: DashboardLineChart[], unit: DashboardLineUnit) =>
|
||||||
|
charts.filter((c) => c.unit === unit);
|
||||||
|
return [
|
||||||
|
...take(user, 'count'),
|
||||||
|
...take(partner, 'count'),
|
||||||
|
...take(product, 'count'),
|
||||||
|
...take(user, 'amount'),
|
||||||
|
...take(partner, 'amount'),
|
||||||
|
...take(product, 'amount'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOrderUser(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('o.user_id')} AS series_id,
|
||||||
|
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('o.user_id')} AS series_id,
|
||||||
|
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('o.user_id')} AS series_id,
|
||||||
|
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: ctx.rangeStart,
|
||||||
|
paidEndExclusive: ctx.rangeEndExclusive,
|
||||||
|
})}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('o.user_id')} AS series_id,
|
||||||
|
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: EPOCH,
|
||||||
|
paidEndExclusive: ctx.rangeStart,
|
||||||
|
})}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||||
|
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||||
|
return [
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'count',
|
||||||
|
'orders.count.total.user',
|
||||||
|
'订单笔数总量 · 用户',
|
||||||
|
'orders.count.increment.user',
|
||||||
|
'订单笔数增量 · 用户',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(countInc, false),
|
||||||
|
baselines: toBaselines(countBase, false),
|
||||||
|
names: countNames,
|
||||||
|
noneLabel: '未知用户',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'amount',
|
||||||
|
'orders.amount.total.user',
|
||||||
|
'订单金额总量 · 用户',
|
||||||
|
'orders.amount.increment.user',
|
||||||
|
'订单金额增量 · 用户',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(amountInc, true),
|
||||||
|
baselines: toBaselines(amountBase, true),
|
||||||
|
names: amountNames,
|
||||||
|
noneLabel: '未知用户',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOrderPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: ctx.rangeStart,
|
||||||
|
paidEndExclusive: ctx.rangeEndExclusive,
|
||||||
|
})}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
INNER JOIN user_user u ON u.id = o.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: EPOCH,
|
||||||
|
paidEndExclusive: ctx.rangeStart,
|
||||||
|
})}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||||
|
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||||
|
return [
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'count',
|
||||||
|
'orders.count.total.partner',
|
||||||
|
'订单笔数总量 · 关联合伙人',
|
||||||
|
'orders.count.increment.partner',
|
||||||
|
'订单笔数增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(countInc, false),
|
||||||
|
baselines: toBaselines(countBase, false),
|
||||||
|
names: countNames,
|
||||||
|
noneLabel: '未关联',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'amount',
|
||||||
|
'orders.amount.total.partner',
|
||||||
|
'订单金额总量 · 关联合伙人',
|
||||||
|
'orders.amount.increment.partner',
|
||||||
|
'订单金额增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(amountInc, true),
|
||||||
|
baselines: toBaselines(amountBase, true),
|
||||||
|
names: amountNames,
|
||||||
|
noneLabel: '未关联',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOrderProduct(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('o.product_id')} AS series_id,
|
||||||
|
MAX(o.product_name) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('o.product_id')} AS series_id,
|
||||||
|
MAX(o.product_name) AS series_name,
|
||||||
|
COUNT(*) AS value
|
||||||
|
FROM user_order o
|
||||||
|
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<AggRow[]>`
|
||||||
|
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('o.product_id')} AS series_id,
|
||||||
|
MAX(o.product_name) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: ctx.rangeStart,
|
||||||
|
paidEndExclusive: ctx.rangeEndExclusive,
|
||||||
|
})}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`,
|
||||||
|
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||||
|
SELECT ${sqlSeriesId('o.product_id')} AS series_id,
|
||||||
|
MAX(o.product_name) AS series_name,
|
||||||
|
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||||
|
FROM user_order o
|
||||||
|
WHERE ${paidOrderSqlWhere({
|
||||||
|
city: ctx.city,
|
||||||
|
paidStart: EPOCH,
|
||||||
|
paidEndExclusive: ctx.rangeStart,
|
||||||
|
})}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||||
|
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||||
|
return [
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'count',
|
||||||
|
'orders.count.total.product',
|
||||||
|
'订单笔数总量 · 商品',
|
||||||
|
'orders.count.increment.product',
|
||||||
|
'订单笔数增量 · 商品',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(countInc, false),
|
||||||
|
baselines: toBaselines(countBase, false),
|
||||||
|
names: countNames,
|
||||||
|
noneLabel: '未知商品',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairCharts(
|
||||||
|
'orders',
|
||||||
|
'amount',
|
||||||
|
'orders.amount.total.product',
|
||||||
|
'订单金额总量 · 商品',
|
||||||
|
'orders.amount.increment.product',
|
||||||
|
'订单金额增量 · 商品',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(amountInc, true),
|
||||||
|
baselines: toBaselines(amountBase, true),
|
||||||
|
names: amountNames,
|
||||||
|
noneLabel: '未知商品',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRedeemCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const store = ctx.can('stores') ? await loadRedeemStore(ctx) : [];
|
||||||
|
const partner = ctx.can('partners') ? await loadRedeemPartner(ctx) : [];
|
||||||
|
if (!store.length && !partner.length) return loadRedeemSingle(ctx);
|
||||||
|
const take = (charts: DashboardLineChart[], unit: DashboardLineUnit) =>
|
||||||
|
charts.filter((c) => c.unit === unit);
|
||||||
|
return [
|
||||||
|
...take(store, 'count'),
|
||||||
|
...take(partner, 'count'),
|
||||||
|
...take(store, 'amount'),
|
||||||
|
...take(partner, 'amount'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRedeemStore(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('r.store_id')} AS series_id,
|
||||||
|
MAX(s.name) AS series_name,
|
||||||
|
COUNT(*) AS cnt,
|
||||||
|
COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`.then(splitCountAmount),
|
||||||
|
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT ${sqlSeriesId('r.store_id')} AS series_id,
|
||||||
|
MAX(s.name) AS series_name,
|
||||||
|
COUNT(*) AS cnt,
|
||||||
|
COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
const countInc = inc.count;
|
||||||
|
const amountInc = inc.amount;
|
||||||
|
const countBase: BaseRow[] = base.map((r) => ({
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.cnt,
|
||||||
|
}));
|
||||||
|
const amountBase: BaseRow[] = base.map((r) => ({
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.amount,
|
||||||
|
}));
|
||||||
|
const names = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||||
|
return [
|
||||||
|
...pairCharts(
|
||||||
|
'redeems',
|
||||||
|
'count',
|
||||||
|
'redeems.count.total.store',
|
||||||
|
'核销单数总量 · 门店',
|
||||||
|
'redeems.count.increment.store',
|
||||||
|
'核销单数增量 · 门店',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(countInc, false),
|
||||||
|
baselines: toBaselines(countBase, false),
|
||||||
|
names,
|
||||||
|
noneLabel: '未知门店',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairCharts(
|
||||||
|
'redeems',
|
||||||
|
'amount',
|
||||||
|
'redeems.amount.total.store',
|
||||||
|
'核销金额总量 · 门店',
|
||||||
|
'redeems.amount.increment.store',
|
||||||
|
'核销金额增量 · 门店',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(amountInc, true),
|
||||||
|
baselines: toBaselines(amountBase, true),
|
||||||
|
names,
|
||||||
|
noneLabel: '未知门店',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRedeemPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period,
|
||||||
|
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS cnt,
|
||||||
|
COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
INNER JOIN user_user u ON u.id = r.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||||
|
GROUP BY period, series_id
|
||||||
|
`.then(splitCountAmount),
|
||||||
|
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||||
|
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||||
|
COUNT(*) AS cnt,
|
||||||
|
COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
INNER JOIN user_user u ON u.id = r.user_id
|
||||||
|
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||||
|
GROUP BY series_id
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
const countBase: BaseRow[] = base.map((r) => ({
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.cnt,
|
||||||
|
}));
|
||||||
|
const amountBase: BaseRow[] = base.map((r) => ({
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.amount,
|
||||||
|
}));
|
||||||
|
const names = mergeNames(namesFrom(inc.count), namesFrom(countBase));
|
||||||
|
return [
|
||||||
|
...pairCharts(
|
||||||
|
'redeems',
|
||||||
|
'count',
|
||||||
|
'redeems.count.total.partner',
|
||||||
|
'核销单数总量 · 关联合伙人',
|
||||||
|
'redeems.count.increment.partner',
|
||||||
|
'核销单数增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc.count, false),
|
||||||
|
baselines: toBaselines(countBase, false),
|
||||||
|
names,
|
||||||
|
noneLabel: '未关联',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairCharts(
|
||||||
|
'redeems',
|
||||||
|
'amount',
|
||||||
|
'redeems.amount.total.partner',
|
||||||
|
'核销金额总量 · 关联合伙人',
|
||||||
|
'redeems.amount.increment.partner',
|
||||||
|
'核销金额增量 · 关联合伙人',
|
||||||
|
buildDimensionLines({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc.amount, true),
|
||||||
|
baselines: toBaselines(amountBase, true),
|
||||||
|
names,
|
||||||
|
noneLabel: '未关联',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRedeemSingle(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||||
|
const [inc, base] = await Promise.all([
|
||||||
|
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||||
|
NULL AS series_name, COUNT(*) AS cnt, COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||||
|
GROUP BY period
|
||||||
|
`.then(splitCountAmount),
|
||||||
|
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||||
|
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS cnt, COALESCE(SUM(r.amount), 0) AS amount
|
||||||
|
FROM user_redeem_record r
|
||||||
|
INNER JOIN store_store s ON s.id = r.store_id
|
||||||
|
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
return [
|
||||||
|
...pairSingle(
|
||||||
|
'redeems',
|
||||||
|
'count',
|
||||||
|
'redeems.count.total',
|
||||||
|
'核销单数总量',
|
||||||
|
'redeems.count.increment',
|
||||||
|
'核销单数增量',
|
||||||
|
buildSingleLine({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc.count, false),
|
||||||
|
baseline: toCount(base[0]?.cnt),
|
||||||
|
name: '核销单数',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
...pairSingle(
|
||||||
|
'redeems',
|
||||||
|
'amount',
|
||||||
|
'redeems.amount.total',
|
||||||
|
'核销金额总量',
|
||||||
|
'redeems.amount.increment',
|
||||||
|
'核销金额增量',
|
||||||
|
buildSingleLine({
|
||||||
|
periodKeys: ctx.periodKeys,
|
||||||
|
points: toPoints(inc.amount, true),
|
||||||
|
baseline: money(base[0]?.amount),
|
||||||
|
name: '核销金额',
|
||||||
|
round: money,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitCountAmount(
|
||||||
|
rows: Array<AggRow & { cnt: unknown; amount: unknown }>,
|
||||||
|
): { count: AggRow[]; amount: AggRow[] } {
|
||||||
|
return {
|
||||||
|
count: rows.map((r) => ({
|
||||||
|
period: r.period,
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.cnt,
|
||||||
|
})),
|
||||||
|
amount: rows.map((r) => ({
|
||||||
|
period: r.period,
|
||||||
|
series_id: r.series_id,
|
||||||
|
series_name: r.series_name,
|
||||||
|
value: r.amount,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import type { HqPermissionKey } from '@dukang/shared-types';
|
import type {
|
||||||
|
DashboardAnalytics,
|
||||||
|
DashboardGranularity,
|
||||||
|
HqPermissionKey,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import {
|
||||||
|
addShanghaiDays,
|
||||||
|
defaultShanghaiRangeYmds,
|
||||||
|
eachShanghaiBuckets,
|
||||||
|
parseShanghaiYmd,
|
||||||
|
shanghaiYmd,
|
||||||
|
} from '@dukang/domain';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import {
|
import {
|
||||||
HqPermissionsResolver,
|
HqPermissionsResolver,
|
||||||
@@ -9,43 +20,8 @@ import {
|
|||||||
type HqCityScope,
|
type HqCityScope,
|
||||||
} from '../../common/guards/hq-permission.guard';
|
} from '../../common/guards/hq-permission.guard';
|
||||||
import type { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
import type { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||||
|
import { type CityFilter } from './admin-dashboard-analytics';
|
||||||
function startOfDay(d: Date) {
|
import { loadDashboardLineCharts } from './admin-dashboard-lines';
|
||||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
function endOfDay(d: Date) {
|
|
||||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseYmd(s: string): Date | null {
|
|
||||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
|
|
||||||
const d = new Date(`${s}T00:00:00`);
|
|
||||||
return Number.isNaN(d.getTime()) ? null : d;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatYmd(d: Date): string {
|
|
||||||
const y = d.getFullYear();
|
|
||||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
|
||||||
const day = String(d.getDate()).padStart(2, '0');
|
|
||||||
return `${y}-${m}-${day}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function eachDate(from: Date, to: Date): string[] {
|
|
||||||
const out: string[] = [];
|
|
||||||
const cur = startOfDay(from);
|
|
||||||
const end = startOfDay(to);
|
|
||||||
while (cur <= end) {
|
|
||||||
out.push(formatYmd(cur));
|
|
||||||
cur.setDate(cur.getDate() + 1);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function num(v: Prisma.Decimal | number | string | null | undefined): number {
|
|
||||||
if (v == null) return 0;
|
|
||||||
return typeof v === 'number' ? v : Number(v);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
||||||
const day = appliedAt.getDay();
|
const day = appliedAt.getDay();
|
||||||
@@ -296,17 +272,20 @@ export class AdminDashboardService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAnalytics(actorId: bigint, query: AdminDashboardAnalyticsQueryDto) {
|
async getAnalytics(
|
||||||
const today = startOfDay(new Date());
|
actorId: bigint,
|
||||||
const defaultFrom = new Date(today);
|
query: AdminDashboardAnalyticsQueryDto,
|
||||||
defaultFrom.setDate(defaultFrom.getDate() - 29);
|
): Promise<DashboardAnalytics> {
|
||||||
|
const grain: DashboardGranularity = query.granularity ?? 'day';
|
||||||
const from =
|
const defaults = defaultShanghaiRangeYmds(grain);
|
||||||
(query.dateFrom ? parseYmd(query.dateFrom) : null) ?? defaultFrom;
|
const fromYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateFrom ?? '')
|
||||||
const to =
|
? query.dateFrom!
|
||||||
(query.dateTo ? parseYmd(query.dateTo) : null) ?? today;
|
: defaults.from;
|
||||||
const rangeStart = startOfDay(from <= to ? from : to);
|
const toYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateTo ?? '') ? query.dateTo! : defaults.to;
|
||||||
const rangeEnd = endOfDay(from <= to ? to : from);
|
const fromDay = parseShanghaiYmd(fromYmd <= toYmd ? fromYmd : toYmd);
|
||||||
|
const toDay = parseShanghaiYmd(fromYmd <= toYmd ? toYmd : fromYmd);
|
||||||
|
const rangeStart = fromDay;
|
||||||
|
const rangeEndExclusive = addShanghaiDays(toDay, 1);
|
||||||
|
|
||||||
const [{ keys, isSuperAdmin }, scope] = await Promise.all([
|
const [{ keys, isSuperAdmin }, scope] = await Promise.all([
|
||||||
this.hqPermissions.resolveAccess(actorId),
|
this.hqPermissions.resolveAccess(actorId),
|
||||||
@@ -314,518 +293,46 @@ export class AdminDashboardService {
|
|||||||
]);
|
]);
|
||||||
const can = (k: HqPermissionKey) => isSuperAdmin || keys.includes(k);
|
const can = (k: HqPermissionKey) => isSuperAdmin || keys.includes(k);
|
||||||
|
|
||||||
let filterCityCode: string | string[] | null | undefined;
|
let city: CityFilter = { kind: 'all' };
|
||||||
let filterCityId: bigint | bigint[] | null | undefined;
|
|
||||||
if (query.cityId === 'none') {
|
if (query.cityId === 'none') {
|
||||||
if (scope !== null) {
|
if (scope !== null) throw new ForbiddenException('无权按未选城筛选');
|
||||||
throw new ForbiddenException('无权按未选城筛选');
|
city = { kind: 'none' };
|
||||||
}
|
|
||||||
filterCityCode = null;
|
|
||||||
filterCityId = null;
|
|
||||||
} else if (query.cityId) {
|
} else if (query.cityId) {
|
||||||
const city = await this.prisma.commonCity.findUnique({
|
const row = await this.prisma.commonCity.findUnique({
|
||||||
where: { id: BigInt(query.cityId) },
|
where: { id: BigInt(query.cityId) },
|
||||||
select: { id: true, code: true },
|
select: { id: true, code: true },
|
||||||
});
|
});
|
||||||
if (!city) {
|
if (!row) throw new ForbiddenException('无权访问该城市的门店');
|
||||||
throw new ForbiddenException('无权访问该城市的门店');
|
assertHqCityInScope(scope, row.id);
|
||||||
}
|
city = { kind: 'ids', ids: [row.id], codes: [row.code] };
|
||||||
assertHqCityInScope(scope, city.id);
|
|
||||||
filterCityCode = city.code;
|
|
||||||
filterCityId = city.id;
|
|
||||||
} else if (scope !== null) {
|
} else if (scope !== null) {
|
||||||
if (!scope.length) {
|
if (!scope.length) {
|
||||||
filterCityId = [];
|
city = { kind: 'empty' };
|
||||||
filterCityCode = [];
|
|
||||||
} else {
|
} else {
|
||||||
const scopedCities = await this.prisma.commonCity.findMany({
|
const scopedCities = await this.prisma.commonCity.findMany({
|
||||||
where: { id: { in: scope } },
|
where: { id: { in: scope } },
|
||||||
select: { id: true, code: true },
|
select: { id: true, code: true },
|
||||||
});
|
});
|
||||||
filterCityId = scope;
|
city = { kind: 'ids', ids: scope, codes: scopedCities.map((c) => c.code) };
|
||||||
filterCityCode = scopedCities.map((c) => c.code);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const filterPromoNone = query.promoCodeId === 'none';
|
const buckets = eachShanghaiBuckets(rangeStart, toDay, grain);
|
||||||
const filterPromoId =
|
const charts = await loadDashboardLineCharts({
|
||||||
can('promo_codes') && query.promoCodeId && query.promoCodeId !== 'none'
|
prisma: this.prisma,
|
||||||
? BigInt(query.promoCodeId)
|
grain,
|
||||||
: undefined;
|
city,
|
||||||
const filterPartnerId =
|
rangeStart,
|
||||||
can('partners') && query.partnerAccountId
|
rangeEndExclusive,
|
||||||
? BigInt(query.partnerAccountId)
|
periodKeys: buckets.map((b) => b.key),
|
||||||
: undefined;
|
can,
|
||||||
|
});
|
||||||
if (filterPartnerId !== undefined && scope !== null) {
|
|
||||||
const partner = await this.prisma.partnerAccount.findUnique({
|
|
||||||
where: { id: filterPartnerId },
|
|
||||||
select: { cityId: true },
|
|
||||||
});
|
|
||||||
if (partner?.cityId) {
|
|
||||||
assertHqCityInScope(scope, partner.cityId);
|
|
||||||
} else if (scope !== null) {
|
|
||||||
throw new ForbiddenException('无权访问该城市的门店');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const userWhere: Prisma.UserWhereInput = {
|
|
||||||
status: 1,
|
|
||||||
mergedIntoUserId: null,
|
|
||||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
|
||||||
};
|
|
||||||
if (filterCityCode === null) {
|
|
||||||
userWhere.OR = [
|
|
||||||
{ cityPreference: null },
|
|
||||||
{ cityPreference: { selectedCityCode: null } },
|
|
||||||
];
|
|
||||||
} else if (Array.isArray(filterCityCode)) {
|
|
||||||
userWhere.cityPreference = {
|
|
||||||
selectedCityCode: { in: filterCityCode.length ? filterCityCode : [''] },
|
|
||||||
};
|
|
||||||
} else if (filterCityCode) {
|
|
||||||
userWhere.cityPreference = { selectedCityCode: filterCityCode };
|
|
||||||
}
|
|
||||||
if (can('promo_codes') && filterPromoNone) {
|
|
||||||
userWhere.promoTouch = { is: null };
|
|
||||||
} else if (filterPromoId !== undefined) {
|
|
||||||
userWhere.promoTouch = { promoCodeId: filterPromoId };
|
|
||||||
}
|
|
||||||
|
|
||||||
const orderWhere: Prisma.OrderWhereInput = {
|
|
||||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
|
||||||
};
|
|
||||||
if (filterCityId === null) {
|
|
||||||
orderWhere.id = { in: [] };
|
|
||||||
} else if (Array.isArray(filterCityId)) {
|
|
||||||
orderWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
|
||||||
} else if (filterCityId !== undefined) {
|
|
||||||
orderWhere.cityId = filterCityId;
|
|
||||||
}
|
|
||||||
if (can('promo_codes') && filterPromoNone) {
|
|
||||||
orderWhere.promoCodeId = null;
|
|
||||||
} else if (filterPromoId !== undefined) {
|
|
||||||
orderWhere.promoCodeId = filterPromoId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const partnerWhere: Prisma.PartnerAccountWhereInput = {
|
|
||||||
isPrimary: 1,
|
|
||||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
|
||||||
};
|
|
||||||
if (filterCityId === null) {
|
|
||||||
partnerWhere.cityId = null;
|
|
||||||
} else if (Array.isArray(filterCityId)) {
|
|
||||||
partnerWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
|
||||||
} else if (filterCityId !== undefined) {
|
|
||||||
partnerWhere.cityId = filterCityId;
|
|
||||||
}
|
|
||||||
if (filterPartnerId !== undefined) {
|
|
||||||
partnerWhere.id = filterPartnerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const storeWhere: Prisma.StoreWhereInput = {
|
|
||||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
|
||||||
};
|
|
||||||
if (filterCityId === null) {
|
|
||||||
storeWhere.id = { in: [] };
|
|
||||||
} else if (Array.isArray(filterCityId)) {
|
|
||||||
storeWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
|
||||||
} else if (filterCityId !== undefined) {
|
|
||||||
storeWhere.cityId = filterCityId;
|
|
||||||
}
|
|
||||||
if (filterPartnerId !== undefined) {
|
|
||||||
storeWhere.partnerAccountId = filterPartnerId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const redeemWhere: Prisma.RedeemRecordWhereInput = {
|
|
||||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
|
||||||
};
|
|
||||||
if (filterCityId === null) {
|
|
||||||
redeemWhere.id = { in: [] };
|
|
||||||
} else {
|
|
||||||
const storeFilter: Prisma.StoreWhereInput = {};
|
|
||||||
if (Array.isArray(filterCityId)) {
|
|
||||||
storeFilter.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
|
||||||
} else if (filterCityId !== undefined) {
|
|
||||||
storeFilter.cityId = filterCityId;
|
|
||||||
}
|
|
||||||
if (filterPartnerId !== undefined) storeFilter.partnerAccountId = filterPartnerId;
|
|
||||||
if (Object.keys(storeFilter).length) {
|
|
||||||
redeemWhere.store = storeFilter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const skipOrders = filterCityId === null || !can('orders');
|
|
||||||
const cityListWhere: Prisma.CommonCityWhereInput =
|
|
||||||
scope === null ? {} : { id: { in: scope.length ? scope : [BigInt(0)] } };
|
|
||||||
|
|
||||||
const [users, orders, partners, stores, redeems, cities, promos, partnerNames] =
|
|
||||||
await Promise.all([
|
|
||||||
can('users')
|
|
||||||
? this.prisma.user.findMany({
|
|
||||||
where: userWhere,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
createdAt: true,
|
|
||||||
cityPreference: { select: { selectedCityCode: true } },
|
|
||||||
promoTouch: { select: { promoCodeId: true } },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: emptyRows<
|
|
||||||
Prisma.UserGetPayload<{
|
|
||||||
select: {
|
|
||||||
id: true;
|
|
||||||
createdAt: true;
|
|
||||||
cityPreference: { select: { selectedCityCode: true } };
|
|
||||||
promoTouch: { select: { promoCodeId: true } };
|
|
||||||
};
|
|
||||||
}>
|
|
||||||
>(),
|
|
||||||
skipOrders
|
|
||||||
? emptyRows<
|
|
||||||
Prisma.OrderGetPayload<{
|
|
||||||
select: {
|
|
||||||
id: true;
|
|
||||||
userId: true;
|
|
||||||
createdAt: true;
|
|
||||||
cityId: true;
|
|
||||||
promoCodeId: true;
|
|
||||||
payStatus: true;
|
|
||||||
};
|
|
||||||
}>
|
|
||||||
>()
|
|
||||||
: this.prisma.order.findMany({
|
|
||||||
where: orderWhere,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
userId: true,
|
|
||||||
createdAt: true,
|
|
||||||
cityId: true,
|
|
||||||
promoCodeId: true,
|
|
||||||
payStatus: true,
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
can('partners')
|
|
||||||
? this.prisma.partnerAccount.findMany({
|
|
||||||
where: partnerWhere,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
createdAt: true,
|
|
||||||
cityId: true,
|
|
||||||
companyName: true,
|
|
||||||
name: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: emptyRows<
|
|
||||||
Prisma.PartnerAccountGetPayload<{
|
|
||||||
select: { id: true; createdAt: true; cityId: true; companyName: true; name: true };
|
|
||||||
}>
|
|
||||||
>(),
|
|
||||||
can('stores')
|
|
||||||
? this.prisma.store.findMany({
|
|
||||||
where: storeWhere,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
createdAt: true,
|
|
||||||
cityId: true,
|
|
||||||
partnerAccountId: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: emptyRows<
|
|
||||||
Prisma.StoreGetPayload<{
|
|
||||||
select: { id: true; createdAt: true; cityId: true; partnerAccountId: true };
|
|
||||||
}>
|
|
||||||
>(),
|
|
||||||
can('benefit')
|
|
||||||
? this.prisma.redeemRecord.findMany({
|
|
||||||
where: redeemWhere,
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
createdAt: true,
|
|
||||||
amount: true,
|
|
||||||
settleAmount: true,
|
|
||||||
store: { select: { cityId: true, partnerAccountId: true } },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
: emptyRows<
|
|
||||||
Prisma.RedeemRecordGetPayload<{
|
|
||||||
select: {
|
|
||||||
id: true;
|
|
||||||
createdAt: true;
|
|
||||||
amount: true;
|
|
||||||
settleAmount: true;
|
|
||||||
store: { select: { cityId: true; partnerAccountId: true } };
|
|
||||||
};
|
|
||||||
}>
|
|
||||||
>(),
|
|
||||||
this.prisma.commonCity.findMany({
|
|
||||||
where: cityListWhere,
|
|
||||||
select: { id: true, code: true, name: true },
|
|
||||||
}),
|
|
||||||
can('promo_codes')
|
|
||||||
? this.prisma.commonPromoCode.findMany({
|
|
||||||
select: { id: true, code: true, name: true },
|
|
||||||
})
|
|
||||||
: emptyRows<Prisma.CommonPromoCodeGetPayload<{ select: { id: true; code: true; name: true } }>>(),
|
|
||||||
can('partners') || can('stores') || can('benefit')
|
|
||||||
? this.prisma.partnerAccount.findMany({
|
|
||||||
where: {
|
|
||||||
isPrimary: 1,
|
|
||||||
...(cityIdFilter(scope) ? { cityId: cityIdFilter(scope) } : {}),
|
|
||||||
},
|
|
||||||
select: { id: true, companyName: true, name: true },
|
|
||||||
})
|
|
||||||
: emptyRows<
|
|
||||||
Prisma.PartnerAccountGetPayload<{
|
|
||||||
select: { id: true; companyName: true; name: true };
|
|
||||||
}>
|
|
||||||
>(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const cityByCode = new Map(cities.map((c) => [c.code, c]));
|
|
||||||
const cityById = new Map(cities.map((c) => [c.id.toString(), c]));
|
|
||||||
const promoById = new Map(promos.map((p) => [p.id.toString(), p]));
|
|
||||||
const partnerLabel = new Map(
|
|
||||||
partnerNames.map((p) => [
|
|
||||||
p.id.toString(),
|
|
||||||
p.companyName || p.name || `合伙人#${p.id}`,
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const dateKeys = eachDate(rangeStart, rangeEnd);
|
|
||||||
type DateBucket = {
|
|
||||||
date: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
partners: number;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
};
|
|
||||||
const byDateMap = new Map<string, DateBucket>(
|
|
||||||
dateKeys.map((d) => [
|
|
||||||
d,
|
|
||||||
{ date: d, users: 0, orders: 0, partners: 0, stores: 0, redeems: 0, redeemAmount: 0 },
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
type CityBucket = {
|
|
||||||
cityId: string;
|
|
||||||
cityName: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
partners: number;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
};
|
|
||||||
const byCityMap = new Map<string, CityBucket>();
|
|
||||||
|
|
||||||
type PromoBucket = {
|
|
||||||
promoCodeId: string | null;
|
|
||||||
code: string;
|
|
||||||
name: string;
|
|
||||||
users: number;
|
|
||||||
orders: number;
|
|
||||||
};
|
|
||||||
const byPromoMap = new Map<string, PromoBucket>();
|
|
||||||
|
|
||||||
type PartnerBucket = {
|
|
||||||
partnerAccountId: string;
|
|
||||||
companyName: string;
|
|
||||||
stores: number;
|
|
||||||
redeems: number;
|
|
||||||
redeemAmount: number;
|
|
||||||
};
|
|
||||||
const byPartnerMap = new Map<string, PartnerBucket>();
|
|
||||||
|
|
||||||
const ensureCity = (key: string, cityId: string, cityName: string) => {
|
|
||||||
let b = byCityMap.get(key);
|
|
||||||
if (!b) {
|
|
||||||
b = {
|
|
||||||
cityId,
|
|
||||||
cityName,
|
|
||||||
users: 0,
|
|
||||||
orders: 0,
|
|
||||||
partners: 0,
|
|
||||||
stores: 0,
|
|
||||||
redeems: 0,
|
|
||||||
redeemAmount: 0,
|
|
||||||
};
|
|
||||||
byCityMap.set(key, b);
|
|
||||||
}
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ensurePromo = (
|
|
||||||
key: string,
|
|
||||||
promoCodeId: string | null,
|
|
||||||
code: string,
|
|
||||||
name: string,
|
|
||||||
) => {
|
|
||||||
let b = byPromoMap.get(key);
|
|
||||||
if (!b) {
|
|
||||||
b = { promoCodeId, code, name, users: 0, orders: 0 };
|
|
||||||
byPromoMap.set(key, b);
|
|
||||||
}
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ensurePartner = (key: string, companyName: string) => {
|
|
||||||
let b = byPartnerMap.get(key);
|
|
||||||
if (!b) {
|
|
||||||
b = {
|
|
||||||
partnerAccountId: key,
|
|
||||||
companyName,
|
|
||||||
stores: 0,
|
|
||||||
redeems: 0,
|
|
||||||
redeemAmount: 0,
|
|
||||||
};
|
|
||||||
byPartnerMap.set(key, b);
|
|
||||||
}
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const u of users) {
|
|
||||||
const d = formatYmd(u.createdAt);
|
|
||||||
const day = byDateMap.get(d);
|
|
||||||
if (day) day.users += 1;
|
|
||||||
|
|
||||||
const code = u.cityPreference?.selectedCityCode ?? null;
|
|
||||||
if (code && cityByCode.has(code)) {
|
|
||||||
const city = cityByCode.get(code)!;
|
|
||||||
ensureCity(city.id.toString(), city.id.toString(), city.name).users += 1;
|
|
||||||
} else {
|
|
||||||
ensureCity('none', 'none', '未选城').users += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pid = u.promoTouch?.promoCodeId?.toString() ?? null;
|
|
||||||
if (pid && promoById.has(pid)) {
|
|
||||||
const p = promoById.get(pid)!;
|
|
||||||
ensurePromo(pid, pid, p.code, p.name).users += 1;
|
|
||||||
} else {
|
|
||||||
ensurePromo('none', null, 'ORGANIC', '自然量').users += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const payingUserIds = new Set<string>();
|
|
||||||
for (const o of orders) {
|
|
||||||
const d = formatYmd(o.createdAt);
|
|
||||||
const day = byDateMap.get(d);
|
|
||||||
if (day) day.orders += 1;
|
|
||||||
|
|
||||||
const cid = o.cityId.toString();
|
|
||||||
const city = cityById.get(cid);
|
|
||||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).orders += 1;
|
|
||||||
|
|
||||||
const pid = o.promoCodeId?.toString() ?? null;
|
|
||||||
if (pid && promoById.has(pid)) {
|
|
||||||
const p = promoById.get(pid)!;
|
|
||||||
ensurePromo(pid, pid, p.code, p.name).orders += 1;
|
|
||||||
} else {
|
|
||||||
ensurePromo('none', null, 'NONE', '无推广码').orders += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (o.payStatus === 'PAID') {
|
|
||||||
payingUserIds.add(o.userId.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const p of partners) {
|
|
||||||
const d = formatYmd(p.createdAt);
|
|
||||||
const day = byDateMap.get(d);
|
|
||||||
if (day) day.partners += 1;
|
|
||||||
|
|
||||||
if (p.cityId) {
|
|
||||||
const cid = p.cityId.toString();
|
|
||||||
const city = cityById.get(cid);
|
|
||||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).partners += 1;
|
|
||||||
} else {
|
|
||||||
ensureCity('none', 'none', '未绑定城市').partners += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const key = p.id.toString();
|
|
||||||
ensurePartner(key, p.companyName || p.name || `合伙人#${key}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const s of stores) {
|
|
||||||
const d = formatYmd(s.createdAt);
|
|
||||||
const day = byDateMap.get(d);
|
|
||||||
if (day) day.stores += 1;
|
|
||||||
|
|
||||||
const cid = s.cityId.toString();
|
|
||||||
const city = cityById.get(cid);
|
|
||||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).stores += 1;
|
|
||||||
|
|
||||||
const pid = s.partnerAccountId.toString();
|
|
||||||
ensurePartner(pid, partnerLabel.get(pid) || `合伙人#${pid}`).stores += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let redeemAmountTotal = 0;
|
|
||||||
for (const r of redeems) {
|
|
||||||
const amount = num(r.amount);
|
|
||||||
redeemAmountTotal += amount;
|
|
||||||
|
|
||||||
const d = formatYmd(r.createdAt);
|
|
||||||
const day = byDateMap.get(d);
|
|
||||||
if (day) {
|
|
||||||
day.redeems += 1;
|
|
||||||
day.redeemAmount += amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cid = r.store.cityId.toString();
|
|
||||||
const city = cityById.get(cid);
|
|
||||||
const cityBucket = ensureCity(cid, cid, city?.name ?? `城市#${cid}`);
|
|
||||||
cityBucket.redeems += 1;
|
|
||||||
cityBucket.redeemAmount += amount;
|
|
||||||
|
|
||||||
const pid = r.store.partnerAccountId.toString();
|
|
||||||
const partnerBucket = ensurePartner(
|
|
||||||
pid,
|
|
||||||
partnerLabel.get(pid) || `合伙人#${pid}`,
|
|
||||||
);
|
|
||||||
partnerBucket.redeems += 1;
|
|
||||||
partnerBucket.redeemAmount += amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
const byCity = [...byCityMap.values()].sort(
|
|
||||||
(a, b) =>
|
|
||||||
b.users + b.orders + b.partners + b.stores + b.redeems -
|
|
||||||
(a.users + a.orders + a.partners + a.stores + a.redeems),
|
|
||||||
);
|
|
||||||
const byPromo = [...byPromoMap.values()].sort(
|
|
||||||
(a, b) => b.users + b.orders - (a.users + a.orders),
|
|
||||||
);
|
|
||||||
const byPartner = [...byPartnerMap.values()].sort(
|
|
||||||
(a, b) => b.stores + b.redeems - (a.stores + a.redeems),
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
summary: {
|
granularity: grain,
|
||||||
users: users.length,
|
range: { from: shanghaiYmd(fromDay), to: shanghaiYmd(toDay) },
|
||||||
orders: orders.length,
|
periods: buckets.map((b) => ({ key: b.key, label: b.label })),
|
||||||
payingUsers: payingUserIds.size,
|
charts,
|
||||||
partners: partners.length,
|
|
||||||
stores: stores.length,
|
|
||||||
redeems: redeems.length,
|
|
||||||
redeemAmount: Math.round(redeemAmountTotal * 100) / 100,
|
|
||||||
},
|
|
||||||
byDate: dateKeys.map((d) => {
|
|
||||||
const row = byDateMap.get(d)!;
|
|
||||||
return {
|
|
||||||
...row,
|
|
||||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
byCity: byCity.map((row) => ({
|
|
||||||
...row,
|
|
||||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
|
||||||
})),
|
|
||||||
byPromo,
|
|
||||||
byPartner: byPartner.map((row) => ({
|
|
||||||
...row,
|
|
||||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
|
||||||
})),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { BadRequestException, Body, Controller, Get, Param, Post, Put, UseGuards } from '@nestjs/common';
|
||||||
|
import type { UpdateWecomReportPushRequest } from '@dukang/shared-types';
|
||||||
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
|
import {
|
||||||
|
HqPermissionGuard,
|
||||||
|
RequireHqPermissions,
|
||||||
|
} from '../../common/guards/hq-permission.guard';
|
||||||
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
|
import { AdminWecomReportsService } from './admin-wecom-reports.service';
|
||||||
|
|
||||||
|
@Controller('admin/wecom-reports')
|
||||||
|
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||||
|
@RequireHqPermissions('wecom_bots')
|
||||||
|
export class AdminWecomReportsController {
|
||||||
|
constructor(private readonly service: AdminWecomReportsService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
list() {
|
||||||
|
return this.service.list();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':kind')
|
||||||
|
detail(@Param('kind') kind: string) {
|
||||||
|
return this.service.detail(this.service.parseKind(kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put(':kind')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_REPORT_UPDATE,
|
||||||
|
refType: 'WECOM_REPORT',
|
||||||
|
refIdField: 'kind',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
update(@Param('kind') kind: string, @Body() body: UpdateWecomReportPushRequest) {
|
||||||
|
return this.service.update(this.service.parseKind(kind), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':kind/preview')
|
||||||
|
preview(@Param('kind') kind: string) {
|
||||||
|
return this.service.preview(this.service.parseKind(kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':kind/send')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_REPORT_SEND,
|
||||||
|
refType: 'WECOM_REPORT',
|
||||||
|
refIdField: 'kind',
|
||||||
|
})
|
||||||
|
async send(@Param('kind') kind: string) {
|
||||||
|
const result = await this.service.send(this.service.parseKind(kind));
|
||||||
|
if (!result.ok) throw new BadRequestException(result.message);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,381 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
Logger,
|
||||||
|
NotFoundException,
|
||||||
|
OnModuleInit,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Cron } from '@nestjs/schedule';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
formatWecomReportMarkdown,
|
||||||
|
isWecomReportKind,
|
||||||
|
wecomReportCutoff,
|
||||||
|
wecomReportPeriod,
|
||||||
|
wecomReportShouldFire,
|
||||||
|
type WecomReportKind,
|
||||||
|
type WecomReportStats,
|
||||||
|
} from '@dukang/domain';
|
||||||
|
import {
|
||||||
|
maskWecomWebhookUrl,
|
||||||
|
WECOM_REPORT_KIND_LABELS,
|
||||||
|
WECOM_STORE_AUDIT_PLACEHOLDER_WEBHOOK,
|
||||||
|
type UpdateWecomReportPushRequest,
|
||||||
|
type WecomReportPreviewDto,
|
||||||
|
type WecomReportPushDto,
|
||||||
|
type WecomReportSendResultDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { applyWecomAtMentionInContent } from '../../modules/dev-plan/dev-plan-wecom-mention.util';
|
||||||
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
|
|
||||||
|
const KIND_SEED: Array<{
|
||||||
|
kind: WecomReportKind;
|
||||||
|
name: string;
|
||||||
|
sendHour: number;
|
||||||
|
sendMinute: number;
|
||||||
|
}> = [
|
||||||
|
{ kind: 'daily', name: '经营日报', sendHour: 20, sendMinute: 0 },
|
||||||
|
{ kind: 'weekly', name: '经营周报', sendHour: 9, sendMinute: 0 },
|
||||||
|
{ kind: 'monthly', name: '经营月报', sendHour: 9, sendMinute: 0 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function asNumber(v: Prisma.Decimal | number | null | undefined): number {
|
||||||
|
if (v == null) return 0;
|
||||||
|
if (typeof v === 'number') return Number.isFinite(v) ? v : 0;
|
||||||
|
return Number(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampHour(n: number | undefined, fallback: number): number {
|
||||||
|
if (n == null || !Number.isFinite(n)) return fallback;
|
||||||
|
return Math.min(23, Math.max(0, Math.floor(n)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampMinute(n: number | undefined, fallback: number): number {
|
||||||
|
if (n == null || !Number.isFinite(n)) return fallback;
|
||||||
|
return Math.min(59, Math.max(0, Math.floor(n)));
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReportRow = {
|
||||||
|
id: bigint;
|
||||||
|
kind: string;
|
||||||
|
name: string;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean | number;
|
||||||
|
mentionWecomUserId: string | null;
|
||||||
|
sendHour: number;
|
||||||
|
sendMinute: number;
|
||||||
|
sendWeekday: number;
|
||||||
|
sendMonthDay: number;
|
||||||
|
lastSentPeriod: string | null;
|
||||||
|
lastSentAt: Date | null;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
function asBool(v: boolean | number): boolean {
|
||||||
|
return v === true || v === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminWecomReportsService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(AdminWecomReportsService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly wecomPush: WecomMessagePushService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(
|
||||||
|
`wecom report ensureDefaults failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async ensureDefaults(): Promise<void> {
|
||||||
|
for (const seed of KIND_SEED) {
|
||||||
|
await this.prisma.$executeRaw`
|
||||||
|
INSERT IGNORE INTO wecom_report_push
|
||||||
|
(kind, name, webhook_url, enabled, send_hour, send_minute, send_weekday, send_month_day)
|
||||||
|
VALUES
|
||||||
|
(${seed.kind}, ${seed.name}, ${WECOM_STORE_AUDIT_PLACEHOLDER_WEBHOOK}, 0, ${seed.sendHour}, ${seed.sendMinute}, 1, 1)
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findByKind(kind: string): Promise<ReportRow | null> {
|
||||||
|
const rows = await this.prisma.$queryRaw<ReportRow[]>`
|
||||||
|
SELECT id, kind, name,
|
||||||
|
webhook_url AS webhookUrl, enabled,
|
||||||
|
mention_wecom_user_id AS mentionWecomUserId,
|
||||||
|
send_hour AS sendHour, send_minute AS sendMinute,
|
||||||
|
send_weekday AS sendWeekday, send_month_day AS sendMonthDay,
|
||||||
|
last_sent_period AS lastSentPeriod, last_sent_at AS lastSentAt,
|
||||||
|
created_at AS createdAt, updated_at AS updatedAt
|
||||||
|
FROM wecom_report_push WHERE kind = ${kind} LIMIT 1
|
||||||
|
`;
|
||||||
|
return rows[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findAll(): Promise<ReportRow[]> {
|
||||||
|
return this.prisma.$queryRaw<ReportRow[]>`
|
||||||
|
SELECT id, kind, name,
|
||||||
|
webhook_url AS webhookUrl, enabled,
|
||||||
|
mention_wecom_user_id AS mentionWecomUserId,
|
||||||
|
send_hour AS sendHour, send_minute AS sendMinute,
|
||||||
|
send_weekday AS sendWeekday, send_month_day AS sendMonthDay,
|
||||||
|
last_sent_period AS lastSentPeriod, last_sent_at AS lastSentAt,
|
||||||
|
created_at AS createdAt, updated_at AS updatedAt
|
||||||
|
FROM wecom_report_push
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
parseKind(raw: string): WecomReportKind {
|
||||||
|
if (!isWecomReportKind(raw)) {
|
||||||
|
throw new BadRequestException('报告类型须为 daily / weekly / monthly');
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(): Promise<WecomReportPushDto[]> {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
const rows = await this.findAll();
|
||||||
|
const byKind = new Map(rows.map((r) => [r.kind, r]));
|
||||||
|
return KIND_SEED.map((s) => {
|
||||||
|
const row = byKind.get(s.kind);
|
||||||
|
if (!row) throw new NotFoundException(`${WECOM_REPORT_KIND_LABELS[s.kind]}未初始化`);
|
||||||
|
return this.toDto(row);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async detail(kind: WecomReportKind): Promise<WecomReportPushDto> {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
const row = await this.findByKind(kind);
|
||||||
|
if (!row) throw new NotFoundException('报告配置不存在');
|
||||||
|
return this.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(kind: WecomReportKind, dto: UpdateWecomReportPushRequest): Promise<WecomReportPushDto> {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
const existing = await this.findByKind(kind);
|
||||||
|
if (!existing) throw new NotFoundException('报告配置不存在');
|
||||||
|
|
||||||
|
const webhookUrl =
|
||||||
|
dto.webhookUrl !== undefined ? dto.webhookUrl.trim() : existing.webhookUrl;
|
||||||
|
if (!webhookUrl) throw new BadRequestException('请填写 Webhook URL');
|
||||||
|
|
||||||
|
const name = dto.name !== undefined ? dto.name.trim() || existing.name : existing.name;
|
||||||
|
const enabled = dto.enabled !== undefined ? (dto.enabled ? 1 : 0) : asBool(existing.enabled) ? 1 : 0;
|
||||||
|
const mention =
|
||||||
|
dto.mentionWecomUserId === undefined
|
||||||
|
? existing.mentionWecomUserId
|
||||||
|
: dto.mentionWecomUserId?.trim() || null;
|
||||||
|
const sendHour = dto.sendHour !== undefined ? clampHour(dto.sendHour, existing.sendHour) : existing.sendHour;
|
||||||
|
const sendMinute =
|
||||||
|
dto.sendMinute !== undefined ? clampMinute(dto.sendMinute, existing.sendMinute) : existing.sendMinute;
|
||||||
|
const sendWeekday =
|
||||||
|
dto.sendWeekday !== undefined
|
||||||
|
? Math.min(7, Math.max(1, Math.floor(dto.sendWeekday) || 1))
|
||||||
|
: existing.sendWeekday;
|
||||||
|
const sendMonthDay =
|
||||||
|
dto.sendMonthDay !== undefined
|
||||||
|
? Math.min(31, Math.max(1, Math.floor(dto.sendMonthDay) || 1))
|
||||||
|
: existing.sendMonthDay;
|
||||||
|
|
||||||
|
await this.prisma.$executeRaw`
|
||||||
|
UPDATE wecom_report_push SET
|
||||||
|
name = ${name},
|
||||||
|
webhook_url = ${webhookUrl},
|
||||||
|
enabled = ${enabled},
|
||||||
|
mention_wecom_user_id = ${mention},
|
||||||
|
send_hour = ${sendHour},
|
||||||
|
send_minute = ${sendMinute},
|
||||||
|
send_weekday = ${sendWeekday},
|
||||||
|
send_month_day = ${sendMonthDay}
|
||||||
|
WHERE kind = ${kind}
|
||||||
|
`;
|
||||||
|
const row = await this.findByKind(kind);
|
||||||
|
if (!row) throw new NotFoundException('报告配置不存在');
|
||||||
|
return this.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async preview(kind: WecomReportKind): Promise<WecomReportPreviewDto> {
|
||||||
|
const period = wecomReportPeriod(kind);
|
||||||
|
const stats = await this.loadStats(period.start, wecomReportCutoff(period));
|
||||||
|
return {
|
||||||
|
kind,
|
||||||
|
periodKey: period.periodKey,
|
||||||
|
title: period.title,
|
||||||
|
rangeLabel: period.rangeLabel,
|
||||||
|
markdown: formatWecomReportMarkdown(period, stats),
|
||||||
|
stats,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(kind: WecomReportKind, opts?: { markSent?: boolean }): Promise<WecomReportSendResultDto> {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
const row = await this.findByKind(kind);
|
||||||
|
if (!row) throw new NotFoundException('报告配置不存在');
|
||||||
|
const url = row.webhookUrl.trim();
|
||||||
|
if (!url || url.includes('key=PENDING')) {
|
||||||
|
throw new BadRequestException('请先填写有效的企微群机器人 Webhook');
|
||||||
|
}
|
||||||
|
|
||||||
|
const period = wecomReportPeriod(kind);
|
||||||
|
const stats = await this.loadStats(period.start, wecomReportCutoff(period));
|
||||||
|
let content = formatWecomReportMarkdown(period, stats);
|
||||||
|
if (row.mentionWecomUserId) {
|
||||||
|
content = applyWecomAtMentionInContent(content, row.mentionWecomUserId);
|
||||||
|
}
|
||||||
|
const ok = await this.wecomPush.sendMarkdownToWebhook(url, content);
|
||||||
|
if (!ok) {
|
||||||
|
throw new BadRequestException('Webhook 发送失败,请检查地址或群机器人是否可用');
|
||||||
|
}
|
||||||
|
if (opts?.markSent !== false) {
|
||||||
|
const sentAt = new Date();
|
||||||
|
await this.prisma.$executeRaw`
|
||||||
|
UPDATE wecom_report_push
|
||||||
|
SET last_sent_period = ${period.periodKey}, last_sent_at = ${sentAt}
|
||||||
|
WHERE kind = ${kind}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
message: `已发送${WECOM_REPORT_KIND_LABELS[kind]}`,
|
||||||
|
periodKey: period.periodKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cron('* * * * *', { timeZone: 'Asia/Shanghai' })
|
||||||
|
async tickScheduled(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const now = new Date();
|
||||||
|
const rows = await this.findAll();
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!asBool(row.enabled)) continue;
|
||||||
|
if (!isWecomReportKind(row.kind)) continue;
|
||||||
|
const due = wecomReportShouldFire(
|
||||||
|
row.kind,
|
||||||
|
{
|
||||||
|
enabled: asBool(row.enabled),
|
||||||
|
sendHour: row.sendHour,
|
||||||
|
sendMinute: row.sendMinute,
|
||||||
|
sendWeekday: row.sendWeekday,
|
||||||
|
sendMonthDay: row.sendMonthDay,
|
||||||
|
lastSentPeriod: row.lastSentPeriod,
|
||||||
|
},
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
if (!due) continue;
|
||||||
|
try {
|
||||||
|
await this.send(row.kind);
|
||||||
|
this.logger.log(`sent wecom ${row.kind} report period=${wecomReportPeriod(row.kind, now).periodKey}`);
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(
|
||||||
|
`wecom ${row.kind} report send failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadStats(start: Date, cutoff: Date): Promise<WecomReportStats> {
|
||||||
|
const userBase = { status: 1, mergedIntoUserId: null } as const;
|
||||||
|
const partnerBase = { isPrimary: 1 } as const;
|
||||||
|
const paid = { payStatus: 'PAID' as const };
|
||||||
|
|
||||||
|
const [
|
||||||
|
usersTotal,
|
||||||
|
usersIncrement,
|
||||||
|
partnersTotal,
|
||||||
|
partnersIncrement,
|
||||||
|
storesTotal,
|
||||||
|
storesIncrement,
|
||||||
|
ordersTotal,
|
||||||
|
ordersIncrement,
|
||||||
|
orderAmountTotal,
|
||||||
|
orderAmountIncrement,
|
||||||
|
redeemsTotal,
|
||||||
|
redeemsIncrement,
|
||||||
|
redeemAmountTotal,
|
||||||
|
redeemAmountIncrement,
|
||||||
|
] = await Promise.all([
|
||||||
|
this.prisma.user.count({ where: { ...userBase, createdAt: { lt: cutoff } } }),
|
||||||
|
this.prisma.user.count({
|
||||||
|
where: { ...userBase, createdAt: { gte: start, lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.partnerAccount.count({
|
||||||
|
where: { ...partnerBase, createdAt: { lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.partnerAccount.count({
|
||||||
|
where: { ...partnerBase, createdAt: { gte: start, lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.store.count({ where: { createdAt: { lt: cutoff } } }),
|
||||||
|
this.prisma.store.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||||
|
this.prisma.order.count({ where: { createdAt: { lt: cutoff } } }),
|
||||||
|
this.prisma.order.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||||
|
this.prisma.order.aggregate({
|
||||||
|
_sum: { payAmount: true },
|
||||||
|
where: { ...paid, paidAt: { lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.order.aggregate({
|
||||||
|
_sum: { payAmount: true },
|
||||||
|
where: { ...paid, paidAt: { gte: start, lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.redeemRecord.count({ where: { createdAt: { lt: cutoff } } }),
|
||||||
|
this.prisma.redeemRecord.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||||
|
this.prisma.redeemRecord.aggregate({
|
||||||
|
_sum: { amount: true },
|
||||||
|
where: { createdAt: { lt: cutoff } },
|
||||||
|
}),
|
||||||
|
this.prisma.redeemRecord.aggregate({
|
||||||
|
_sum: { amount: true },
|
||||||
|
where: { createdAt: { gte: start, lt: cutoff } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
usersTotal,
|
||||||
|
usersIncrement,
|
||||||
|
partnersTotal,
|
||||||
|
partnersIncrement,
|
||||||
|
storesTotal,
|
||||||
|
storesIncrement,
|
||||||
|
ordersTotal,
|
||||||
|
ordersIncrement,
|
||||||
|
orderAmountTotal: asNumber(orderAmountTotal._sum.payAmount),
|
||||||
|
orderAmountIncrement: asNumber(orderAmountIncrement._sum.payAmount),
|
||||||
|
redeemsTotal,
|
||||||
|
redeemsIncrement,
|
||||||
|
redeemAmountTotal: asNumber(redeemAmountTotal._sum.amount),
|
||||||
|
redeemAmountIncrement: asNumber(redeemAmountIncrement._sum.amount),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDto(row: ReportRow): WecomReportPushDto {
|
||||||
|
return {
|
||||||
|
id: String(row.id),
|
||||||
|
kind: row.kind as WecomReportKind,
|
||||||
|
name: row.name,
|
||||||
|
webhookUrl: row.webhookUrl,
|
||||||
|
webhookUrlMasked: maskWecomWebhookUrl(row.webhookUrl),
|
||||||
|
enabled: asBool(row.enabled),
|
||||||
|
mentionWecomUserId: row.mentionWecomUserId,
|
||||||
|
sendHour: row.sendHour,
|
||||||
|
sendMinute: row.sendMinute,
|
||||||
|
sendWeekday: row.sendWeekday,
|
||||||
|
sendMonthDay: row.sendMonthDay,
|
||||||
|
lastSentPeriod: row.lastSentPeriod,
|
||||||
|
lastSentAt: row.lastSentAt ? row.lastSentAt.toISOString() : null,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -59,4 +59,9 @@ export class AdminXiaofeixiaController {
|
|||||||
getTrack(@Body() body: XiaofeixiaShipmentQueryDto) {
|
getTrack(@Body() body: XiaofeixiaShipmentQueryDto) {
|
||||||
return this.service.getTrack(body);
|
return this.service.getTrack(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('get-sign-photos')
|
||||||
|
getSignPhotos(@Body() body: XiaofeixiaShipmentQueryDto) {
|
||||||
|
return this.service.getSignPhotos(body);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,6 +101,19 @@ export class AdminXiaofeixiaService {
|
|||||||
return this.wrap(() => this.courier.getTrack(query, options));
|
return this.wrap(() => this.courier.getTrack(query, options));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getSignPhotos(dto: XiaofeixiaShipmentQueryDto) {
|
||||||
|
const query = this.mapShipmentQuery(dto);
|
||||||
|
const options = await this.callOptions();
|
||||||
|
return this.wrap(async () => {
|
||||||
|
const dataUris = await this.courier.getSignPhotos(query, options);
|
||||||
|
return {
|
||||||
|
count: dataUris.length,
|
||||||
|
// 联调预览用:完整 dataURI;日志侧已截断
|
||||||
|
data: dataUris,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async callOptions() {
|
private async callOptions() {
|
||||||
const fromDb = await this.fulfillmentProviderService.resolveDefaultXiaofeixiaConfig();
|
const fromDb = await this.fulfillmentProviderService.resolveDefaultXiaofeixiaConfig();
|
||||||
return fromDb ? { xiaofeixia: fromDb } : undefined;
|
return fromDb ? { xiaofeixia: fromDb } : undefined;
|
||||||
|
|||||||
@@ -233,9 +233,13 @@ export class AdminOrdersExportDto {
|
|||||||
columns?: string[];
|
columns?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
/** 概览页折线图:只吃全局粒度 / 日期 / 城市 */
|
||||||
export class AdminDashboardAnalyticsQueryDto {
|
export class AdminDashboardAnalyticsQueryDto {
|
||||||
/** YYYY-MM-DD,默认近 30 天 */
|
@IsOptional()
|
||||||
|
@IsIn(['day', 'week', 'month', 'quarter', 'year'])
|
||||||
|
granularity?: 'day' | 'week' | 'month' | 'quarter' | 'year';
|
||||||
|
|
||||||
|
/** YYYY-MM-DD,默认随粒度 */
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
dateFrom?: string;
|
dateFrom?: string;
|
||||||
@@ -248,16 +252,6 @@ export class AdminDashboardAnalyticsQueryDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
cityId?: string;
|
cityId?: string;
|
||||||
|
|
||||||
/** 推广码 id;`none` = 无归因 / 订单无推广码 */
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
promoCodeId?: string;
|
|
||||||
|
|
||||||
/** 城市合伙人(主账号)id */
|
|
||||||
@IsOptional()
|
|
||||||
@IsString()
|
|
||||||
partnerAccountId?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AdminStoresQueryDto extends PaginationQueryDto {
|
export class AdminStoresQueryDto extends PaginationQueryDto {
|
||||||
|
|||||||
@@ -69,6 +69,8 @@ import { AdminWecomBotsController } from './admin-wecom-bots.controller';
|
|||||||
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
||||||
import { AdminWecomMessagePushesController } from './admin-wecom-message-pushes.controller';
|
import { AdminWecomMessagePushesController } from './admin-wecom-message-pushes.controller';
|
||||||
import { AdminWecomMessagePushesService } from './admin-wecom-message-pushes.service';
|
import { AdminWecomMessagePushesService } from './admin-wecom-message-pushes.service';
|
||||||
|
import { AdminWecomReportsController } from './admin-wecom-reports.controller';
|
||||||
|
import { AdminWecomReportsService } from './admin-wecom-reports.service';
|
||||||
import { AdminWecomPushTemplatesController } from './admin-wecom-push-templates.controller';
|
import { AdminWecomPushTemplatesController } from './admin-wecom-push-templates.controller';
|
||||||
import { AdminWecomBotLogsController } from './admin-wecom-bot-logs.controller';
|
import { AdminWecomBotLogsController } from './admin-wecom-bot-logs.controller';
|
||||||
import { AdminWecomBotLogsService } from './admin-wecom-bot-logs.service';
|
import { AdminWecomBotLogsService } from './admin-wecom-bot-logs.service';
|
||||||
@@ -128,6 +130,7 @@ import { PartnerActivityPostersController } from './partner-activity-posters.con
|
|||||||
AdminSystemConfigController,
|
AdminSystemConfigController,
|
||||||
AdminWecomBotsController,
|
AdminWecomBotsController,
|
||||||
AdminWecomMessagePushesController,
|
AdminWecomMessagePushesController,
|
||||||
|
AdminWecomReportsController,
|
||||||
AdminWecomPushTemplatesController,
|
AdminWecomPushTemplatesController,
|
||||||
AdminWecomBotLogsController,
|
AdminWecomBotLogsController,
|
||||||
AdminLlmConfigsController,
|
AdminLlmConfigsController,
|
||||||
@@ -166,6 +169,7 @@ import { PartnerActivityPostersController } from './partner-activity-posters.con
|
|||||||
AdminDeployService,
|
AdminDeployService,
|
||||||
AdminWecomBotsService,
|
AdminWecomBotsService,
|
||||||
AdminWecomMessagePushesService,
|
AdminWecomMessagePushesService,
|
||||||
|
AdminWecomReportsService,
|
||||||
AdminWecomBotLogsService,
|
AdminWecomBotLogsService,
|
||||||
AdminLlmConfigsService,
|
AdminLlmConfigsService,
|
||||||
AdminKnowledgeBasesService,
|
AdminKnowledgeBasesService,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
orderTabToStatuses,
|
orderTabToStatuses,
|
||||||
toMinSaleQuantity,
|
toMinSaleQuantity,
|
||||||
validateMinPurchase,
|
validateMinPurchase,
|
||||||
|
validateShippingAddress,
|
||||||
} from '@dukang/domain';
|
} from '@dukang/domain';
|
||||||
import { loadAppConfig, ClientApp, WECHAT_AUTH_REQUIRED } from '@dukang/shared-types';
|
import { loadAppConfig, ClientApp, WECHAT_AUTH_REQUIRED } from '@dukang/shared-types';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
@@ -155,6 +156,19 @@ export class TradeService {
|
|||||||
addressMessage = '该规格不支持跨城配送,请更换为开城城市内的收货地址';
|
addressMessage = '该规格不支持跨城配送,请更换为开城城市内的收货地址';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (addressOk && body.addressId) {
|
||||||
|
const address = await this.prisma.userAddress.findFirst({
|
||||||
|
where: { id: BigInt(body.addressId), userId },
|
||||||
|
});
|
||||||
|
if (address) {
|
||||||
|
const shipping = validateShippingAddress(address);
|
||||||
|
if (!shipping.ok) {
|
||||||
|
addressOk = false;
|
||||||
|
addressMessage = shipping.message || '请完善收货地址(需具体区县)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const bottlesPerUnit = sale.bottlesPerUnit > 0 ? sale.bottlesPerUnit : 1;
|
const bottlesPerUnit = sale.bottlesPerUnit > 0 ? sale.bottlesPerUnit : 1;
|
||||||
@@ -276,6 +290,10 @@ export class TradeService {
|
|||||||
where: { id: BigInt(body.addressId), userId },
|
where: { id: BigInt(body.addressId), userId },
|
||||||
});
|
});
|
||||||
if (!address) throw new BadRequestException('请选择收货地址');
|
if (!address) throw new BadRequestException('请选择收货地址');
|
||||||
|
const shipping = validateShippingAddress(address);
|
||||||
|
if (!shipping.ok) {
|
||||||
|
throw new BadRequestException(shipping.message || '请完善收货地址(需具体区县)');
|
||||||
|
}
|
||||||
receiverName = address.receiverName;
|
receiverName = address.receiverName;
|
||||||
receiverPhone = address.phone;
|
receiverPhone = address.phone;
|
||||||
receiverAddress = `${address.province}${address.city}${address.district}${address.detail}`;
|
receiverAddress = `${address.province}${address.city}${address.district}${address.detail}`;
|
||||||
@@ -1866,6 +1884,15 @@ export class TradeService {
|
|||||||
if (!body.addressDetail?.trim()) {
|
if (!body.addressDetail?.trim()) {
|
||||||
throw new BadRequestException('请填写详细地址');
|
throw new BadRequestException('请填写详细地址');
|
||||||
}
|
}
|
||||||
|
const shipping = validateShippingAddress({
|
||||||
|
province: receiverProvince,
|
||||||
|
city: receiverCity,
|
||||||
|
district: receiverDistrict,
|
||||||
|
detail: body.addressDetail,
|
||||||
|
});
|
||||||
|
if (!shipping.ok) {
|
||||||
|
throw new BadRequestException(shipping.message || '请完善收货地址(需具体区县)');
|
||||||
|
}
|
||||||
receiverAddress = `${receiverProvince}${receiverCity}${receiverDistrict}${body.addressDetail.trim()}`;
|
receiverAddress = `${receiverProvince}${receiverCity}${receiverDistrict}${body.addressDetail.trim()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2281,6 +2308,15 @@ export class TradeService {
|
|||||||
if (!body.addressDetail?.trim()) {
|
if (!body.addressDetail?.trim()) {
|
||||||
throw new BadRequestException('请填写详细地址');
|
throw new BadRequestException('请填写详细地址');
|
||||||
}
|
}
|
||||||
|
const shipping = validateShippingAddress({
|
||||||
|
province: receiverProvince,
|
||||||
|
city: receiverCity,
|
||||||
|
district: receiverDistrict,
|
||||||
|
detail: body.addressDetail,
|
||||||
|
});
|
||||||
|
if (!shipping.ok) {
|
||||||
|
throw new BadRequestException(shipping.message || '请完善收货地址(需具体区县)');
|
||||||
|
}
|
||||||
receiverAddress = `${receiverProvince}${receiverCity}${receiverDistrict}${body.addressDetail.trim()}`;
|
receiverAddress = `${receiverProvince}${receiverCity}${receiverDistrict}${body.addressDetail.trim()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user