Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 42c1b65632 | |||
| de7bd34aa8 | |||
| 68a4b7f984 | |||
| e5fe8b903a | |||
| c6b01def4c | |||
| 63fcf33416 | |||
| 101b27c92c | |||
| 5ed9f79a5e | |||
| 6880b5daf4 | |||
| 1000b489a0 | |||
| 72fef35807 | |||
| f570383717 | |||
| fe557c912d | |||
| 84fb2f314a |
@@ -18,6 +18,7 @@
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"jspdf": "^4.2.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0"
|
||||
|
||||
@@ -51,6 +51,7 @@ import SystemSettingsPage from './pages/SystemSettingsPage';
|
||||
import TestWhitelistPage from './pages/TestWhitelistPage';
|
||||
import WecomBotsPage from './pages/WecomBotsPage';
|
||||
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
||||
import WecomReportsPage from './pages/WecomReportsPage';
|
||||
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
||||
import LlmConfigsPage from './pages/LlmConfigsPage';
|
||||
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={<WecomBotsPage />} />
|
||||
<Route path="/wecom/pushes" element={<WecomMessagePushesPage />} />
|
||||
<Route path="/wecom/reports" element={<WecomReportsPage />} />
|
||||
<Route path="/logs/wecom-bots" element={<WecomBotLogsPage />} />
|
||||
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
||||
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Form, Input, Modal, message } from 'antd';
|
||||
import type { UpdateMyHqCredentialsRequest } from '@dukang/shared-types';
|
||||
import { request, type HqProfile } from '../lib/api';
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
profile: HqProfile | null;
|
||||
onClose: () => void;
|
||||
onUpdated: (profile: HqProfile) => void;
|
||||
};
|
||||
|
||||
export function HqAccountSettingsModal({ open, profile, onClose, onUpdated }: Props) {
|
||||
const [form] = Form.useForm<UpdateMyHqCredentialsRequest & { confirmPassword?: string }>();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
form.setFieldsValue({
|
||||
loginName: profile?.loginName ?? '',
|
||||
oldPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
}, [open, profile, form]);
|
||||
|
||||
async function submit() {
|
||||
const values = await form.validateFields();
|
||||
if (values.newPassword && values.newPassword !== values.confirmPassword) {
|
||||
message.error('两次输入的新密码不一致');
|
||||
return;
|
||||
}
|
||||
const body: UpdateMyHqCredentialsRequest = {};
|
||||
const nextLogin = values.loginName?.trim();
|
||||
if (nextLogin && nextLogin !== (profile?.loginName ?? '')) {
|
||||
body.loginName = nextLogin;
|
||||
}
|
||||
if (values.newPassword?.trim()) {
|
||||
body.newPassword = values.newPassword.trim();
|
||||
if (values.oldPassword?.trim()) body.oldPassword = values.oldPassword.trim();
|
||||
}
|
||||
if (!body.loginName && !body.newPassword) {
|
||||
message.warning('请填写要修改的内容');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await request('/admin/me/credentials', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const updated = await request<HqProfile>('/admin/auth/me');
|
||||
message.success('账号信息已更新');
|
||||
onUpdated(updated);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="账号设置"
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
onOk={() => void submit()}
|
||||
confirmLoading={saving}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="loginName" label="登录用户名" rules={[{ required: true, message: '请输入用户名' }]}>
|
||||
<Input autoComplete="username" placeholder="用于密码登录" />
|
||||
</Form.Item>
|
||||
<Form.Item name="oldPassword" label="当前密码" extra="已设置过密码时,修改密码必填">
|
||||
<Input.Password autoComplete="current-password" placeholder="不修改密码请留空" />
|
||||
</Form.Item>
|
||||
<Form.Item name="newPassword" label="新密码" rules={[{ min: 6, message: '至少 6 位' }]}>
|
||||
<Input.Password autoComplete="new-password" placeholder="不修改请留空" />
|
||||
</Form.Item>
|
||||
<Form.Item name="confirmPassword" label="确认新密码">
|
||||
<Input.Password autoComplete="new-password" placeholder="不修改请留空" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Descriptions,
|
||||
Drawer,
|
||||
@@ -140,6 +141,14 @@ export default function OrderTrackDrawer({
|
||||
</Space>
|
||||
</Image.PreviewGroup>
|
||||
</div>
|
||||
) : nodes.some((n) => n.statusName?.includes('签收') || n.trackInfo?.includes('签收')) ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="暂无签收照片"
|
||||
description="小飞侠 100108 未返回图片(可能是本人签收未拍照,或照片已过期)。可在「小飞侠联调」用运单号复测。"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Typography.Title level={5} style={{ marginTop: 0 }}>
|
||||
|
||||
@@ -30,6 +30,7 @@ import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
||||
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
||||
import { ListColumnPrefsProvider } from '../lib/ListColumnPrefsContext';
|
||||
import { HqAccountSettingsModal } from '../components/HqAccountSettingsModal';
|
||||
|
||||
const { Header, Sider, Content } = Layout;
|
||||
|
||||
@@ -128,6 +129,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
children: [
|
||||
{ key: '/wecom/bots', label: '智能机器人' },
|
||||
{ key: '/wecom/pushes', label: '消息推送' },
|
||||
{ key: '/wecom/reports', label: '报告' },
|
||||
],
|
||||
},
|
||||
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
||||
@@ -185,6 +187,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/activity-posters': 'activity_posters',
|
||||
'/wecom/bots': 'wecom_bots',
|
||||
'/wecom/pushes': 'wecom_bots',
|
||||
'/wecom/reports': 'wecom_bots',
|
||||
'wecom-group': 'wecom_bots',
|
||||
'/llm-configs': 'llm_configs',
|
||||
'/knowledge-bases': 'knowledge_bases',
|
||||
@@ -292,6 +295,7 @@ export default function AdminLayout() {
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [profile, setProfile] = useState<HqProfile | null>(null);
|
||||
const [auditPendingCount, setAuditPendingCount] = useState(0);
|
||||
const [accountSettingsOpen, setAccountSettingsOpen] = useState(false);
|
||||
|
||||
function refreshAuditPendingCount() {
|
||||
Promise.all([
|
||||
@@ -419,11 +423,20 @@ export default function AdminLayout() {
|
||||
<span style={{ color: '#999' }}>
|
||||
{HQ_ROLE_LABELS[profile?.adminRole ?? ''] || profile?.adminRole || ''}
|
||||
</span>
|
||||
<Button type="text" icon={<UserOutlined />} onClick={() => setAccountSettingsOpen(true)}>
|
||||
账号设置
|
||||
</Button>
|
||||
<Button type="text" icon={<LogoutOutlined />} onClick={logout}>
|
||||
退出
|
||||
</Button>
|
||||
</Space>
|
||||
</Header>
|
||||
<HqAccountSettingsModal
|
||||
open={accountSettingsOpen}
|
||||
profile={profile}
|
||||
onClose={() => setAccountSettingsOpen(false)}
|
||||
onUpdated={setProfile}
|
||||
/>
|
||||
<div
|
||||
ref={contentRef}
|
||||
className="admin-layout"
|
||||
|
||||
@@ -6,6 +6,7 @@ export const CLIENT_APP = 'HQ_WEB';
|
||||
export type HqProfile = {
|
||||
id: string;
|
||||
phone: string;
|
||||
loginName?: string | null;
|
||||
name: string;
|
||||
adminRole: string;
|
||||
status: string;
|
||||
@@ -146,50 +147,12 @@ export type DashboardStats = {
|
||||
ordersByStatus: Array<{ status: string; count: number }>;
|
||||
};
|
||||
|
||||
export type DashboardAnalytics = {
|
||||
summary: {
|
||||
users: number;
|
||||
orders: number;
|
||||
payingUsers: number;
|
||||
partners: number;
|
||||
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 {
|
||||
DashboardAnalytics,
|
||||
DashboardGranularity,
|
||||
DashboardLineChart,
|
||||
DashboardLineHref,
|
||||
} from '@dukang/shared-types';
|
||||
|
||||
export type SystemVersion = {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** 将列表可见列 key 追加到导出 query */
|
||||
export function appendExportColumns(qs: URLSearchParams, keys: string[]) {
|
||||
if (keys.length) qs.set('columns', keys.join(','));
|
||||
}
|
||||
|
||||
export function exportColumnsBody(keys: string[]): { columns?: string[] } {
|
||||
return keys.length ? { columns: keys } : {};
|
||||
}
|
||||
@@ -8,8 +8,11 @@ export type StoreCreateForm = {
|
||||
city?: string;
|
||||
district: string;
|
||||
districtCode?: string;
|
||||
/** @deprecated 使用 categoryIds */
|
||||
categoryParentId?: string;
|
||||
categoryId: string;
|
||||
/** @deprecated 使用 categoryIds */
|
||||
categoryId?: string;
|
||||
categoryIds: string[];
|
||||
name: string;
|
||||
phone: string;
|
||||
address: string;
|
||||
@@ -52,7 +55,7 @@ export function validateStoreCreateStep1(
|
||||
| 'partnerAccountId'
|
||||
| 'cityId'
|
||||
| 'regionCodes'
|
||||
| 'categoryId'
|
||||
| 'categoryIds'
|
||||
| 'name'
|
||||
| 'phone'
|
||||
| 'address'
|
||||
@@ -69,7 +72,7 @@ export function validateStoreCreateStep1(
|
||||
if (!form.partnerAccountId) return '请选择开城合伙人';
|
||||
if (!form.regionCodes || form.regionCodes.length < 3) return '请选择省 / 市 / 区县';
|
||||
if (!form.cityId) return '所选地区未匹配到开城城市,请先在「开城 → 城市」配置对应区划';
|
||||
if (!form.categoryId?.trim()) return '请选择门店分类(细类)';
|
||||
if (!form.categoryIds?.length) return '请至少选择一个门店分类(细类)';
|
||||
if (!form.name?.trim()) return '请填写门店名称';
|
||||
if (!form.phone?.trim()) return '请填写门店手机号';
|
||||
if (!PHONE_RE.test(form.phone.trim())) return '门店手机号须为11位手机号';
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
applyColumnPrefs,
|
||||
columnKey,
|
||||
settingItems,
|
||||
visibleColumnKeys,
|
||||
type ListColumnSettingItem,
|
||||
} from './list-column-prefs';
|
||||
import { beginColumnResize, withResizeTitle } from './column-resize';
|
||||
@@ -48,6 +49,16 @@ export function useAdminListColumns<T>(
|
||||
);
|
||||
itemsRef.current = items;
|
||||
|
||||
const exportColumnKeys = useMemo(() => {
|
||||
const keyed = (allColumns as ColumnType<T>[]).map((col, i) => ({
|
||||
col,
|
||||
key: columnKey(col, i),
|
||||
actions: col.title === '操作' || col.key === ACTIONS_COLUMN_KEY || col.key === 'actions',
|
||||
}));
|
||||
const defaultKeys = keyed.filter((c) => !c.actions).map((c) => c.key);
|
||||
return visibleColumnKeys(defaultKeys, pref);
|
||||
}, [allColumns, pref]);
|
||||
|
||||
const serialCol: ColumnType<T> = useMemo(
|
||||
() => ({
|
||||
key: SERIAL_COLUMN_KEY,
|
||||
@@ -171,5 +182,5 @@ export function useAdminListColumns<T>(
|
||||
/>
|
||||
);
|
||||
|
||||
return { columns, settingsButton, settingsModal };
|
||||
return { columns, settingsButton, settingsModal, exportColumnKeys };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
@@ -129,12 +129,18 @@ function formatApiError(err: unknown): string | null {
|
||||
|
||||
export default function CityPartnersPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialCityId = searchParams.get('cityId')?.trim() || '';
|
||||
const [filterForm] = Form.useForm();
|
||||
const [editForm] = Form.useForm();
|
||||
const [createForm] = Form.useForm();
|
||||
const [subForm] = 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>(
|
||||
'/admin/partners',
|
||||
() => {
|
||||
@@ -484,6 +490,7 @@ export default function CityPartnersPage() {
|
||||
form={filterForm}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
initialValues={initialCityId ? { cityId: initialCityId } : undefined}
|
||||
onFinish={(v) => {
|
||||
setFilters(v);
|
||||
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 {
|
||||
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';
|
||||
import { CloudUploadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import { CloudUploadOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
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 {
|
||||
request,
|
||||
type DashboardAnalytics,
|
||||
@@ -17,6 +28,7 @@ import {
|
||||
type SystemVersion,
|
||||
} from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { downloadDashboardChartsPdf } from '../lib/dashboard-charts-pdf';
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
@@ -36,26 +48,121 @@ const DEPLOYED_BY_LABELS: Record<string, string> = {
|
||||
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 PromoOption = { id: string; code: string; name: string };
|
||||
|
||||
type AnalyticsFilters = {
|
||||
granularity: DashboardGranularity;
|
||||
range: [Dayjs, Dayjs];
|
||||
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) {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('granularity', f.granularity);
|
||||
qs.set('dateFrom', f.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('dateTo', f.range[1].format('YYYY-MM-DD'));
|
||||
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();
|
||||
}
|
||||
|
||||
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() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||
const [version, setVersion] = useState<SystemVersion | null>(null);
|
||||
@@ -72,27 +179,27 @@ export default function DashboardPage() {
|
||||
const canStores = has('stores');
|
||||
const canStoreAudits = has('store_audits');
|
||||
const canPartners = has('partners');
|
||||
const canPromo = has('promo_codes');
|
||||
const canFinance = has('finance');
|
||||
const canBenefit = has('benefit');
|
||||
const canDeliveries = has('deliveries');
|
||||
const canTickets = has('tickets');
|
||||
const permsReady = profile !== null;
|
||||
const hasAnalytics = canUsers || canOrders || canPartners || canStores || canBenefit;
|
||||
|
||||
const [filterForm] = Form.useForm<{
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}>();
|
||||
const [filters, setFilters] = useState<AnalyticsFilters>({
|
||||
range: [dayjs().subtract(29, 'day'), dayjs()],
|
||||
granularity: 'day',
|
||||
range: defaultRange('day'),
|
||||
});
|
||||
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
|
||||
const [analyticsLoading, setAnalyticsLoading] = useState(true);
|
||||
const [cities, setCities] = useState<CityOption[]>([]);
|
||||
const [promos, setPromos] = useState<PromoOption[]>([]);
|
||||
const [partners, setPartners] = useState<Array<{ id: string; companyName?: string | null; name: string }>>([]);
|
||||
const [metric, setMetric] = useState<ChartMetric>('total');
|
||||
const [pdfLoading, setPdfLoading] = useState(false);
|
||||
const chartsWrapRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const loadVersion = useCallback(() => {
|
||||
setVersionLoading(true);
|
||||
@@ -136,18 +243,6 @@ export default function DashboardPage() {
|
||||
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setCities(res.items ?? []))
|
||||
.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]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -157,42 +252,22 @@ export default function DashboardPage() {
|
||||
function applyFilters(values: {
|
||||
range?: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}) {
|
||||
const next: AnalyticsFilters = {
|
||||
range: values.range ?? filters.range,
|
||||
setFilters((prev) => ({
|
||||
...prev,
|
||||
range: values.range ?? prev.range,
|
||||
cityId: values.cityId || undefined,
|
||||
promoCodeId: values.promoCodeId || undefined,
|
||||
partnerAccountId: values.partnerAccountId || undefined,
|
||||
};
|
||||
setFilters(next);
|
||||
}));
|
||||
}
|
||||
|
||||
function setCityFilter(cityId: string) {
|
||||
const next = { ...filters, cityId: cityId === filters.cityId ? undefined : cityId };
|
||||
filterForm.setFieldsValue({ cityId: next.cityId });
|
||||
setFilters(next);
|
||||
function setGranularity(granularity: DashboardGranularity) {
|
||||
setFilters((prev) => ({ ...prev, granularity }));
|
||||
}
|
||||
|
||||
function setPromoFilter(promoCodeId: string) {
|
||||
const key = promoCodeId === 'null' || promoCodeId === '' ? 'none' : promoCodeId;
|
||||
const next = {
|
||||
...filters,
|
||||
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 applyDatePreset(kind: 'lastWeek' | 'lastMonth' | 'lastQuarter') {
|
||||
const range = datePresetRange(kind);
|
||||
filterForm.setFieldsValue({ range });
|
||||
setFilters((prev) => ({ ...prev, range }));
|
||||
}
|
||||
|
||||
function handleDeploy() {
|
||||
@@ -217,224 +292,51 @@ export default function DashboardPage() {
|
||||
}
|
||||
|
||||
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(() => {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('createdFrom', filters.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('createdTo', filters.range[1].format('YYYY-MM-DD'));
|
||||
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) });
|
||||
async function handleDownloadPdf() {
|
||||
if (analyticsLoading || chartOptions.length === 0) {
|
||||
message.warning('暂无可下载的图');
|
||||
return;
|
||||
}
|
||||
if (canOrders) {
|
||||
legend.push('订单数');
|
||||
series.push({ name: '订单数', type: 'line', smooth: true, data: rows.map((r) => r.orders) });
|
||||
}
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: legend },
|
||||
grid: { left: 40, right: 20, top: 40, bottom: 40 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series,
|
||||
};
|
||||
}, [analytics, canUsers, canOrders]);
|
||||
|
||||
const byCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
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),
|
||||
const grainLabel = GRAIN_OPTIONS.find((o) => o.value === filters.granularity)?.label ?? filters.granularity;
|
||||
const metricLabel = metric === 'increment' ? '增量' : '总量';
|
||||
const cityLabel = !filters.cityId
|
||||
? (cityScoped ? '全部负责城市' : '全部开城')
|
||||
: filters.cityId === 'none'
|
||||
? '未选城'
|
||||
: (cities.find((c) => c.id === filters.cityId)?.name ?? '城市');
|
||||
const from = filters.range[0].format('YYYY-MM-DD');
|
||||
const to = filters.range[1].format('YYYY-MM-DD');
|
||||
setPdfLoading(true);
|
||||
try {
|
||||
const doms = [
|
||||
...(chartsWrapRef.current?.querySelectorAll<HTMLElement>('[_echarts_instance_]') ?? []),
|
||||
];
|
||||
await downloadDashboardChartsPdf({
|
||||
filename: `数据概览-${metricLabel}-${grainLabel}-${from}_${to}.pdf`,
|
||||
subtitle: `${metricLabel} · ${grainLabel} · ${from} ~ ${to} · ${cityLabel}`,
|
||||
charts: chartOptions.map(({ chart }, index) => ({
|
||||
title: chart.title,
|
||||
instance: doms[index] ? getInstanceByDom(doms[index]) : undefined,
|
||||
})),
|
||||
});
|
||||
} 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 (
|
||||
<div>
|
||||
@@ -574,7 +476,7 @@ export default function DashboardPage() {
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
title="数据统计筛选"
|
||||
title="全局筛选"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Button
|
||||
@@ -592,9 +494,25 @@ export default function DashboardPage() {
|
||||
initialValues={{ range: filters.range }}
|
||||
onFinish={applyFilters}
|
||||
>
|
||||
<Form.Item name="range" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
|
||||
<Form.Item label="粒度">
|
||||
<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 name="cityId" label="城市">
|
||||
<Select
|
||||
allowClear
|
||||
@@ -606,230 +524,49 @@ export default function DashboardPage() {
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{canPromo ? (
|
||||
<Form.Item name="promoCodeId" label="推广码">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部来源"
|
||||
style={{ width: 200 }}
|
||||
options={[
|
||||
{ value: 'none', label: '自然量 / 无推广码' },
|
||||
...promos.map((p) => ({ value: p.id, label: `${p.name}(${p.code})` })),
|
||||
]}
|
||||
<Form.Item label="指标">
|
||||
<Segmented
|
||||
options={METRIC_OPTIONS}
|
||||
value={metric}
|
||||
onChange={(v) => setMetric(v as ChartMetric)}
|
||||
/>
|
||||
</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>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button
|
||||
icon={<DownloadOutlined />}
|
||||
loading={pdfLoading}
|
||||
disabled={!hasAnalytics || analyticsLoading || chartOptions.length === 0}
|
||||
onClick={() => void handleDownloadPdf()}
|
||||
>
|
||||
下载PDF
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
{canUsers || canOrders ? (
|
||||
<Card
|
||||
title={canUsers && canOrders ? '用户 / 订单统计' : canUsers ? '用户统计' : '订单统计'}
|
||||
style={{ marginBottom: 24 }}
|
||||
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>
|
||||
{permsReady && !hasAnalytics ? (
|
||||
<Card style={{ marginBottom: 24 }}>
|
||||
<Typography.Text type="secondary">当前账号无可视指标</Typography.Text>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{canPartners || canStores || canBenefit ? (
|
||||
{hasAnalytics ? (
|
||||
<div ref={chartsWrapRef} style={{ marginBottom: 24 }}>
|
||||
{chartOptions.map(({ chart, option }) => (
|
||||
<Card
|
||||
title={[canPartners && '合伙人', canStores && '门店', canBenefit && '核销'].filter(Boolean).join(' / ') + '统计'}
|
||||
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
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
key={chart.key}
|
||||
title={chart.title}
|
||||
extra={<Link to={listHref(chart.href, filters)}>查看</Link>}
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<ReactECharts
|
||||
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>
|
||||
</Col>
|
||||
{canBenefit ? (
|
||||
<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>
|
||||
<ReactECharts option={option} style={{ height: 320, width: '100%' }} notMerge />
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{canFinance || canTickets ? (
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
import { request } from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { downloadBase64File } from '../lib/exportExcel';
|
||||
import { exportColumnsBody } from '../lib/export-columns';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
import OssUpload from '../components/OssUpload';
|
||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
@@ -62,6 +63,8 @@ export default function DevPlanTasksPage() {
|
||||
const [dispatchOpen, setDispatchOpen] = useState(false);
|
||||
const [batchEditOpen, setBatchEditOpen] = useState(false);
|
||||
const [batchSaving, setBatchSaving] = useState(false);
|
||||
const [creatingVersion, setCreatingVersion] = useState(false);
|
||||
const [newVersionNo, setNewVersionNo] = useState('');
|
||||
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
||||
const [supportTickets, setSupportTickets] = useState<SupportTicketDto[]>([]);
|
||||
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
||||
@@ -172,9 +175,34 @@ export default function DevPlanTasksPage() {
|
||||
|
||||
function openBatchEdit() {
|
||||
batchForm.setFieldsValue({ status: undefined, versionId: undefined });
|
||||
setNewVersionNo('');
|
||||
setBatchEditOpen(true);
|
||||
}
|
||||
|
||||
async function createVersionInBatch() {
|
||||
const versionNo = newVersionNo.trim();
|
||||
if (!versionNo) {
|
||||
message.warning('请输入版本号');
|
||||
return;
|
||||
}
|
||||
setCreatingVersion(true);
|
||||
try {
|
||||
const created = await request<DevPlanVersionDto>('/admin/dev-plan/versions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ versionNo }),
|
||||
});
|
||||
const res = await request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100');
|
||||
setVersions(res.items ?? []);
|
||||
batchForm.setFieldsValue({ versionId: created.id });
|
||||
setNewVersionNo('');
|
||||
message.success(`已创建版本 ${versionNo}`);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '创建失败');
|
||||
} finally {
|
||||
setCreatingVersion(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitBatchEdit() {
|
||||
const values = await batchForm.validateFields();
|
||||
if (!values.status && !values.versionId) {
|
||||
@@ -224,34 +252,6 @@ export default function DevPlanTasksPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function exportTasks(scope: 'filter' | 'selected') {
|
||||
setExporting(true);
|
||||
try {
|
||||
const result = await request<{
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
contentBase64: string;
|
||||
count: number;
|
||||
}>('/admin/dev-plan/tasks/export', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
scope,
|
||||
format: exportFormat,
|
||||
ids: scope === 'selected' ? selectedRowKeys : undefined,
|
||||
status: filters.status || undefined,
|
||||
type: filters.type || undefined,
|
||||
keyword: filters.keyword || undefined,
|
||||
}),
|
||||
});
|
||||
downloadBase64File(result.contentBase64, result.filename, result.mimeType);
|
||||
message.success(`已导出 ${result.count} 条任务`);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '导出失败');
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const baseColumns: ColumnsType<DevPlanTaskDto> = [
|
||||
{
|
||||
title: '任务号',
|
||||
@@ -285,6 +285,7 @@ export default function DevPlanTasksPage() {
|
||||
},
|
||||
{
|
||||
title: '附件',
|
||||
key: 'attachmentUrls',
|
||||
width: 100,
|
||||
render: (_, row) =>
|
||||
row.attachmentUrls?.length ? (
|
||||
@@ -314,6 +315,7 @@ export default function DevPlanTasksPage() {
|
||||
},
|
||||
{
|
||||
title: '关联版本',
|
||||
key: 'versions',
|
||||
dataIndex: 'versions',
|
||||
width: 140,
|
||||
render: (_, row) =>
|
||||
@@ -347,7 +349,36 @@ export default function DevPlanTasksPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('dev-plan-tasks', baseColumns, { page, pageSize });
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('dev-plan-tasks', baseColumns, { page, pageSize });
|
||||
|
||||
async function exportTasks(scope: 'filter' | 'selected') {
|
||||
setExporting(true);
|
||||
try {
|
||||
const result = await request<{
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
contentBase64: string;
|
||||
count: number;
|
||||
}>('/admin/dev-plan/tasks/export', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
scope,
|
||||
format: exportFormat,
|
||||
ids: scope === 'selected' ? selectedRowKeys : undefined,
|
||||
status: filters.status || undefined,
|
||||
type: filters.type || undefined,
|
||||
keyword: filters.keyword || undefined,
|
||||
...exportColumnsBody(exportColumnKeys),
|
||||
}),
|
||||
});
|
||||
downloadBase64File(result.contentBase64, result.filename, result.mimeType);
|
||||
message.success(`已导出 ${result.count} 条任务`);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '导出失败');
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -541,6 +572,19 @@ export default function DevPlanTasksPage() {
|
||||
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="创建新版本">
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input
|
||||
placeholder="版本号,如 v4.0.11"
|
||||
value={newVersionNo}
|
||||
onChange={(e) => setNewVersionNo(e.target.value)}
|
||||
onPressEnter={() => void createVersionInBatch()}
|
||||
/>
|
||||
<Button loading={creatingVersion} onClick={() => void createVersionInBatch()}>
|
||||
创建
|
||||
</Button>
|
||||
</Space.Compact>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
|
||||
@@ -57,6 +57,7 @@ export default function DevPlanVersionsPage() {
|
||||
useAdminList<DevPlanVersionDto>('/admin/dev-plan/versions', () => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.keyword) qs.set('keyword', filters.keyword);
|
||||
return qs;
|
||||
}, [filters]);
|
||||
|
||||
@@ -190,6 +191,9 @@ export default function DevPlanVersionsPage() {
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
||||
</Form.Item>
|
||||
<Form.Item name="keyword" label="查找">
|
||||
<Input allowClear placeholder="版本号或内容" style={{ width: 220 }} />
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
筛选
|
||||
</Button>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
} from '@dukang/shared-types';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { appendExportColumns } from '../lib/export-columns';
|
||||
import { request } from '../lib/api';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
@@ -98,6 +100,7 @@ const STATUS_COLORS: Record<string, string> = {
|
||||
};
|
||||
|
||||
export default function LogisticsBillsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm();
|
||||
const [summaryForm] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||
@@ -202,6 +205,7 @@ export default function LogisticsBillsPage() {
|
||||
if (filters.providerId) qs.set('providerId', filters.providerId);
|
||||
if (filters.year) qs.set('year', filters.year);
|
||||
if (filters.month) qs.set('month', filters.month);
|
||||
appendExportColumns(qs, exportColumnKeys);
|
||||
const result = await request<{ csv: string; count: number }>(
|
||||
`/admin/logistics-bills/export?${qs}`,
|
||||
);
|
||||
@@ -250,6 +254,7 @@ export default function LogisticsBillsPage() {
|
||||
const billColumns: ColumnsType<BillRow> = [
|
||||
{
|
||||
title: '账单号',
|
||||
key: '账单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 170,
|
||||
render: (v, row) => (
|
||||
@@ -258,42 +263,49 @@ export default function LogisticsBillsPage() {
|
||||
},
|
||||
{
|
||||
title: '承运商',
|
||||
key: '承运商',
|
||||
width: 140,
|
||||
render: (_, r) => `${r.providerName || ''} (${r.providerCode || ''})`,
|
||||
},
|
||||
{
|
||||
title: '账期',
|
||||
key: '账期',
|
||||
width: 200,
|
||||
render: (_, r) =>
|
||||
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
||||
},
|
||||
{
|
||||
title: '结算方式',
|
||||
key: '结算方式',
|
||||
dataIndex: 'settlementMethod',
|
||||
width: 100,
|
||||
render: (v) =>
|
||||
LOGISTICS_SETTLEMENT_METHOD_LABELS[v as LogisticsSettlementMethod] || v,
|
||||
},
|
||||
{ title: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||
{ title: '瓶数', dataIndex: 'bottleCount', width: 80 },
|
||||
{ title: '订单数', key: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||
{ title: '瓶数', key: '瓶数', dataIndex: 'bottleCount', width: 80 },
|
||||
{
|
||||
title: '物流费',
|
||||
key: '物流费',
|
||||
dataIndex: 'logisticsAmount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '收款户名',
|
||||
key: '收款户名',
|
||||
width: 100,
|
||||
render: (_, r) => providerBank(r)?.bankAccountName || '—',
|
||||
},
|
||||
{
|
||||
title: '收款账号',
|
||||
key: '收款账号',
|
||||
width: 140,
|
||||
render: (_, r) => providerBank(r)?.bankAccountNo || '—',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
||||
@@ -398,7 +410,7 @@ export default function LogisticsBillsPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-logistics-bills', billColumns, {
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-logistics-bills', billColumns, {
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
@@ -627,7 +639,20 @@ export default function LogisticsBillsPage() {
|
||||
pagination={false}
|
||||
dataSource={detail.items ?? []}
|
||||
columns={[
|
||||
{ title: '订单号', dataIndex: 'orderNo' },
|
||||
{
|
||||
title: '订单号',
|
||||
dataIndex: 'orderNo',
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<AdminPrimaryLink
|
||||
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||
>
|
||||
{v}
|
||||
</AdminPrimaryLink>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{ title: '瓶数', dataIndex: 'quantity', width: 70 },
|
||||
{
|
||||
title: '物流费',
|
||||
|
||||
@@ -29,6 +29,7 @@ import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
import { AdminListHeader } from '../components/AdminListHeader';
|
||||
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
|
||||
import { downloadBase64File } from '../lib/exportExcel';
|
||||
import { exportColumnsBody } from '../lib/export-columns';
|
||||
import {
|
||||
ADMIN_OPTIONS_PAGE_SIZE,
|
||||
DELIVERY_PROVIDER_LABELS,
|
||||
@@ -265,8 +266,9 @@ function buildExportPayload(
|
||||
format: OrderExportFormat,
|
||||
filters: OrderExportFilters,
|
||||
selectedIds: string[],
|
||||
columns?: string[],
|
||||
) {
|
||||
const payload: Record<string, unknown> = { scope, format };
|
||||
const payload: Record<string, unknown> = { scope, format, ...exportColumnsBody(columns ?? []) };
|
||||
if (scope === 'selected') {
|
||||
payload.ids = selectedIds;
|
||||
return payload;
|
||||
@@ -325,6 +327,9 @@ export default function OrdersPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialOrderNo = searchParams.get('orderNo')?.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 initialStatuses = useMemo(
|
||||
() => initialStatusParam.split(',').map((s) => s.trim()).filter(Boolean),
|
||||
@@ -387,6 +392,18 @@ export default function OrdersPage() {
|
||||
}
|
||||
}, [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(() => {
|
||||
if (initialStatuses.length) {
|
||||
form.setFieldsValue({ status: initialStatuses });
|
||||
@@ -435,7 +452,7 @@ export default function OrdersPage() {
|
||||
const statusList = statuses.length ? statuses : initialStatuses;
|
||||
for (const status of statusList) qs.append('status', status);
|
||||
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.userKeyword) qs.set('userKeyword', values.userKeyword);
|
||||
if (values.productKeyword) qs.set('productKeyword', values.productKeyword);
|
||||
@@ -443,14 +460,16 @@ export default function OrdersPage() {
|
||||
if (values.deliveryType) qs.set('deliveryType', values.deliveryType);
|
||||
if (values.assocPartnerAccountId) qs.set('assocPartnerAccountId', values.assocPartnerAccountId);
|
||||
if (initialPromoCodeId) qs.set('promoCodeId', initialPromoCodeId);
|
||||
if (values.dateRange?.[0]) qs.set('createdFrom', values.dateRange[0].format('YYYY-MM-DD'));
|
||||
if (values.dateRange?.[1]) qs.set('createdTo', values.dateRange[1].format('YYYY-MM-DD'));
|
||||
const createdFrom = values.dateRange?.[0]?.format('YYYY-MM-DD') || initialCreatedFrom;
|
||||
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}`);
|
||||
setData(res);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [form, page, pageSize, initialOrderNo, initialPromoCodeId, initialStatuses]);
|
||||
}, [form, page, pageSize, initialOrderNo, initialPromoCodeId, initialStatuses, initialCityId, initialCreatedFrom, initialCreatedTo]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
@@ -671,6 +690,7 @@ export default function OrdersPage() {
|
||||
status: selectedStatuses(values.status).length ? values.status : initialStatuses,
|
||||
},
|
||||
selectedRowKeys,
|
||||
exportColumnKeys,
|
||||
);
|
||||
const result = await request<OrderExportResult>('/admin/orders/export', {
|
||||
method: 'POST',
|
||||
@@ -688,6 +708,7 @@ export default function OrdersPage() {
|
||||
const baseColumns: ColumnsType<AdminOrderRow> = [
|
||||
{
|
||||
title: '订单号',
|
||||
key: '订单号',
|
||||
dataIndex: 'orderNo',
|
||||
width: 180,
|
||||
render: (v, row) => (
|
||||
@@ -699,7 +720,7 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '用户',
|
||||
key: 'user',
|
||||
key: '用户',
|
||||
width: 200,
|
||||
render: (_, row) =>
|
||||
row.user?.id ? (
|
||||
@@ -712,12 +733,20 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '商品',
|
||||
key: 'productName',
|
||||
key: '商品',
|
||||
width: 180,
|
||||
render: (_, row) => (
|
||||
<Space size={4} wrap>
|
||||
<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 ? (
|
||||
<Tag color="purple">代下单</Tag>
|
||||
) : null}
|
||||
@@ -726,12 +755,14 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '规格',
|
||||
key: '规格',
|
||||
dataIndex: 'productSpec',
|
||||
width: 140,
|
||||
render: (v: string | undefined) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '数量',
|
||||
key: '数量',
|
||||
dataIndex: 'quantity',
|
||||
width: 80,
|
||||
render: (v: number | undefined, row) =>
|
||||
@@ -739,12 +770,14 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '配送方式',
|
||||
key: '配送方式',
|
||||
dataIndex: 'deliveryType',
|
||||
width: 100,
|
||||
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (s: string) => (
|
||||
@@ -753,42 +786,47 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '实付',
|
||||
key: '实付',
|
||||
dataIndex: 'payAmount',
|
||||
width: 90,
|
||||
render: (v: number) => `¥${v}`,
|
||||
},
|
||||
{
|
||||
title: '运费',
|
||||
key: 'logisticsFee',
|
||||
key: '运费',
|
||||
width: 90,
|
||||
render: (_, row) =>
|
||||
row.delivery?.logisticsFee == null ? '—' : `¥${Number(row.delivery.logisticsFee).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '好客权益',
|
||||
key: '好客权益',
|
||||
width: 200,
|
||||
render: (_, row) => formatBenefitBrief(row),
|
||||
},
|
||||
{
|
||||
title: '收货人',
|
||||
key: '收货人',
|
||||
dataIndex: 'receiverName',
|
||||
width: 90,
|
||||
render: (v: string | undefined) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '电话',
|
||||
key: '电话',
|
||||
dataIndex: 'receiverPhone',
|
||||
width: 120,
|
||||
render: (v: string | undefined) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '地址',
|
||||
key: 'receiverAddress',
|
||||
key: '地址',
|
||||
width: 260,
|
||||
render: (_, row) => formatReceiverAddress(row) || '—',
|
||||
},
|
||||
{
|
||||
title: '下单时间',
|
||||
key: '下单时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: fmtTime,
|
||||
@@ -823,7 +861,7 @@ export default function OrdersPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('orders', baseColumns, {
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('orders', baseColumns, {
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
@@ -1010,7 +1048,7 @@ export default function OrdersPage() {
|
||||
) : <span />}
|
||||
<Space size={12} wrap>
|
||||
<Form.Item name="fulfillmentHold" valuePropName="checked" noStyle>
|
||||
<Checkbox>大单拦截</Checkbox>
|
||||
<Checkbox>履约拦截</Checkbox>
|
||||
</Form.Item>
|
||||
<Button
|
||||
onClick={() => {
|
||||
@@ -1120,7 +1158,7 @@ export default function OrdersPage() {
|
||||
{detail.fulfillmentHold ? (
|
||||
<Tag color="orange">
|
||||
{FULFILLMENT_HOLD_REASON_LABELS[detail.fulfillmentHoldReason || ''] ||
|
||||
'大单待确认'}
|
||||
'履约待确认'}
|
||||
</Tag>
|
||||
) : null}
|
||||
{detail.orderType === 'PROXY' || detail.isProxyOrder ? (
|
||||
@@ -1517,10 +1555,16 @@ export default function OrdersPage() {
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message="大单已拦截自动推小飞侠"
|
||||
message={
|
||||
shipTarget.fulfillmentHoldReason === 'LARGE_ORDER_GE_10_BOXES'
|
||||
? '大单已拦截自动推小飞侠'
|
||||
: shipTarget.fulfillmentHoldReason === 'COURIER_OUT_OF_SERVICE'
|
||||
? '小飞侠超出服务区'
|
||||
: '自动推配送失败'
|
||||
}
|
||||
description={
|
||||
FULFILLMENT_HOLD_REASON_LABELS[shipTarget.fulfillmentHoldReason || ''] ||
|
||||
'≥10箱订单需总部确认:可选仓推小飞侠,或改用快递自配送。'
|
||||
'请确认后:可选仓重推小飞侠,或改用快递自配送。'
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
@@ -22,6 +24,7 @@ import dayjs, { type Dayjs } from 'dayjs';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { appendExportColumns } from '../lib/export-columns';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
import { AdminListHeader } from '../components/AdminListHeader';
|
||||
@@ -48,6 +51,7 @@ type Row = {
|
||||
redeemCommission: number;
|
||||
totalAmount: number;
|
||||
status: string;
|
||||
billDate: string;
|
||||
periodStart: string;
|
||||
periodEnd: string;
|
||||
rejectReason?: string | null;
|
||||
@@ -109,6 +113,7 @@ function weekMonday(d: Dayjs) {
|
||||
}
|
||||
|
||||
export default function PartnerBillsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||
const [partners, setPartners] = useState<PartnerOption[]>([]);
|
||||
@@ -263,6 +268,7 @@ export default function PartnerBillsPage() {
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.partnerId) qs.set('partnerId', filters.partnerId);
|
||||
if (filters.weekStartYmd) qs.set('weekStartYmd', filters.weekStartYmd);
|
||||
appendExportColumns(qs, exportColumnKeys);
|
||||
const result = await request<{ csv: string; count: number }>(`/admin/partner-bills/export?${qs}`);
|
||||
const suffix = filters.weekStartYmd || 'all';
|
||||
downloadExcelCsv(result.csv, `合伙人账单_${suffix}.csv`);
|
||||
@@ -285,6 +291,7 @@ export default function PartnerBillsPage() {
|
||||
const baseColumns: ColumnsType<Row> = [
|
||||
{
|
||||
title: '账单号',
|
||||
key: '账单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 180,
|
||||
render: (v, row) => (
|
||||
@@ -293,29 +300,45 @@ export default function PartnerBillsPage() {
|
||||
},
|
||||
{
|
||||
title: '合伙人',
|
||||
key: '合伙人',
|
||||
width: 200,
|
||||
render: (_, r) => partnerName(r),
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<Tooltip title="周账出账日为账期结束后的下周一;历史月账为次月 1 日">
|
||||
出账日
|
||||
</Tooltip>
|
||||
),
|
||||
key: '出账日',
|
||||
dataIndex: 'billDate',
|
||||
width: 110,
|
||||
render: (v) => String(v || '').slice(0, 10),
|
||||
},
|
||||
{
|
||||
title: '账期',
|
||||
key: '账期',
|
||||
width: 200,
|
||||
render: (_, r) =>
|
||||
`${String(r.periodStart || '').slice(0, 10)} ~ ${String(r.periodEnd || '').slice(0, 10)}`,
|
||||
},
|
||||
{
|
||||
title: '酒单佣金',
|
||||
key: '酒单佣金',
|
||||
dataIndex: 'orderCommission',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '核销佣金',
|
||||
key: '核销佣金',
|
||||
dataIndex: 'redeemCommission',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '合计应付',
|
||||
key: '合计应付',
|
||||
dataIndex: 'totalAmount',
|
||||
width: 130,
|
||||
render: (v) =>
|
||||
@@ -323,16 +346,19 @@ export default function PartnerBillsPage() {
|
||||
},
|
||||
{
|
||||
title: '收款户名',
|
||||
key: '收款户名',
|
||||
width: 100,
|
||||
render: (_, r) => partnerBank(r)?.bankAccountName || '—',
|
||||
},
|
||||
{
|
||||
title: '收款账号',
|
||||
key: '收款账号',
|
||||
width: 140,
|
||||
render: (_, r) => partnerBank(r)?.bankAccountNo || '—',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 130,
|
||||
render: (s, row) => (
|
||||
@@ -380,7 +406,7 @@ export default function PartnerBillsPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-partner-bills', baseColumns, { page, pageSize });
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-partner-bills', baseColumns, { page, pageSize });
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -572,6 +598,7 @@ export default function PartnerBillsPage() {
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
||||
<Descriptions.Item label="合伙人">{partnerName(detail)}</Descriptions.Item>
|
||||
<Descriptions.Item label="出账日">{String(detail.billDate || '').slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账期">
|
||||
{String(detail.periodStart).slice(0, 10)} ~ {String(detail.periodEnd).slice(0, 10)}
|
||||
</Descriptions.Item>
|
||||
@@ -610,7 +637,21 @@ export default function PartnerBillsPage() {
|
||||
pagination={false}
|
||||
dataSource={detail.orderItems ?? []}
|
||||
columns={[
|
||||
{ title: '订单号', dataIndex: 'refNo', width: 160 },
|
||||
{
|
||||
title: '订单号',
|
||||
dataIndex: 'refNo',
|
||||
width: 160,
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<AdminPrimaryLink
|
||||
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||
>
|
||||
{v}
|
||||
</AdminPrimaryLink>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{ title: '商品', dataIndex: 'title' },
|
||||
{ title: '数量', dataIndex: 'extra', width: 70 },
|
||||
{
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { appendExportColumns } from '../lib/export-columns';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
import { AdminListHeader } from '../components/AdminListHeader';
|
||||
@@ -44,6 +45,8 @@ type Row = {
|
||||
amount: number;
|
||||
status: StoreSettlementStatus;
|
||||
date: string;
|
||||
periodStart?: string | null;
|
||||
periodEnd?: string | null;
|
||||
overdue?: boolean;
|
||||
redeemCount?: number | null;
|
||||
redeemAmount?: number | null;
|
||||
@@ -198,6 +201,7 @@ export default function StoreBillsPage() {
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
appendExportColumns(qs, exportColumnKeys);
|
||||
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
||||
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
||||
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
||||
@@ -218,6 +222,7 @@ export default function StoreBillsPage() {
|
||||
const baseColumns: ColumnsType<Row> = [
|
||||
{
|
||||
title: '类型',
|
||||
key: '类型',
|
||||
dataIndex: 'kind',
|
||||
width: 100,
|
||||
render: (k: StoreSettlementKind) => (
|
||||
@@ -228,6 +233,7 @@ export default function StoreBillsPage() {
|
||||
},
|
||||
{
|
||||
title: '单号',
|
||||
key: '账单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 180,
|
||||
render: (v, row) => (
|
||||
@@ -243,39 +249,58 @@ export default function StoreBillsPage() {
|
||||
出账日
|
||||
</Tooltip>
|
||||
),
|
||||
key: '出账日',
|
||||
dataIndex: 'date',
|
||||
width: 160,
|
||||
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
|
||||
},
|
||||
{ title: '门店', dataIndex: ['store', 'name'], width: 140 },
|
||||
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||
{
|
||||
title: (
|
||||
<Tooltip title="T+1 账期为出账日前一日的核销窗口;手动提现无账期">
|
||||
账期
|
||||
</Tooltip>
|
||||
),
|
||||
key: '账期',
|
||||
width: 200,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' && row.periodStart
|
||||
? `${row.periodStart} ~ ${row.periodEnd}`
|
||||
: '—',
|
||||
},
|
||||
{ title: '门店', key: '门店', dataIndex: ['store', 'name'], width: 140 },
|
||||
{ title: '登录手机', key: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||
{ title: '城市', key: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||
{
|
||||
title: '收款户名',
|
||||
key: '收款户名',
|
||||
width: 100,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountName || '—' : '—',
|
||||
},
|
||||
{
|
||||
title: '收款账号',
|
||||
key: '收款账号',
|
||||
width: 140,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' ? row.bankAccount?.bankAccountNo || '—' : '—',
|
||||
},
|
||||
{
|
||||
title: '笔数',
|
||||
key: '笔数',
|
||||
width: 80,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
||||
},
|
||||
{
|
||||
title: '应付金额',
|
||||
key: '应付金额',
|
||||
dataIndex: 'amount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (s: string, row) => (
|
||||
@@ -325,7 +350,7 @@ export default function StoreBillsPage() {
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-store-bills', baseColumns, { page, pageSize });
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-store-bills', baseColumns, { page, pageSize });
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -495,6 +520,11 @@ export default function StoreBillsPage() {
|
||||
<Descriptions.Item label="出账日">
|
||||
{String(detail.billDate || '').slice(0, 10)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="账期">
|
||||
{detail.periodStart
|
||||
? `${String(detail.periodStart).slice(0, 10)} ~ ${String(detail.periodEnd || '').slice(0, 10)}`
|
||||
: '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">
|
||||
¥{Number(detail.payoutAmount ?? 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
|
||||
@@ -224,6 +224,7 @@ type StoreRow = {
|
||||
settlementRate?: number;
|
||||
sortOrder?: number;
|
||||
category?: { id: string; name: string; parentId?: string | null } | null;
|
||||
categories?: { id: string; name: string; parentId?: string | null }[] | null;
|
||||
};
|
||||
|
||||
type PartnerOption = { id: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||
@@ -350,29 +351,17 @@ export default function StoresPage() {
|
||||
const selectedPartnerId = Form.useWatch('partnerAccountId', createForm);
|
||||
const selectedRegionCodes = Form.useWatch('regionCodes', createForm);
|
||||
const selectedCityId = Form.useWatch('cityId', createForm);
|
||||
const selectedCategoryParentId = Form.useWatch('categoryParentId', createForm);
|
||||
const editCategoryParentId = Form.useWatch('categoryParentId', editForm);
|
||||
|
||||
const categoryParentOptions = useMemo(
|
||||
() =>
|
||||
categoryTree
|
||||
.filter((n) => n.status !== 'INACTIVE')
|
||||
.map((n) => ({ value: n.id, label: n.name })),
|
||||
[categoryTree],
|
||||
);
|
||||
const categoryChildOptions = useMemo(() => {
|
||||
const parent = categoryTree.find((n) => n.id === selectedCategoryParentId);
|
||||
return (parent?.children ?? [])
|
||||
.filter((n) => n.status !== 'INACTIVE')
|
||||
.map((n) => ({ value: n.id, label: n.name }));
|
||||
}, [categoryTree, selectedCategoryParentId]);
|
||||
|
||||
const editCategoryChildOptions = useMemo(() => {
|
||||
const parent = categoryTree.find((n) => n.id === editCategoryParentId);
|
||||
return (parent?.children ?? [])
|
||||
.filter((n) => n.status !== 'INACTIVE')
|
||||
.map((n) => ({ value: n.id, label: n.name }));
|
||||
}, [categoryTree, editCategoryParentId]);
|
||||
const categoryLeafOptions = useMemo(() => {
|
||||
const options: { value: string; label: string }[] = [];
|
||||
for (const parent of categoryTree) {
|
||||
if (parent.status === 'INACTIVE') continue;
|
||||
for (const child of parent.children ?? []) {
|
||||
if (child.status === 'INACTIVE') continue;
|
||||
options.push({ value: child.id, label: `${parent.name} / ${child.name}` });
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}, [categoryTree]);
|
||||
|
||||
async function deleteStore(id: string) {
|
||||
setDeleting(true);
|
||||
@@ -414,20 +403,14 @@ export default function StoresPage() {
|
||||
bankBranch?: string | null;
|
||||
})
|
||||
: null;
|
||||
const categoryId = category?.id != null ? String(category.id) : undefined;
|
||||
let parentId = category?.parentId != null ? String(category.parentId) : undefined;
|
||||
if (!parentId && categoryId) {
|
||||
for (const parent of cats) {
|
||||
if (parent.id === categoryId) {
|
||||
parentId = parent.id;
|
||||
break;
|
||||
}
|
||||
if ((parent.children ?? []).some((c) => c.id === categoryId)) {
|
||||
parentId = parent.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const categories = Array.isArray(d.categories)
|
||||
? (d.categories as { id?: string }[])
|
||||
: [];
|
||||
const categoryIds = categories.length
|
||||
? categories.map((c) => String(c.id)).filter(Boolean)
|
||||
: category?.id != null
|
||||
? [String(category.id)]
|
||||
: [];
|
||||
const loginPhone =
|
||||
(typeof d.loginPhone === 'string' && d.loginPhone) ||
|
||||
account?.phone ||
|
||||
@@ -466,8 +449,7 @@ export default function StoresPage() {
|
||||
city: d.cityName,
|
||||
district: d.district,
|
||||
address: d.address,
|
||||
categoryParentId: parentId,
|
||||
categoryId,
|
||||
categoryIds,
|
||||
latitude: d.latitude != null ? Number(d.latitude) : undefined,
|
||||
longitude: d.longitude != null ? Number(d.longitude) : undefined,
|
||||
settlementRate: d.settlementRate != null ? Number(d.settlementRate) * 100 : 60,
|
||||
@@ -530,7 +512,7 @@ export default function StoresPage() {
|
||||
!/^null$/i.test(v.benefitUsageRule.trim())
|
||||
? v.benefitUsageRule.trim()
|
||||
: null,
|
||||
categoryId: v.categoryId,
|
||||
categoryIds: v.categoryIds,
|
||||
province: v.province,
|
||||
city: v.city,
|
||||
district: v.district,
|
||||
@@ -661,8 +643,7 @@ export default function StoresPage() {
|
||||
'partnerAccountId',
|
||||
'regionCodes',
|
||||
'cityId',
|
||||
'categoryParentId',
|
||||
'categoryId',
|
||||
'categoryIds',
|
||||
'name',
|
||||
'phone',
|
||||
'address',
|
||||
@@ -691,7 +672,7 @@ export default function StoresPage() {
|
||||
body: JSON.stringify({
|
||||
partnerAccountId: values.partnerAccountId,
|
||||
cityId: values.cityId,
|
||||
categoryId: values.categoryId,
|
||||
categoryIds: values.categoryIds,
|
||||
province: values.province,
|
||||
city: values.city,
|
||||
name: values.name.trim(),
|
||||
@@ -769,8 +750,14 @@ export default function StoresPage() {
|
||||
{
|
||||
key: 'category',
|
||||
title: '分类',
|
||||
width: 100,
|
||||
render: (_, row) => row.category?.name || '—',
|
||||
width: 140,
|
||||
render: (_, row) => {
|
||||
const cats = Array.isArray(row.categories)
|
||||
? row.categories.map((c: { name?: string }) => c.name).filter(Boolean)
|
||||
: [];
|
||||
if (cats.length) return cats.join('、');
|
||||
return row.category?.name || '—';
|
||||
},
|
||||
},
|
||||
{ key: 'cityName', title: '城市', dataIndex: 'cityName', width: 80 },
|
||||
{ key: 'phone', title: '登录号', dataIndex: 'phone', width: 120 },
|
||||
@@ -1156,29 +1143,17 @@ export default function StoresPage() {
|
||||
<Input placeholder="手机号或座机,如 0379-8888888" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="categoryParentId"
|
||||
label="门店分类(大类)"
|
||||
rules={[{ required: true, message: '请选择门店大类' }]}
|
||||
name="categoryIds"
|
||||
label="门店分类(细类,可多选)"
|
||||
rules={[{ required: true, message: '请至少选择一个门店细类' }]}
|
||||
>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
loading={optionsLoading}
|
||||
optionFilterProp="label"
|
||||
options={categoryParentOptions}
|
||||
onChange={() => editForm.setFieldValue('categoryId', undefined)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="categoryId"
|
||||
label="门店分类(细类)"
|
||||
rules={[{ required: true, message: '请选择门店细类' }]}
|
||||
>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder={editCategoryParentId ? '选择细类' : '请先选大类'}
|
||||
disabled={!editCategoryParentId}
|
||||
options={editCategoryChildOptions}
|
||||
placeholder="选择细类,可多选"
|
||||
options={categoryLeafOptions}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="coverUrl" label="封面图 / 门头照">
|
||||
@@ -1457,23 +1432,9 @@ export default function StoresPage() {
|
||||
<Form.Item name="district" hidden><Input /></Form.Item>
|
||||
<Form.Item name="districtCode" hidden><Input /></Form.Item>
|
||||
<Form.Item
|
||||
name="categoryParentId"
|
||||
label="门店分类(大类)"
|
||||
rules={[{ required: true, message: '请选择门店大类' }]}
|
||||
>
|
||||
<Select
|
||||
showSearch
|
||||
loading={optionsLoading}
|
||||
optionFilterProp="label"
|
||||
placeholder={optionsLoading ? '加载中…' : '选择大类'}
|
||||
options={categoryParentOptions}
|
||||
onChange={() => createForm.setFieldValue('categoryId', undefined)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="categoryId"
|
||||
label="门店分类(细类)"
|
||||
rules={[{ required: true, message: '请选择门店细类' }]}
|
||||
name="categoryIds"
|
||||
label="门店分类(细类,可多选)"
|
||||
rules={[{ required: true, message: '请至少选择一个门店细类' }]}
|
||||
extra={
|
||||
<Typography.Link onClick={() => navigate('/store-categories')}>
|
||||
去配置门店分类
|
||||
@@ -1481,11 +1442,12 @@ export default function StoresPage() {
|
||||
}
|
||||
>
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
loading={optionsLoading}
|
||||
optionFilterProp="label"
|
||||
placeholder={selectedCategoryParentId ? '选择细类' : '请先选大类'}
|
||||
disabled={!selectedCategoryParentId}
|
||||
options={categoryChildOptions}
|
||||
placeholder={optionsLoading ? '加载中…' : '选择细类,可多选'}
|
||||
options={categoryLeafOptions}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label="门店名称" rules={[{ required: true, message: '请填写门店名称' }]}>
|
||||
|
||||
@@ -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,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
} from '@dukang/shared-types';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { appendExportColumns } from '../lib/export-columns';
|
||||
import { request, type HqProfile } from '../lib/api';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||
@@ -37,6 +39,8 @@ type Row = {
|
||||
id: string;
|
||||
billNo: string;
|
||||
billDate: string;
|
||||
periodStart: string;
|
||||
periodEnd: string;
|
||||
orderCount: number;
|
||||
orderAmount: number;
|
||||
wineryRate: number;
|
||||
@@ -107,6 +111,7 @@ const WINERY_BANK_KEYS = [
|
||||
] as const;
|
||||
|
||||
export default function WineryBillsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm();
|
||||
const [bankForm] = Form.useForm<Record<string, string>>();
|
||||
const [reconcileForm] = Form.useForm<{ range?: [Dayjs, Dayjs] }>();
|
||||
@@ -196,6 +201,7 @@ export default function WineryBillsPage() {
|
||||
if (filters.month) qs.set('month', filters.month);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
appendExportColumns(qs, exportColumnKeys);
|
||||
const result = await request<{ csv: string; count: number }>(`/admin/winery-bills/export?${qs}`);
|
||||
const suffix = filters.year && filters.month ? `${filters.year}-${filters.month}` : 'all';
|
||||
downloadExcelCsv(result.csv, `酒厂对账单_${suffix}.csv`);
|
||||
@@ -275,6 +281,7 @@ export default function WineryBillsPage() {
|
||||
const baseColumns: ColumnsType<Row> = [
|
||||
{
|
||||
title: '账单号',
|
||||
key: '账单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 170,
|
||||
render: (v, row) => (
|
||||
@@ -284,34 +291,49 @@ export default function WineryBillsPage() {
|
||||
{
|
||||
title: (
|
||||
<Tooltip title="出账当天的北京日历日;T+3 只决定纳入哪天完成的订单">
|
||||
账单日
|
||||
出账日
|
||||
</Tooltip>
|
||||
),
|
||||
key: '出账日',
|
||||
dataIndex: 'billDate',
|
||||
width: 110,
|
||||
render: (v) => String(v || '').slice(0, 10),
|
||||
},
|
||||
{ title: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||
{
|
||||
title: '酒单实付合计',
|
||||
title: (
|
||||
<Tooltip title="纳入本账单的订单完成日区间(含起止日)">
|
||||
账期
|
||||
</Tooltip>
|
||||
),
|
||||
key: '账期',
|
||||
width: 200,
|
||||
render: (_, row) => `${row.periodStart} ~ ${row.periodEnd}`,
|
||||
},
|
||||
{ title: '订单数', key: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||
{
|
||||
title: '订单总额',
|
||||
key: '订单总额',
|
||||
dataIndex: 'orderAmount',
|
||||
width: 120,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '酒厂比例',
|
||||
key: '酒厂比例',
|
||||
dataIndex: 'wineryRate',
|
||||
width: 90,
|
||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
||||
},
|
||||
{
|
||||
title: '应付',
|
||||
key: '应付',
|
||||
dataIndex: 'wineryAmount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
key: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (s, row) => {
|
||||
@@ -338,7 +360,7 @@ export default function WineryBillsPage() {
|
||||
},
|
||||
];
|
||||
|
||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('finance-winery-bills', baseColumns, { page, pageSize });
|
||||
const { columns, settingsButton, settingsModal, exportColumnKeys } = useAdminListColumns('finance-winery-bills', baseColumns, { page, pageSize });
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -365,7 +387,7 @@ export default function WineryBillsPage() {
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space size="large" wrap>
|
||||
<Statistic title="账单数" value={summary.count} />
|
||||
<Statistic title="酒单实付合计" value={summary.orderAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="订单总额" value={summary.orderAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.wineryAmount ?? 0} prefix="¥" precision={2} />
|
||||
</Space>
|
||||
</Card>
|
||||
@@ -460,7 +482,10 @@ export default function WineryBillsPage() {
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">{String(detail.billDate).slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="出账日">{String(detail.billDate).slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账期">
|
||||
{detail.periodStart} ~ {detail.periodEnd}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">¥{Number(detail.wineryAmount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{displayWineryStatus(detail.status, detail.wineryAmount).label}
|
||||
@@ -500,7 +525,20 @@ export default function WineryBillsPage() {
|
||||
pagination={false}
|
||||
dataSource={detail.items ?? []}
|
||||
columns={[
|
||||
{ title: '订单号', dataIndex: 'orderNo' },
|
||||
{
|
||||
title: '订单号',
|
||||
dataIndex: 'orderNo',
|
||||
render: (v: string) =>
|
||||
v ? (
|
||||
<AdminPrimaryLink
|
||||
onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}
|
||||
>
|
||||
{v}
|
||||
</AdminPrimaryLink>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '配送',
|
||||
dataIndex: 'deliveryType',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
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,
|
||||
} from 'antd';
|
||||
import { request } from '../lib/api';
|
||||
@@ -53,6 +53,22 @@ const CREATE_DEFAULTS = {
|
||||
|
||||
function ResultPanel({ result }: { result: ApiResult | null }) {
|
||||
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 (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 8 }}>
|
||||
@@ -64,7 +80,7 @@ function ResultPanel({ result }: { result: ApiResult | null }) {
|
||||
margin: 0, padding: 12, background: '#f5f5f5', borderRadius: 4,
|
||||
maxHeight: 360, overflow: 'auto', fontSize: 12,
|
||||
}}>
|
||||
{JSON.stringify(result, null, 2)}
|
||||
{JSON.stringify(display, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
@@ -81,7 +97,9 @@ export default function XiaofeixiaTestPage() {
|
||||
const [queryForm] = Form.useForm();
|
||||
const [batchForm] = Form.useForm();
|
||||
const [trackForm] = Form.useForm();
|
||||
const [signPhotoForm] = Form.useForm();
|
||||
const [cancelForm] = Form.useForm();
|
||||
const [signPhotoPreview, setSignPhotoPreview] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
void request<XfxConfig>('/admin/courier/xiaofeixia/config').then(setConfig);
|
||||
@@ -99,12 +117,19 @@ export default function XiaofeixiaTestPage() {
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
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('调用成功');
|
||||
else message.warning(res.error || '调用失败');
|
||||
} catch (e) {
|
||||
const err = e instanceof Error ? e.message : String(e);
|
||||
message.error(err);
|
||||
setResult({ ok: false, elapsedMs: 0, error: err });
|
||||
setSignPhotoPreview([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -118,7 +143,7 @@ export default function XiaofeixiaTestPage() {
|
||||
<div>
|
||||
<Typography.Title level={4}>小飞侠接口联调</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
通过 HQ 后台直接调用后端封装的小飞侠 API(cmd 100101~100301)。凭证请在
|
||||
通过 HQ 后台直接调用后端封装的小飞侠 API(cmd 100101~100301,含签收图片 100108)。凭证请在
|
||||
<Link to="/fulfillment-providers">仓配管理</Link>
|
||||
中配置;联调会优先使用仓配管理里启用的小飞侠承运商。
|
||||
</Typography.Paragraph>
|
||||
@@ -273,6 +298,25 @@ export default function XiaofeixiaTestPage() {
|
||||
</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',
|
||||
label: '取消订单 (100103)',
|
||||
@@ -290,6 +334,24 @@ export default function XiaofeixiaTestPage() {
|
||||
<Col xs={24} lg={10}>
|
||||
<Card title="响应结果" size="small">
|
||||
<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>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
@@ -25,7 +25,10 @@ export type StoreDraftForm = {
|
||||
/** 人均费用(选填) */
|
||||
avgPrice: string;
|
||||
categoryParentId: string;
|
||||
/** @deprecated 使用 categoryIds */
|
||||
categoryId: string;
|
||||
/** 二级分类多选 */
|
||||
categoryIds: string[];
|
||||
intro: string;
|
||||
/** 好客权益券使用规则 */
|
||||
benefitUsageRule: string;
|
||||
@@ -68,6 +71,7 @@ export const defaultStoreForm = (): StoreDraftForm => ({
|
||||
avgPrice: '',
|
||||
categoryParentId: '',
|
||||
categoryId: '',
|
||||
categoryIds: [],
|
||||
intro: '',
|
||||
benefitUsageRule: '',
|
||||
coverUrl: '',
|
||||
@@ -122,6 +126,20 @@ export function normalizeStoreDraftForm(raw: Partial<StoreDraftForm> | null | un
|
||||
openTime2: String(raw.openTime2 ?? base.openTime2),
|
||||
closeTime2: String(raw.closeTime2 ?? base.closeTime2),
|
||||
avgPrice: String(raw.avgPrice ?? base.avgPrice),
|
||||
categoryIds: (() => {
|
||||
if (Array.isArray(raw.categoryIds) && raw.categoryIds.length) {
|
||||
return raw.categoryIds.map(String).filter(Boolean);
|
||||
}
|
||||
const legacy = String(raw.categoryId ?? '').trim();
|
||||
return legacy ? [legacy] : base.categoryIds;
|
||||
})(),
|
||||
categoryId: (() => {
|
||||
const ids = Array.isArray(raw.categoryIds) && raw.categoryIds.length
|
||||
? raw.categoryIds.map(String).filter(Boolean)
|
||||
: [];
|
||||
if (ids.length) return ids[0];
|
||||
return String(raw.categoryId ?? base.categoryId);
|
||||
})(),
|
||||
envPhotoUrls: normalizeStringArray(raw.envPhotoUrls, MIN_ENV_PHOTO_COUNT),
|
||||
// 兼容旧草稿:单个 contractUrl 迁移为数组
|
||||
contractUrls: (() => {
|
||||
@@ -201,7 +219,7 @@ export function validateStoreStep1(
|
||||
| 'openTime2'
|
||||
| 'closeTime2'
|
||||
| 'avgPrice'
|
||||
| 'categoryId'
|
||||
| 'categoryIds'
|
||||
| 'intro'
|
||||
| 'benefitUsageRule'
|
||||
>,
|
||||
@@ -233,7 +251,7 @@ export function validateStoreStep1(
|
||||
const n = Number(form.avgPrice);
|
||||
if (Number.isNaN(n) || n < 0) return '人均费用须为非负数字';
|
||||
}
|
||||
if (!form.categoryId.trim()) return '请选择店铺类型';
|
||||
if (!form.categoryIds?.length) return '请至少选择一个店铺类型';
|
||||
if (form.intro.trim()) {
|
||||
const len = form.intro.trim().length;
|
||||
if (len < 2 || len > 500) return '门店简介须为 2~500 字';
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import QRCode from 'qrcode';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
||||
import { validateShippingAddress } from '@dukang/domain';
|
||||
import ChinaRegionPicker from '../components/ChinaRegionPicker';
|
||||
import { getToken, request } from '../lib/api';
|
||||
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
||||
@@ -243,6 +244,13 @@ export default function ProxyOrderPage() {
|
||||
if (!allowOnline) return '该商品不支持线上购买';
|
||||
if (!region?.province || !region?.city || !region?.district) 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 '配送到址须勾选同意自动收货';
|
||||
} else if (!allowOnSite) {
|
||||
return '该商品不支持现场提货';
|
||||
|
||||
@@ -206,9 +206,9 @@ export default function StoreCreatePage() {
|
||||
.then((list) => {
|
||||
const tree = Array.isArray(list) ? list : [];
|
||||
setCategoryTree(tree);
|
||||
if (form.categoryId && !form.categoryParentId) {
|
||||
if (form.categoryIds.length && !form.categoryParentId) {
|
||||
const parent = tree.find((root) =>
|
||||
(root.children ?? []).some((child) => child.id === form.categoryId),
|
||||
(root.children ?? []).some((child) => form.categoryIds.includes(child.id)),
|
||||
);
|
||||
if (parent) patchForm({ categoryParentId: parent.id });
|
||||
}
|
||||
@@ -216,12 +216,6 @@ export default function StoreCreatePage() {
|
||||
.catch(() => setCategoryTree([]));
|
||||
}, []);
|
||||
|
||||
const categoryChildren = useMemo(() => {
|
||||
const parent = categoryTree.find((item) => item.id === form.categoryParentId);
|
||||
return Array.isArray(parent?.children) ? parent!.children! : [];
|
||||
}, [categoryTree, form.categoryParentId]);
|
||||
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -523,7 +517,8 @@ export default function StoreCreatePage() {
|
||||
|
||||
...(form.avgPrice.trim() ? { avgPrice: Number(form.avgPrice) } : {}),
|
||||
|
||||
categoryId: form.categoryId.trim(),
|
||||
categoryIds: form.categoryIds,
|
||||
categoryId: form.categoryIds[0] || form.categoryId.trim(),
|
||||
|
||||
intro: form.intro.trim() || undefined,
|
||||
benefitUsageRule: form.benefitUsageRule.trim() || undefined,
|
||||
@@ -690,56 +685,40 @@ export default function StoreCreatePage() {
|
||||
|
||||
<div className="partner-field">
|
||||
|
||||
<label>店铺类型 <span className="text-primary">*</span></label>
|
||||
|
||||
<div className="partner-input-row" style={{ gap: 8 }}>
|
||||
|
||||
<select
|
||||
|
||||
className="partner-field-input partner-field-input--block"
|
||||
|
||||
value={form.categoryParentId}
|
||||
|
||||
onChange={(e) => patchForm({ categoryParentId: e.target.value, categoryId: '' })}
|
||||
|
||||
aria-label="一级店铺类型"
|
||||
|
||||
>
|
||||
|
||||
<option value="">选择大类</option>
|
||||
|
||||
{categoryTree.map((item) => (
|
||||
|
||||
<option key={item.id} value={item.id}>{item.name}</option>
|
||||
<label>店铺类型 <span className="text-primary">*</span> <span className="label-md text-muted">(可多选)</span></label>
|
||||
|
||||
<div className="partner-category-multi">
|
||||
{categoryTree.map((parent) => (
|
||||
<div key={parent.id} className="partner-category-group">
|
||||
<div className="partner-category-group-title">{parent.name}</div>
|
||||
<div className="partner-category-options">
|
||||
{(parent.children ?? []).map((child) => {
|
||||
const checked = form.categoryIds.includes(child.id);
|
||||
return (
|
||||
<label key={child.id} className="partner-category-option">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => {
|
||||
const next = checked
|
||||
? form.categoryIds.filter((id) => id !== child.id)
|
||||
: [...form.categoryIds, child.id];
|
||||
patchForm({
|
||||
categoryIds: next,
|
||||
categoryId: next[0] ?? '',
|
||||
categoryParentId: next.length
|
||||
? parent.id
|
||||
: form.categoryParentId,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<span>{child.name}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
</select>
|
||||
|
||||
<select
|
||||
|
||||
className="partner-field-input partner-field-input--block"
|
||||
|
||||
value={form.categoryId}
|
||||
|
||||
onChange={(e) => patchForm({ categoryId: e.target.value })}
|
||||
|
||||
disabled={!form.categoryParentId}
|
||||
|
||||
aria-label="二级店铺类型"
|
||||
|
||||
>
|
||||
|
||||
<option value="">{form.categoryParentId ? '选择细类' : '请先选大类'}</option>
|
||||
|
||||
{categoryChildren.map((item) => (
|
||||
|
||||
<option key={item.id} value={item.id}>{item.name}</option>
|
||||
|
||||
))}
|
||||
|
||||
</select>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@dukang/mini-user",
|
||||
"version": "4.0.4",
|
||||
"version": "4.0.10",
|
||||
"private": true,
|
||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||
"scripts": {
|
||||
|
||||
@@ -53,10 +53,10 @@ export default function OrderQtyControls({ value, unitLabel, onChange }: OrderQt
|
||||
onBlur={commit}
|
||||
onConfirm={commit}
|
||||
/>
|
||||
<Text className="order-qty-unit">{unitLabel}</Text>
|
||||
<View className="order-qty-btn" onClick={() => onChange(Math.min(MAX_QTY, current() + 1))}>
|
||||
<Text>+</Text>
|
||||
</View>
|
||||
<Text className="order-qty-unit">{unitLabel}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
getCitiesForPicker,
|
||||
getDistricts,
|
||||
getDistrictsForPicker,
|
||||
getDistrictsForShippingPicker,
|
||||
getProvincesForPicker,
|
||||
normalizeRegionSelection,
|
||||
normalizeShippingRegionSelection,
|
||||
toCityLevelRegion,
|
||||
type RegionSelection,
|
||||
} from '../lib/region-data';
|
||||
@@ -18,6 +20,8 @@ type RegionPickerProps = {
|
||||
onClose: () => void;
|
||||
onConfirm: (region: RegionSelection) => void;
|
||||
levels?: 2 | 3;
|
||||
/** filter:门店筛选可「全市」;shipping:收货地址禁止伪区县 */
|
||||
mode?: 'filter' | 'shipping';
|
||||
};
|
||||
|
||||
type PickerLevel = 'province' | 'city' | 'district';
|
||||
@@ -28,8 +32,13 @@ const ALL_TABS: Array<{ key: PickerLevel; label: string }> = [
|
||||
{ key: 'district', label: '区县' },
|
||||
];
|
||||
|
||||
function initialTab(value: RegionSelection, levels: 2 | 3): PickerLevel {
|
||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
||||
function initialTab(value: RegionSelection, levels: 2 | 3, mode: 'filter' | 'shipping'): PickerLevel {
|
||||
const normalized =
|
||||
levels === 2
|
||||
? toCityLevelRegion(value)
|
||||
: mode === 'shipping'
|
||||
? normalizeShippingRegionSelection(value)
|
||||
: normalizeRegionSelection(value);
|
||||
if (levels === 2) {
|
||||
return normalized.province && normalized.province !== REGION_ALL ? 'city' : 'province';
|
||||
}
|
||||
@@ -54,24 +63,35 @@ export default function RegionPicker({
|
||||
onClose,
|
||||
onConfirm,
|
||||
levels = 3,
|
||||
mode = 'filter',
|
||||
}: RegionPickerProps) {
|
||||
const [draft, setDraft] = useState<RegionSelection>(value);
|
||||
const [activeTab, setActiveTab] = useState<PickerLevel>('province');
|
||||
|
||||
const tabs = levels === 2 ? ALL_TABS.slice(0, 2) : ALL_TABS;
|
||||
const shipping = mode === 'shipping';
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
||||
const normalized =
|
||||
levels === 2
|
||||
? toCityLevelRegion(value)
|
||||
: shipping
|
||||
? normalizeShippingRegionSelection(value)
|
||||
: normalizeRegionSelection(value);
|
||||
setDraft(normalized);
|
||||
setActiveTab(initialTab(value, levels));
|
||||
}, [open, value, levels]);
|
||||
setActiveTab(initialTab(value, levels, mode));
|
||||
}, [open, value, levels, mode, shipping]);
|
||||
|
||||
const listItems = useMemo(() => {
|
||||
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);
|
||||
}, [activeTab, draft.province, draft.city]);
|
||||
}, [activeTab, draft.province, draft.city, shipping]);
|
||||
|
||||
const selectedValue =
|
||||
activeTab === 'province' ? draft.province : activeTab === 'city' ? draft.city : draft.district;
|
||||
@@ -79,12 +99,19 @@ export default function RegionPicker({
|
||||
const canConfirm =
|
||||
levels === 2
|
||||
? Boolean(draft.province && draft.city)
|
||||
: shipping
|
||||
? Boolean(
|
||||
draft.province &&
|
||||
draft.city &&
|
||||
draft.district &&
|
||||
draft.district !== REGION_ALL,
|
||||
)
|
||||
: Boolean(draft.province && draft.city && draft.district);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
function selectProvince(province: string) {
|
||||
if (province === REGION_ALL) {
|
||||
if (!shipping && province === REGION_ALL) {
|
||||
setDraft({ province: REGION_ALL, city: REGION_ALL, district: REGION_ALL });
|
||||
setActiveTab('city');
|
||||
return;
|
||||
@@ -97,12 +124,16 @@ export default function RegionPicker({
|
||||
return;
|
||||
}
|
||||
const nextDistricts = getDistricts(province, city);
|
||||
setDraft({ province, city, district: nextDistricts[0] ?? '' });
|
||||
setDraft({
|
||||
province,
|
||||
city,
|
||||
district: shipping ? '' : (nextDistricts[0] ?? ''),
|
||||
});
|
||||
setActiveTab('city');
|
||||
}
|
||||
|
||||
function selectCity(city: string) {
|
||||
if (city === REGION_ALL) {
|
||||
if (!shipping && city === REGION_ALL) {
|
||||
setDraft({ ...draft, city: REGION_ALL, district: REGION_ALL });
|
||||
if (levels === 3) setActiveTab('district');
|
||||
return;
|
||||
@@ -112,11 +143,16 @@ export default function RegionPicker({
|
||||
return;
|
||||
}
|
||||
const nextDistricts = getDistricts(draft.province, city);
|
||||
setDraft({ ...draft, city, district: nextDistricts[0] ?? '' });
|
||||
setDraft({
|
||||
...draft,
|
||||
city,
|
||||
district: shipping ? '' : (nextDistricts[0] ?? ''),
|
||||
});
|
||||
setActiveTab('district');
|
||||
}
|
||||
|
||||
function selectDistrict(district: string) {
|
||||
if (shipping && district === REGION_ALL) return;
|
||||
setDraft({ ...draft, district });
|
||||
}
|
||||
|
||||
@@ -134,7 +170,13 @@ export default function RegionPicker({
|
||||
|
||||
function handleConfirm() {
|
||||
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);
|
||||
onClose();
|
||||
}
|
||||
|
||||
@@ -30,6 +30,12 @@ export function getDistrictsForPicker(province: string, city: string): string[]
|
||||
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 {
|
||||
if (!province) return '';
|
||||
if (province === REGION_ALL) return REGION_ALL;
|
||||
@@ -96,6 +102,35 @@ export const DEFAULT_REGION: RegionSelection = {
|
||||
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 {
|
||||
const cityName = city.endsWith('市') ? city : `${city}市`;
|
||||
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 ?? ''),
|
||||
});
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export function storeCategoryTags(
|
||||
tags?: unknown;
|
||||
categoryId?: string | null;
|
||||
category?: StoreCategoryLike | null;
|
||||
categories?: StoreCategoryLike[] | null;
|
||||
},
|
||||
tree: StoreCategoryTreeNode[] = [],
|
||||
): string[] {
|
||||
@@ -30,24 +31,125 @@ export function storeCategoryTags(
|
||||
: [];
|
||||
if (fromJson.length) return fromJson;
|
||||
|
||||
const names: string[] = [];
|
||||
const childName = String(store.category?.name || '').trim();
|
||||
const parentName = String(store.category?.parent?.name || '').trim();
|
||||
if (parentName) names.push(parentName);
|
||||
if (childName && childName !== parentName) names.push(childName);
|
||||
|
||||
const storeCatId = String(store.categoryId || store.category?.id || '');
|
||||
const storeParentId = String(store.category?.parentId || '');
|
||||
for (const root of tree) {
|
||||
if (root.id === storeParentId || root.id === storeCatId) {
|
||||
if (root.name && !names.includes(root.name)) names.unshift(root.name);
|
||||
const multi = Array.isArray(store.categories) ? store.categories : [];
|
||||
if (multi.length) {
|
||||
return groupCategoryTags(multi, tree);
|
||||
}
|
||||
|
||||
if (store.category || store.categoryId) {
|
||||
const grouped = groupCategoryTags(
|
||||
store.category ? [store.category] : [],
|
||||
tree,
|
||||
store.categoryId,
|
||||
);
|
||||
if (grouped.length) return grouped;
|
||||
}
|
||||
|
||||
const storeCatId = String(store.categoryId || '');
|
||||
if (storeCatId) {
|
||||
for (const root of tree) {
|
||||
for (const child of root.children ?? []) {
|
||||
if (child.id === storeCatId) {
|
||||
if (root.name && !names.includes(root.name)) names.unshift(root.name);
|
||||
if (child.name && !names.includes(child.name)) names.push(child.name);
|
||||
return [`${root.name}|${child.name}`];
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** 按大类分组:餐饮|火锅·江浙菜、娱乐|KTV */
|
||||
function groupCategoryTags(
|
||||
categories: StoreCategoryLike[],
|
||||
tree: StoreCategoryTreeNode[] = [],
|
||||
fallbackCategoryId?: string | null,
|
||||
): string[] {
|
||||
if (!categories.length && fallbackCategoryId) {
|
||||
return groupCategoryTags([{ id: String(fallbackCategoryId) }], tree);
|
||||
}
|
||||
|
||||
const groups = new Map<string, { parentName: string; children: string[] }>();
|
||||
const order: string[] = [];
|
||||
|
||||
for (const cat of categories) {
|
||||
const resolved = resolveCategoryParts(cat, tree);
|
||||
if (!resolved) continue;
|
||||
const { parentKey, parentName, childName } = resolved;
|
||||
if (!groups.has(parentKey)) {
|
||||
groups.set(parentKey, { parentName, children: [] });
|
||||
order.push(parentKey);
|
||||
}
|
||||
const group = groups.get(parentKey)!;
|
||||
if (childName && childName !== parentName && !group.children.includes(childName)) {
|
||||
group.children.push(childName);
|
||||
}
|
||||
}
|
||||
|
||||
return order
|
||||
.map((key) => {
|
||||
const group = groups.get(key)!;
|
||||
if (group.parentName && group.children.length) {
|
||||
return `${group.parentName}|${group.children.join('·')}`;
|
||||
}
|
||||
if (group.children.length) return group.children.join('·');
|
||||
return group.parentName;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function resolveCategoryParts(
|
||||
cat: StoreCategoryLike,
|
||||
tree: StoreCategoryTreeNode[] = [],
|
||||
): { parentKey: string; parentName: string; childName: string } | null {
|
||||
const childName = String(cat.name || '').trim();
|
||||
let parentName = String(cat.parent?.name || '').trim();
|
||||
const catId = String(cat.id || '');
|
||||
const parentId = String(cat.parentId || '');
|
||||
|
||||
if (!parentName && (parentId || catId)) {
|
||||
for (const root of tree) {
|
||||
if (parentId && root.id === parentId) {
|
||||
parentName = root.name;
|
||||
break;
|
||||
}
|
||||
for (const child of root.children ?? []) {
|
||||
if (catId && child.id === catId) {
|
||||
parentName = root.name;
|
||||
if (!childName) return { parentKey: root.id, parentName, childName: child.name };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!childName && !parentName) return null;
|
||||
|
||||
const parentKey = parentId || parentName || catId;
|
||||
if (!parentName && catId) {
|
||||
for (const root of tree) {
|
||||
for (const child of root.children ?? []) {
|
||||
if (child.id === catId) {
|
||||
return { parentKey: root.id, parentName: root.name, childName: child.name };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parentKey,
|
||||
parentName: parentName || childName,
|
||||
childName: childName || parentName,
|
||||
};
|
||||
}
|
||||
|
||||
export function storeLeafCategoryIds(store: {
|
||||
categoryId?: string | null;
|
||||
category?: StoreCategoryLike | null;
|
||||
categories?: StoreCategoryLike[] | null;
|
||||
}): string[] {
|
||||
if (Array.isArray(store.categories) && store.categories.length) {
|
||||
return store.categories.map((c) => String(c.id || '')).filter(Boolean);
|
||||
}
|
||||
const id = String(store.categoryId || store.category?.id || '');
|
||||
return id ? [id] : [];
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ type StoresSession = {
|
||||
cache: StoresListCache | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'dukang_stores_session_v2';
|
||||
const STORAGE_KEY = 'dukang_stores_session_v3';
|
||||
|
||||
let memory: StoresSession | null = null;
|
||||
|
||||
|
||||
@@ -7,12 +7,16 @@ import SubPageHeader from '../../components/SubPageHeader';
|
||||
import RegionPicker from '../../components/RegionPicker';
|
||||
import { buildAddressListUrl, readCheckoutContext } from '../../lib/checkout-nav';
|
||||
import {
|
||||
DEFAULT_REGION,
|
||||
DEFAULT_SHIPPING_REGION,
|
||||
REGION_ALL,
|
||||
formatRegion,
|
||||
type RegionSelection,
|
||||
} from '../../lib/region-data';
|
||||
import { normalizePhoneInput, validateMobilePhone } from '../../lib/phone';
|
||||
import {
|
||||
shippingDetailCityWideHint,
|
||||
validateClientShippingAddress,
|
||||
} from '../../lib/shipping-address';
|
||||
import { getStoredUserPhone, resolveDefaultUserPhone } from '../../lib/user-phone';
|
||||
import { resolveUserCity } from '../../lib/user-location';
|
||||
import { request, toast, type UserProfile } from '../../lib/api';
|
||||
@@ -36,12 +40,13 @@ export default function AddressEditPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [locating, setLocating] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [hint, setHint] = useState('');
|
||||
const [form, setForm] = useState<AddressForm>(() => ({
|
||||
receiverName: '',
|
||||
phone: id ? '' : getStoredUserPhone(),
|
||||
province: DEFAULT_REGION.province,
|
||||
city: DEFAULT_REGION.city,
|
||||
district: DEFAULT_REGION.district,
|
||||
province: DEFAULT_SHIPPING_REGION.province,
|
||||
city: DEFAULT_SHIPPING_REGION.city,
|
||||
district: DEFAULT_SHIPPING_REGION.district,
|
||||
detail: '',
|
||||
isDefault: true,
|
||||
}));
|
||||
@@ -69,7 +74,7 @@ export default function AddressEditPage() {
|
||||
? resolved.region.district
|
||||
: resolved.district && resolved.district !== REGION_ALL
|
||||
? resolved.district
|
||||
: DEFAULT_REGION.district;
|
||||
: '';
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
province: resolved.region.province || prev.province,
|
||||
@@ -91,12 +96,13 @@ export default function AddressEditPage() {
|
||||
request<Array<Record<string, unknown>>>('/user/addresses').then((list) => {
|
||||
const found = list.find((a) => String(a.id) === id);
|
||||
if (found) {
|
||||
const district = String(found.district ?? '');
|
||||
setForm({
|
||||
receiverName: String(found.receiverName ?? ''),
|
||||
phone: String(found.phone ?? ''),
|
||||
province: String(found.province ?? DEFAULT_REGION.province),
|
||||
city: String(found.city ?? DEFAULT_REGION.city),
|
||||
district: String(found.district ?? DEFAULT_REGION.district),
|
||||
province: String(found.province ?? DEFAULT_SHIPPING_REGION.province),
|
||||
city: String(found.city ?? DEFAULT_SHIPPING_REGION.city),
|
||||
district: district === REGION_ALL ? '' : district,
|
||||
detail: String(found.detail ?? ''),
|
||||
isDefault: found.isDefault === 1 || found.isDefault === true,
|
||||
});
|
||||
@@ -104,14 +110,21 @@ export default function AddressEditPage() {
|
||||
}).catch(() => {});
|
||||
}, [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 {
|
||||
if (!form.receiverName.trim()) return '请输入收货人姓名';
|
||||
const phoneCheck = validateMobilePhone(form.phone);
|
||||
if (!phoneCheck.ok) return phoneCheck.message ?? '请输入正确的手机号码';
|
||||
if (!form.province || !form.city || !form.district) return '请选择所在地区';
|
||||
if (!form.detail.trim()) return '请输入详细地址';
|
||||
const shipping = validateClientShippingAddress(form);
|
||||
if (!shipping.ok) return shipping.message ?? '请完善收货地址';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -201,7 +214,7 @@ export default function AddressEditPage() {
|
||||
<Text>
|
||||
{locating && !isEdit
|
||||
? '定位中…'
|
||||
: regionText || '请选择省市区'}
|
||||
: regionText || '请选择省 / 市 / 区县'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
@@ -228,6 +241,7 @@ export default function AddressEditPage() {
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
{hint ? <Text className="address-form-hint">{hint}</Text> : null}
|
||||
<View className="address-form-row">
|
||||
<Text>设为默认地址</Text>
|
||||
<Switch
|
||||
@@ -248,6 +262,7 @@ export default function AddressEditPage() {
|
||||
onClose={() => setPickerOpen(false)}
|
||||
onConfirm={onRegionConfirm}
|
||||
levels={3}
|
||||
mode="shipping"
|
||||
/>
|
||||
</PageShell>
|
||||
);
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
buildOrderConfirmUrl,
|
||||
readCheckoutContext,
|
||||
} from '../../lib/checkout-nav';
|
||||
import { isDirtyShippingAddress } from '../../lib/shipping-address';
|
||||
import { request, toast } from '../../lib/api';
|
||||
|
||||
type Address = {
|
||||
@@ -51,6 +52,11 @@ export default function AddressesPage() {
|
||||
|
||||
function selectAddress(addr: Address) {
|
||||
if (!selectMode) return;
|
||||
if (isDirtyShippingAddress(addr)) {
|
||||
toast('该地址缺少具体区县,请先完善');
|
||||
Taro.navigateTo({ url: buildAddressEditUrl(addr.id, checkoutCtx) }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
Taro.redirectTo({
|
||||
url: buildOrderConfirmUrl({
|
||||
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 (
|
||||
<PageShell variant="sub" className="address-page" hasFixedFooter>
|
||||
<SubPageHeader title={selectMode ? '选择收货地址' : '地址管理'} />
|
||||
@@ -84,21 +96,27 @@ export default function AddressesPage() {
|
||||
{!loading && list.length === 0 ? (
|
||||
<View className="u-empty">暂无收货地址</View>
|
||||
) : null}
|
||||
{list.map((a) => (
|
||||
{sorted.map((a) => {
|
||||
const dirty = isDirtyShippingAddress(a);
|
||||
return (
|
||||
<View
|
||||
key={a.id}
|
||||
className="address-item"
|
||||
className={`address-item${dirty ? ' address-item--dirty' : ''}`}
|
||||
onClick={() => selectAddress(a)}
|
||||
>
|
||||
<View className="address-item-head">
|
||||
<Text className="address-item-name">{a.receiverName}</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>
|
||||
{!selectMode ? (
|
||||
{dirty ? (
|
||||
<Text className="address-item-warn">缺少具体区县,同城配送可能失败,请编辑完善</Text>
|
||||
) : null}
|
||||
{!selectMode || dirty ? (
|
||||
<View className="address-item-actions">
|
||||
<Text
|
||||
className="address-action"
|
||||
@@ -109,8 +127,9 @@ export default function AddressesPage() {
|
||||
});
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
{dirty ? '去完善' : '编辑'}
|
||||
</Text>
|
||||
{!selectMode ? (
|
||||
<Text
|
||||
className="address-action"
|
||||
onClick={(e) => {
|
||||
@@ -120,10 +139,12 @@ export default function AddressesPage() {
|
||||
>
|
||||
删除
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<View
|
||||
className="address-fab"
|
||||
|
||||
@@ -196,6 +196,17 @@ export default function HomePage() {
|
||||
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) {
|
||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=2`;
|
||||
if (!isLoggedIn()) {
|
||||
@@ -348,7 +359,7 @@ export default function HomePage() {
|
||||
className="home-buy-btn"
|
||||
onClick={(e) => {
|
||||
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 { loadLocalDeliveries, matchLocalDelivery, resolveLocalDeliveryHintHtml } from '../../lib/local-delivery';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
import { isDirtyShippingAddress } from '../../lib/shipping-address';
|
||||
import BenefitFigure from '../../components/BenefitFigure';
|
||||
import OrderQtyControls from '../../components/OrderQtyControls';
|
||||
|
||||
@@ -177,7 +178,12 @@ export default function OrderConfirmPage() {
|
||||
const isCross =
|
||||
forceCross || preview?.deliveryType === 'CROSS_CITY' || localCross;
|
||||
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 minQty =
|
||||
preview?.minQty ??
|
||||
@@ -186,7 +192,9 @@ export default function OrderConfirmPage() {
|
||||
const canSubmit =
|
||||
!!addressId && !!preview && quantityOk && addressOk && !loading && !previewLoading;
|
||||
|
||||
const addressHint = !addressOk
|
||||
const addressHint = dirtyAddress
|
||||
? '请完善收货地址(需选择具体区县)'
|
||||
: !addressOk
|
||||
? preview?.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||
: '';
|
||||
|
||||
|
||||
@@ -79,6 +79,12 @@ type Store = {
|
||||
parentId?: string | null;
|
||||
parent?: { name?: string } | null;
|
||||
} | null;
|
||||
categories?: {
|
||||
id?: string;
|
||||
name?: string;
|
||||
parentId?: string | null;
|
||||
parent?: { name?: string } | null;
|
||||
}[] | null;
|
||||
};
|
||||
|
||||
type RecentRedeem = {
|
||||
@@ -406,12 +412,15 @@ export default function StoreDetailPage() {
|
||||
|
||||
<View className="store-detail-title-row">
|
||||
<Text className="store-detail-name">{store.name}</Text>
|
||||
{storeCategoryTags(store, categoryTree).map((tag) => (
|
||||
<Text key={tag} className="store-detail-tag">
|
||||
{tag}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
{(() => {
|
||||
const categoryLabels = storeCategoryTags(store, categoryTree);
|
||||
return categoryLabels.length ? (
|
||||
<View className="store-detail-tags-row">
|
||||
<Text className="store-detail-category-line">{categoryLabels.join('、')}</Text>
|
||||
</View>
|
||||
) : null;
|
||||
})()}
|
||||
<View className="store-detail-rating-row">
|
||||
<View className="store-detail-stars">
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
toWeappShareTimeline,
|
||||
} from '../../lib/wechat-share';
|
||||
import BenefitSloganBar from '../../components/BenefitSloganBar';
|
||||
import { storeCategoryTags, storeStarCount } from '../../lib/store-display';
|
||||
import { storeCategoryTags, storeLeafCategoryIds, storeStarCount } from '../../lib/store-display';
|
||||
import openBadgeImg from '../../assets/icons/store-open-badge.png';
|
||||
|
||||
type Store = {
|
||||
@@ -66,6 +66,12 @@ type Store = {
|
||||
parentId?: string | null;
|
||||
parent?: { name?: string } | null;
|
||||
} | null;
|
||||
categories?: {
|
||||
id?: string;
|
||||
name?: string;
|
||||
parentId?: string | null;
|
||||
parent?: { name?: string } | null;
|
||||
}[] | null;
|
||||
tags?: unknown;
|
||||
rating?: number | string | null;
|
||||
latitude?: number | string | null;
|
||||
@@ -288,14 +294,21 @@ export default function StoresPage() {
|
||||
|
||||
function matchesCategory(store: Store): boolean {
|
||||
if (!category.parentId) return true;
|
||||
const storeCatId = String(store.categoryId || store.category?.id || '');
|
||||
const storeParentId = String(store.category?.parentId || '');
|
||||
if (category.childId) {
|
||||
return storeCatId === category.childId;
|
||||
const leafIds = storeLeafCategoryIds(store);
|
||||
const parentIds = new Set<string>();
|
||||
if (Array.isArray(store.categories)) {
|
||||
for (const cat of store.categories) {
|
||||
if (cat.parentId) parentIds.add(String(cat.parentId));
|
||||
}
|
||||
if (storeParentId && storeParentId === category.parentId) return true;
|
||||
}
|
||||
const legacyParent = String(store.category?.parentId || '');
|
||||
if (legacyParent) parentIds.add(legacyParent);
|
||||
if (category.childId) {
|
||||
return leafIds.includes(category.childId);
|
||||
}
|
||||
if ([...parentIds].some((id) => id === category.parentId)) return true;
|
||||
const siblings = childIdsByParent.get(category.parentId) ?? [];
|
||||
return siblings.includes(storeCatId);
|
||||
return leafIds.some((id) => siblings.includes(id));
|
||||
}
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
@@ -461,14 +474,10 @@ export default function StoresPage() {
|
||||
<Text className="store-card-name">{s.name}</Text>
|
||||
</View>
|
||||
{(() => {
|
||||
const tags = storeCategoryTags(s, categoryTree);
|
||||
return tags.length ? (
|
||||
<View className="store-card-tags">
|
||||
{tags.map((tag) => (
|
||||
<Text key={tag} className="store-card-tag">
|
||||
{tag}
|
||||
</Text>
|
||||
))}
|
||||
const categoryLabels = storeCategoryTags(s, categoryTree);
|
||||
return categoryLabels.length ? (
|
||||
<View className="store-card-category-wrap">
|
||||
<Text className="store-card-category-text">{categoryLabels.join('、')}</Text>
|
||||
</View>
|
||||
) : null;
|
||||
})()}
|
||||
|
||||
@@ -38,6 +38,34 @@
|
||||
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 {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
|
||||
@@ -191,7 +191,7 @@
|
||||
}
|
||||
|
||||
.order-qty-unit {
|
||||
margin-right: 8px;
|
||||
margin-left: 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-on-surface);
|
||||
|
||||
@@ -100,6 +100,12 @@
|
||||
}
|
||||
|
||||
.store-detail-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.store-detail-tags-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
@@ -107,6 +113,20 @@
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.store-detail-category-line {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
background: rgba(166, 29, 36, 0.1);
|
||||
box-sizing: border-box;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
line-height: 16px;
|
||||
color: var(--color-heritage-red);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.store-detail-name {
|
||||
font-family: var(--font-headline);
|
||||
font-size: 20px;
|
||||
|
||||
@@ -215,13 +215,32 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-card-category-wrap {
|
||||
align-self: flex-start;
|
||||
max-width: 100%;
|
||||
padding: 0 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(166, 29, 36, 0.1);
|
||||
box-sizing: border-box;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.store-card-category-text {
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
line-height: 14px;
|
||||
color: var(--color-heritage-red);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.store-card-tags {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
margin-top: 2px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.store-card-tag {
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
| 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.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)。
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
| **mini-user** | 购酒/权益/核销/门店/物流/版本门控 | 规则弹窗、发票、四类型工单、问卷 |
|
||||
| **h5-shop** | 扫码核销、记录、营业、iOS 扫码 OAuth | 手机号核销、提现、子账号、弱网兜底 |
|
||||
| **h5-partner** | 子账号、拓店、订单/账单、套餐 | 试核销100、负责人复核、代下单 |
|
||||
| **admin-web** | 商品/开城/门店/订单(含 Excel/PDF 导出)/权益/核销/结算/推广码 metrics/开发计划/技术支持 | 完整 SOP 审核 UI、发票、热力图 |
|
||||
| **admin-web** | 商品/开城/门店/订单(含 Excel/PDF 导出)/权益/核销/结算/推广码 metrics/开发计划/技术支持/企微报告 | 完整 SOP 审核 UI、发票、热力图 |
|
||||
| **后端** | 主模块、支付、权益、核销、payout、Courier 适配 | 30min 取消 job、部分 Wave3 |
|
||||
|
||||
## 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-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)。
|
||||
|
||||
## 1. 交付目标(六条)
|
||||
@@ -44,6 +44,10 @@ C 端购酒核销 · 门店扫码核销+打款 · 合伙人拓店履约 · WebAd
|
||||
|
||||
**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`);列表手机号不脱敏。
|
||||
|
||||
**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.0**(2026-08-29)· 关联码与分佣事实源;**v4.0.6** 酒厂对账;**v4.0.7** HQ 活动图快链与勾选导出;**v4.0.9** 合伙人 H5 周结算与用户管理
|
||||
> 未改规则仍见 [`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md)。**冲突时 V4 > V3**(本主题:订单佣金归属、关联码、合伙人账单明细、活动图、酒厂对账、合伙人周结算)。
|
||||
> 实现:[`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**(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**(本主题:订单佣金归属、关联码、合伙人账单明细、活动图、酒厂对账、合伙人周结算、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.0.14 开发文档`](./杜康好客-v4.0.14-开发文档.md) · [`v4.0.15 开发文档`](./杜康好客-v4.0.15-开发文档.md) · 审计:[`v4-现状对照`](./杜康好客-v4-现状对照.md)
|
||||
|
||||
## 0. 版本
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
| 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.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,佣金归属改写)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
| 维度 | 结论 |
|
||||
|------|------|
|
||||
| 版本线 | **v4.0.9** 合伙人 H5 周结算、预付款、子账号用户管理 |
|
||||
| 版本线 | **v4.0.15** HQ 概览折线图(粒度分桶、总量/增量、维度线条) |
|
||||
| 订单佣金 | 区县归属已删除;只认关联 / 代下单选择 |
|
||||
| 账单 | 酒订单 / 核销订单分列;合伙人改为周账(周一 08:00);零元不同步合伙人;酒厂含现场提货,零应付仍出账(无需打款) |
|
||||
| 活动图 | HQ 上传底图/码栏/文案;合伙人选择写入库;HQ 可指定一张图为勾选主合伙人合成下载;子账号不可看活动图 |
|
||||
@@ -21,6 +21,9 @@
|
||||
| 4.0.6 | [`酒厂对账核对`](./杜康好客-v4.0.6-开发文档.md) | ✅ 已实现 |
|
||||
| 4.0.7 | [`活动图快链与勾选导出`](./杜康好客-v4.0.7-开发文档.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-09-01 | v4.0.7:HQ 城市合伙人活动图快链;单张/勾选导出合成图(PNG / zip) |
|
||||
| 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 './phone';
|
||||
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?: {
|
||||
createShipment?: boolean;
|
||||
getTrack?: boolean;
|
||||
getSignPhotos?: boolean;
|
||||
callback?: boolean;
|
||||
cancel?: boolean;
|
||||
} | null;
|
||||
|
||||
@@ -149,6 +149,7 @@ export const HQ_ADMIN_ROLE_VALUES = [
|
||||
'FINANCE',
|
||||
'CUSTOMER_SERVICE',
|
||||
'CITY_STORE_SERVICE',
|
||||
'DEVELOPER',
|
||||
] as const;
|
||||
|
||||
export type HqAdminRoleValue = (typeof HQ_ADMIN_ROLE_VALUES)[number];
|
||||
@@ -159,6 +160,7 @@ export const HQ_ADMIN_ROLES: { value: HqAdminRoleValue; label: string }[] = [
|
||||
{ value: 'FINANCE', label: '财务' },
|
||||
{ value: 'CUSTOMER_SERVICE', label: '客服' },
|
||||
{ value: 'CITY_STORE_SERVICE', label: '城市门店服务' },
|
||||
{ value: 'DEVELOPER', label: '开发者' },
|
||||
];
|
||||
|
||||
const OPS_STORE_KEYS: HqPermissionKey[] = [
|
||||
@@ -170,6 +172,13 @@ const OPS_STORE_KEYS: HqPermissionKey[] = [
|
||||
'store_media',
|
||||
];
|
||||
|
||||
/** 开发者默认:除权限分配、HQ 账户外全部权限 */
|
||||
function developerDefaultPermissions(): HqPermissionKey[] {
|
||||
return HQ_PERMISSION_CATALOG.map((p) => p.key).filter(
|
||||
(k) => k !== 'hq_permissions' && k !== 'hq_accounts',
|
||||
);
|
||||
}
|
||||
|
||||
export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<HqAdminRoleValue, HqPermissionKey[]> = {
|
||||
SUPER_ADMIN: [...hqBasePermissionKeys(), ...HQ_DEBUG_PERMISSION_KEYS],
|
||||
OPS: [
|
||||
@@ -228,4 +237,5 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<HqAdminRoleValue, HqPermissionK
|
||||
'store_ratings',
|
||||
'store_categories',
|
||||
],
|
||||
DEVELOPER: developerDefaultPermissions(),
|
||||
};
|
||||
|
||||
@@ -30,6 +30,7 @@ export * from './fulfillment-provider';
|
||||
export * from './system-config';
|
||||
export * from './wecom-bot';
|
||||
export * from './wecom-message-push';
|
||||
export * from './wecom-report';
|
||||
export * from './llm-config';
|
||||
export * from './knowledge-base';
|
||||
export * from './legal';
|
||||
|
||||
@@ -34,6 +34,14 @@ export interface UpdateAdminUserRequest {
|
||||
hqRemark: string;
|
||||
}
|
||||
|
||||
/** HQ 当前账号修改登录名 / 密码(自助) */
|
||||
export interface UpdateMyHqCredentialsRequest {
|
||||
loginName?: string;
|
||||
/** 修改密码时必填(账号尚未设置密码时可省略) */
|
||||
oldPassword?: string;
|
||||
newPassword?: string;
|
||||
}
|
||||
|
||||
export interface AdminPageResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
@@ -60,3 +68,38 @@ export interface DeployTriggerResult {
|
||||
started?: boolean;
|
||||
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[];
|
||||
};
|
||||
|
||||
@@ -139,6 +139,8 @@ export interface PartnerBillDto {
|
||||
redeemCommission: number;
|
||||
totalAmount: number;
|
||||
status: PartnerBillStatus;
|
||||
/** 出账日 YYYY-MM-DD(周账=账期结束后下周一;历史月账=次月 1 日) */
|
||||
billDate: string;
|
||||
periodStart: string;
|
||||
periodEnd: string;
|
||||
confirmedAt?: string | null;
|
||||
@@ -187,6 +189,10 @@ export interface StoreBillDto {
|
||||
storeId: string;
|
||||
/** 出账日 YYYY-MM-DD(T+1 窗口「昨日 00:00–今日 00:00」中的今天) */
|
||||
billDate: string;
|
||||
/** 账期起 YYYY-MM-DD(含;T+1 = 出账日前一日) */
|
||||
periodStart: string;
|
||||
/** 账期止 YYYY-MM-DD(含;T+1 = 出账日前一日) */
|
||||
periodEnd: string;
|
||||
redeemCount: number;
|
||||
redeemAmount: number;
|
||||
settlementRate: number;
|
||||
@@ -202,6 +208,10 @@ export interface WineryBillDto {
|
||||
billNo: string;
|
||||
/** 出账日 YYYY-MM-DD(北京时间;T+3 = 每 3 天一期,纳入上期 3 天完成订单) */
|
||||
billDate: string;
|
||||
/** 账期起 YYYY-MM-DD(含) */
|
||||
periodStart: string;
|
||||
/** 账期止 YYYY-MM-DD(含) */
|
||||
periodEnd: string;
|
||||
orderCount: number;
|
||||
orderAmount: number;
|
||||
wineryRate: number;
|
||||
|
||||
@@ -99,11 +99,16 @@ export interface OrderTrackDto {
|
||||
queryError?: string | null;
|
||||
}
|
||||
|
||||
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
||||
/** 履约拦截原因(大单 / 承运商拒单等) */
|
||||
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
||||
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 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:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
jspdf:
|
||||
specifier: ^4.2.1
|
||||
version: 4.2.1
|
||||
react:
|
||||
specifier: ^18.3.1
|
||||
version: 18.3.1
|
||||
@@ -2811,6 +2814,9 @@ packages:
|
||||
'@types/node@25.9.5':
|
||||
resolution: {integrity: sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==}
|
||||
|
||||
'@types/pako@2.0.4':
|
||||
resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==}
|
||||
|
||||
'@types/pdfkit@0.17.6':
|
||||
resolution: {integrity: sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==}
|
||||
|
||||
@@ -2826,6 +2832,9 @@ packages:
|
||||
'@types/qs@6.15.1':
|
||||
resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}
|
||||
|
||||
'@types/raf@3.4.3':
|
||||
resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==}
|
||||
|
||||
'@types/range-parser@1.2.7':
|
||||
resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}
|
||||
|
||||
@@ -2856,6 +2865,9 @@ packages:
|
||||
'@types/serve-static@1.15.10':
|
||||
resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==}
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
|
||||
'@types/validator@13.15.10':
|
||||
resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==}
|
||||
|
||||
@@ -3313,6 +3325,10 @@ packages:
|
||||
bare-url@2.5.2:
|
||||
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:
|
||||
resolution: {integrity: sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3476,6 +3492,10 @@ packages:
|
||||
caniuse-lite@1.0.30001799:
|
||||
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:
|
||||
resolution: {integrity: sha512-ds37W8CytHgwnhGGTi88pcPyR15qoNkOpYwmMMfnWqqWgESapLqvDx6huFjQ5vqWSn2Z06173XNA7LtMOeUh1A==}
|
||||
|
||||
@@ -3749,6 +3769,9 @@ packages:
|
||||
resolution: {integrity: sha512-8HFEBPKhOpJPEPu70wJJetjKta86Gw9+CCyCnB3sui2qQfOvRyqBy4IKLKKAwdMpWb2lHXWk9Wb4Z6AmaUT1Pg==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
css-line-break@2.1.0:
|
||||
resolution: {integrity: sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==}
|
||||
|
||||
css-tree@3.2.1:
|
||||
resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
|
||||
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==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
dompurify@3.4.14:
|
||||
resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==}
|
||||
|
||||
dot-case@3.0.4:
|
||||
resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==}
|
||||
|
||||
@@ -4190,6 +4216,9 @@ packages:
|
||||
fast-levenshtein@2.0.6:
|
||||
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
|
||||
|
||||
fast-png@6.4.0:
|
||||
resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==}
|
||||
|
||||
fast-safe-stringify@2.1.1:
|
||||
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
||||
|
||||
@@ -4591,6 +4620,10 @@ packages:
|
||||
resolution: {integrity: sha512-ztqyC3kLto0e9WbNp0aeP+M3kTt+nbaIveGmUxAtZa+8iFgKLUOD4YKM5j+f3QD89bra7UeumolZHKuOXnTmeQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
html2canvas@1.4.1:
|
||||
resolution: {integrity: sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
|
||||
http-cache-semantics@3.8.1:
|
||||
resolution: {integrity: sha512-5ai2iksyV8ZXmnZhHH4rWPoxxistEexSi5936zIQ1bnNTW5VnA85B6P/VpXiRM017IgRvb2kKo1a//y+0wSp3w==}
|
||||
|
||||
@@ -4687,6 +4720,9 @@ packages:
|
||||
resolution: {integrity: sha512-TcdjPibTksa1NQximqep2r17ISRiNE9fwlfbg3F8ANdvP5/yrFTew86VcO//jk4QTaMlbjypPBq76HN2zaKfZQ==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
iobuffer@5.4.0:
|
||||
resolution: {integrity: sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==}
|
||||
|
||||
ioredis@5.10.1:
|
||||
resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}
|
||||
engines: {node: '>=12.22.0'}
|
||||
@@ -4906,6 +4942,9 @@ packages:
|
||||
resolution: {integrity: sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==}
|
||||
engines: {node: '>=12', npm: '>=6'}
|
||||
|
||||
jspdf@4.2.1:
|
||||
resolution: {integrity: sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==}
|
||||
|
||||
jstoxml@2.2.9:
|
||||
resolution: {integrity: sha512-OYWlK0j+roh+eyaMROlNbS5cd5R25Y+IUpdl7cNdB8HNrkgwQzIS7L9MegxOiWNBj9dQhA/yAxiMwCC5mwNoBw==}
|
||||
|
||||
@@ -5476,6 +5515,9 @@ packages:
|
||||
pako@1.0.11:
|
||||
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:
|
||||
resolution: {integrity: sha512-eQE845L6ot89sk2N8liD8HAuH4ca6Vvr7VWAWwt7+kvvG5aBcPmmphQ68JsEG2qa9n1TykS2DLeMt363AAH8/w==}
|
||||
|
||||
@@ -5563,6 +5605,9 @@ packages:
|
||||
pend@1.2.0:
|
||||
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
|
||||
|
||||
performance-now@2.1.0:
|
||||
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -5788,6 +5833,9 @@ packages:
|
||||
queue-microtask@1.2.3:
|
||||
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
||||
|
||||
raf@3.4.1:
|
||||
resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
|
||||
|
||||
randombytes@2.1.0:
|
||||
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
|
||||
|
||||
@@ -6190,6 +6238,10 @@ packages:
|
||||
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
|
||||
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:
|
||||
resolution: {integrity: sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==}
|
||||
deprecated: Rimraf versions prior to v4 are no longer supported
|
||||
@@ -6433,6 +6485,10 @@ packages:
|
||||
stackback@0.0.2:
|
||||
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:
|
||||
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
|
||||
|
||||
@@ -6547,6 +6603,10 @@ packages:
|
||||
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
|
||||
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:
|
||||
resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==}
|
||||
|
||||
@@ -6634,6 +6694,9 @@ packages:
|
||||
text-decoder@1.2.7:
|
||||
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:
|
||||
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
|
||||
|
||||
@@ -6930,6 +6993,9 @@ packages:
|
||||
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
|
||||
engines: {node: '>= 0.4.0'}
|
||||
|
||||
utrie@1.0.2:
|
||||
resolution: {integrity: sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==}
|
||||
|
||||
uuid@8.3.2:
|
||||
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).
|
||||
@@ -9830,6 +9896,8 @@ snapshots:
|
||||
dependencies:
|
||||
undici-types: 7.24.6
|
||||
|
||||
'@types/pako@2.0.4': {}
|
||||
|
||||
'@types/pdfkit@0.17.6':
|
||||
dependencies:
|
||||
'@types/node': 20.19.43
|
||||
@@ -9847,6 +9915,9 @@ snapshots:
|
||||
|
||||
'@types/qs@6.15.1': {}
|
||||
|
||||
'@types/raf@3.4.3':
|
||||
optional: true
|
||||
|
||||
'@types/range-parser@1.2.7': {}
|
||||
|
||||
'@types/react-dom@18.3.7(@types/react@18.3.31)':
|
||||
@@ -9885,6 +9956,9 @@ snapshots:
|
||||
'@types/node': 20.19.43
|
||||
'@types/send': 0.17.6
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
optional: true
|
||||
|
||||
'@types/validator@13.15.10': {}
|
||||
|
||||
'@types/xml2js@0.4.14':
|
||||
@@ -10552,6 +10626,9 @@ snapshots:
|
||||
dependencies:
|
||||
bare-path: 3.1.1
|
||||
|
||||
base64-arraybuffer@1.0.2:
|
||||
optional: true
|
||||
|
||||
base64-js@0.0.8: {}
|
||||
|
||||
base64-js@1.5.1: {}
|
||||
@@ -10745,6 +10822,18 @@ snapshots:
|
||||
|
||||
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:
|
||||
dependencies:
|
||||
no-case: 3.0.4
|
||||
@@ -11049,6 +11138,11 @@ snapshots:
|
||||
|
||||
css-functions-list@3.3.3: {}
|
||||
|
||||
css-line-break@2.1.0:
|
||||
dependencies:
|
||||
utrie: 1.0.2
|
||||
optional: true
|
||||
|
||||
css-tree@3.2.1:
|
||||
dependencies:
|
||||
mdn-data: 2.27.1
|
||||
@@ -11191,6 +11285,11 @@ snapshots:
|
||||
xml: 1.0.1
|
||||
xml-js: 1.6.11
|
||||
|
||||
dompurify@3.4.14:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
optional: true
|
||||
|
||||
dot-case@3.0.4:
|
||||
dependencies:
|
||||
no-case: 3.0.4
|
||||
@@ -11597,6 +11696,12 @@ snapshots:
|
||||
|
||||
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-uri@3.1.2: {}
|
||||
@@ -12051,6 +12156,12 @@ snapshots:
|
||||
|
||||
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@4.2.0: {}
|
||||
@@ -12178,6 +12289,8 @@ snapshots:
|
||||
from2: 2.3.0
|
||||
p-is-promise: 1.1.0
|
||||
|
||||
iobuffer@5.4.0: {}
|
||||
|
||||
ioredis@5.10.1:
|
||||
dependencies:
|
||||
'@ioredis/commands': 1.5.1
|
||||
@@ -12382,6 +12495,17 @@ snapshots:
|
||||
ms: 2.1.3
|
||||
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: {}
|
||||
|
||||
jszip@3.10.1:
|
||||
@@ -12884,6 +13008,8 @@ snapshots:
|
||||
|
||||
pako@1.0.11: {}
|
||||
|
||||
pako@2.2.0: {}
|
||||
|
||||
param-case@2.1.1:
|
||||
dependencies:
|
||||
no-case: 2.3.2
|
||||
@@ -12968,6 +13094,9 @@ snapshots:
|
||||
|
||||
pend@1.2.0: {}
|
||||
|
||||
performance-now@2.1.0:
|
||||
optional: true
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
picomatch@2.3.2: {}
|
||||
@@ -13161,6 +13290,11 @@ snapshots:
|
||||
|
||||
queue-microtask@1.2.3: {}
|
||||
|
||||
raf@3.4.1:
|
||||
dependencies:
|
||||
performance-now: 2.1.0
|
||||
optional: true
|
||||
|
||||
randombytes@2.1.0:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
@@ -13658,6 +13792,9 @@ snapshots:
|
||||
|
||||
reusify@1.1.0: {}
|
||||
|
||||
rgbcolor@1.0.1:
|
||||
optional: true
|
||||
|
||||
rimraf@2.7.1:
|
||||
dependencies:
|
||||
glob: 7.2.3
|
||||
@@ -13984,6 +14121,9 @@ snapshots:
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
stackblur-canvas@2.7.0:
|
||||
optional: true
|
||||
|
||||
standard-as-callback@2.1.0: {}
|
||||
|
||||
statuses@1.5.0: {}
|
||||
@@ -14133,6 +14273,9 @@ snapshots:
|
||||
|
||||
supports-preserve-symlinks-flag@1.0.0: {}
|
||||
|
||||
svg-pathdata@6.0.3:
|
||||
optional: true
|
||||
|
||||
svg-tags@1.0.0: {}
|
||||
|
||||
swiper@11.1.15: {}
|
||||
@@ -14222,6 +14365,11 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- react-native-b4a
|
||||
|
||||
text-segmentation@1.0.3:
|
||||
dependencies:
|
||||
utrie: 1.0.2
|
||||
optional: true
|
||||
|
||||
text-table@0.2.0: {}
|
||||
|
||||
thenify-all@1.6.0:
|
||||
@@ -14502,6 +14650,11 @@ snapshots:
|
||||
|
||||
utils-merge@1.0.1: {}
|
||||
|
||||
utrie@1.0.2:
|
||||
dependencies:
|
||||
base64-arraybuffer: 1.0.2
|
||||
optional: true
|
||||
|
||||
uuid@8.3.2: {}
|
||||
|
||||
v8-compile-cache-lib@3.0.1: {}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"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: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: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",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- v4.0.11: HQ 角色新增「开发者」(DEVELOPER)
|
||||
-- 默认权限见 packages/shared-types HQ_ROLE_DEFAULT_PERMISSIONS.DEVELOPER
|
||||
-- (除 hq_permissions / hq_accounts 外全部;未写入 hq_role_permission 时走代码默认)
|
||||
|
||||
ALTER TABLE `hq_account`
|
||||
MODIFY COLUMN `admin_role` ENUM(
|
||||
'SUPER_ADMIN',
|
||||
'OPS',
|
||||
'FINANCE',
|
||||
'CUSTOMER_SERVICE',
|
||||
'CITY_STORE_SERVICE',
|
||||
'DEVELOPER'
|
||||
) NOT NULL DEFAULT 'OPS';
|
||||
|
||||
ALTER TABLE `hq_role_permission`
|
||||
MODIFY COLUMN `admin_role` ENUM(
|
||||
'SUPER_ADMIN',
|
||||
'OPS',
|
||||
'FINANCE',
|
||||
'CUSTOMER_SERVICE',
|
||||
'CITY_STORE_SERVICE',
|
||||
'DEVELOPER'
|
||||
) NOT NULL;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- 门店多分类关联表(v4.0.9+)
|
||||
-- 执行:mysql ... < migrate-store-category-link.sql
|
||||
|
||||
CREATE TABLE IF NOT EXISTS store_category_link (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
store_id BIGINT UNSIGNED NOT NULL,
|
||||
category_id BIGINT UNSIGNED NOT NULL,
|
||||
priority INT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_store_category_link (store_id, category_id),
|
||||
KEY idx_store_category_link_category (category_id),
|
||||
CONSTRAINT fk_store_category_link_store FOREIGN KEY (store_id) REFERENCES store_store(id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_store_category_link_category FOREIGN KEY (category_id) REFERENCES common_store_category(id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- 从现有主分类回填
|
||||
INSERT IGNORE INTO store_category_link (store_id, category_id, priority)
|
||||
SELECT id, category_id, 0
|
||||
FROM store_store
|
||||
WHERE category_id IS NOT NULL;
|
||||
@@ -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();
|
||||
});
|
||||
@@ -268,6 +268,7 @@ enum HqAdminRole {
|
||||
FINANCE
|
||||
CUSTOMER_SERVICE
|
||||
CITY_STORE_SERVICE
|
||||
DEVELOPER
|
||||
}
|
||||
|
||||
enum HqPermissionEffect {
|
||||
@@ -545,6 +546,26 @@ model WecomPushTemplate {
|
||||
@@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 配置(非超管仅可见/可开关自己创建的)
|
||||
model LlmApiConfig {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
@@ -1000,12 +1021,29 @@ model CommonStoreCategory {
|
||||
parent CommonStoreCategory? @relation("StoreCategoryTree", fields: [parentId], references: [id], onDelete: Restrict)
|
||||
children CommonStoreCategory[] @relation("StoreCategoryTree")
|
||||
stores Store[]
|
||||
storeLinks StoreCategoryLink[]
|
||||
|
||||
@@index([parentId, sort])
|
||||
@@index([status])
|
||||
@@map("common_store_category")
|
||||
}
|
||||
|
||||
/// 门店 ↔ 二级分类多对多;store.category_id 保留主分类(排序第一)
|
||||
model StoreCategoryLink {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||
categoryId BigInt @map("category_id") @db.UnsignedBigInt
|
||||
priority Int @default(0)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
|
||||
category CommonStoreCategory @relation(fields: [categoryId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([storeId, categoryId])
|
||||
@@index([categoryId])
|
||||
@@map("store_category_link")
|
||||
}
|
||||
|
||||
model CommonPromoCode {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
code String @unique @db.VarChar(32)
|
||||
@@ -1542,6 +1580,7 @@ model Store {
|
||||
packages StorePackage[]
|
||||
packageChangeRequests StorePackageChangeRequest[]
|
||||
infoChangeRequests StoreInfoChangeRequest[]
|
||||
categoryLinks StoreCategoryLink[]
|
||||
|
||||
@@index([cityId, status])
|
||||
@@index([partnerAccountId])
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
export type ExportColumnDef<T> = {
|
||||
key: string;
|
||||
header: string;
|
||||
value: (row: T) => string | number;
|
||||
};
|
||||
|
||||
/** 按请求的列 key 过滤导出列;未传则导出全部 */
|
||||
export function pickExportColumns<T>(
|
||||
defs: ExportColumnDef<T>[],
|
||||
requestedKeys?: string[],
|
||||
): ExportColumnDef<T>[] {
|
||||
if (!requestedKeys?.length) return defs;
|
||||
const byKey = new Map(defs.map((d) => [d.key, d]));
|
||||
return requestedKeys.map((k) => byKey.get(k)).filter((d): d is ExportColumnDef<T> => !!d);
|
||||
}
|
||||
|
||||
export function parseExportColumnKeys(raw?: string): string[] | undefined {
|
||||
if (!raw?.trim()) return undefined;
|
||||
const keys = raw
|
||||
.split(',')
|
||||
.map((k) => k.trim())
|
||||
.filter(Boolean);
|
||||
return keys.length ? keys : undefined;
|
||||
}
|
||||
|
||||
export function buildCsvFromColumns<T>(
|
||||
defs: ExportColumnDef<T>[],
|
||||
rows: T[],
|
||||
requestedKeys?: string[],
|
||||
): { csv: string; count: number } {
|
||||
const active = pickExportColumns(defs, requestedKeys);
|
||||
if (!active.length) {
|
||||
return { csv: '\uFEFF', count: 0 };
|
||||
}
|
||||
const header = active.map((d) => d.header).join(',');
|
||||
const body = rows.map((row) =>
|
||||
active
|
||||
.map((d) => {
|
||||
const v = d.value(row);
|
||||
const s = v == null ? '' : String(v);
|
||||
return s.includes(',') || s.includes('"') || s.includes('\n')
|
||||
? `"${s.replace(/"/g, '""')}"`
|
||||
: s;
|
||||
})
|
||||
.join(','),
|
||||
);
|
||||
return { csv: `\uFEFF${[header, ...body].join('\n')}`, count: rows.length };
|
||||
}
|
||||
@@ -95,6 +95,8 @@ export const HqOperationAction = {
|
||||
WECOM_MESSAGE_PUSH_UPDATE: 'WECOM_MESSAGE_PUSH_UPDATE',
|
||||
WECOM_MESSAGE_PUSH_DELETE: 'WECOM_MESSAGE_PUSH_DELETE',
|
||||
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_UPDATE: 'LLM_CONFIG_UPDATE',
|
||||
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_DELETE]: '删除企微消息推送',
|
||||
[HqOperationAction.WECOM_MESSAGE_PUSH_TEST]: '测试企微消息推送',
|
||||
[HqOperationAction.WECOM_REPORT_UPDATE]: '编辑企微经营报告',
|
||||
[HqOperationAction.WECOM_REPORT_SEND]: '发送企微经营报告',
|
||||
[HqOperationAction.LLM_CONFIG_CREATE]: '创建语言模型配置',
|
||||
[HqOperationAction.LLM_CONFIG_UPDATE]: '更新语言模型配置',
|
||||
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
||||
|
||||
@@ -47,13 +47,27 @@ export function sceneForXfxCmd(cmd: string) {
|
||||
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) {
|
||||
const responseBody =
|
||||
input.responseBody === undefined
|
||||
? undefined
|
||||
: typeof input.responseBody === 'object' && input.responseBody !== null
|
||||
? (input.responseBody as Record<string, unknown>)
|
||||
: { value: input.responseBody };
|
||||
const responseBody = sanitizeCourierResponseBody(input.scene, input.responseBody);
|
||||
|
||||
const row = await prisma.logThirdParty.create({
|
||||
data: {
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
pickExportColumns,
|
||||
type ExportColumnDef,
|
||||
} from '../../common/export/column-export.util';
|
||||
import {
|
||||
DEV_PLAN_TASK_STATUS_LABELS,
|
||||
DEV_PLAN_TASK_TYPE_LABELS,
|
||||
@@ -27,6 +31,7 @@ const EXPORT_HEADERS = [
|
||||
'状态',
|
||||
'内容',
|
||||
'关联工单',
|
||||
'关联版本',
|
||||
'创建人',
|
||||
'创建时间',
|
||||
'完成时间',
|
||||
@@ -39,6 +44,7 @@ export type DevPlanTaskExportRow = {
|
||||
status: string;
|
||||
content: string;
|
||||
supportTicketNo: string;
|
||||
versionNos: string;
|
||||
creatorName: string;
|
||||
createdAt: string;
|
||||
completedAt: string;
|
||||
@@ -53,6 +59,7 @@ export function mapTaskToExportRow(task: {
|
||||
status: DevPlanTaskStatusDto;
|
||||
content: string;
|
||||
supportTicketNo?: string | null;
|
||||
versionNos?: string | null;
|
||||
creatorName?: string | null;
|
||||
createdAt: string;
|
||||
completedAt?: string | null;
|
||||
@@ -64,6 +71,7 @@ export function mapTaskToExportRow(task: {
|
||||
status: DEV_PLAN_TASK_STATUS_LABELS[task.status] ?? task.status,
|
||||
content: task.content,
|
||||
supportTicketNo: task.supportTicketNo ?? '',
|
||||
versionNos: task.versionNos ?? '',
|
||||
creatorName: task.creatorName ?? '',
|
||||
createdAt: task.createdAt.slice(0, 19).replace('T', ' '),
|
||||
completedAt: task.completedAt ? task.completedAt.slice(0, 19).replace('T', ' ') : '',
|
||||
@@ -71,20 +79,30 @@ export function mapTaskToExportRow(task: {
|
||||
};
|
||||
}
|
||||
|
||||
function rowToCells(row: DevPlanTaskExportRow): string[] {
|
||||
function devPlanExportColumnDefs(): ExportColumnDef<DevPlanTaskExportRow>[] {
|
||||
return [
|
||||
row.taskNo,
|
||||
row.type,
|
||||
row.status,
|
||||
row.content,
|
||||
row.supportTicketNo,
|
||||
row.creatorName,
|
||||
row.createdAt,
|
||||
row.completedAt,
|
||||
row.attachmentUrls.join(' '),
|
||||
{ key: 'taskNo', header: '任务编号', value: (r) => r.taskNo },
|
||||
{ key: 'type', header: '类型', value: (r) => r.type },
|
||||
{ key: 'status', header: '状态', value: (r) => r.status },
|
||||
{ key: 'content', header: '内容', value: (r) => r.content },
|
||||
{ key: 'supportTicketNo', header: '关联工单', value: (r) => r.supportTicketNo },
|
||||
{ key: 'versions', header: '关联版本', value: (r) => r.versionNos },
|
||||
{ key: 'creatorName', header: '创建人', value: (r) => r.creatorName },
|
||||
{ key: 'createdAt', header: '创建时间', value: (r) => r.createdAt },
|
||||
{ key: 'completedAt', header: '完成时间', value: (r) => r.completedAt },
|
||||
{
|
||||
key: 'attachmentUrls',
|
||||
header: '附件',
|
||||
value: (r) => r.attachmentUrls.join(' '),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function rowToCells(row: DevPlanTaskExportRow, columnKeys?: string[]): string[] {
|
||||
const cols = pickExportColumns(devPlanExportColumnDefs(), columnKeys);
|
||||
return cols.map((c) => String(c.value(row)));
|
||||
}
|
||||
|
||||
function resolvePdfFontPath(): string {
|
||||
const candidates = [
|
||||
process.env.EXPORT_PDF_FONT_PATH,
|
||||
@@ -187,15 +205,17 @@ export async function buildDevPlanDocx(rows: DevPlanTaskExportRow[]): Promise<Bu
|
||||
return Packer.toBuffer(doc);
|
||||
}
|
||||
|
||||
export async function buildDevPlanXlsx(rows: DevPlanTaskExportRow[]): Promise<Buffer> {
|
||||
export async function buildDevPlanXlsx(rows: DevPlanTaskExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||
const cols = pickExportColumns(devPlanExportColumnDefs(), columnKeys);
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet('开发任务');
|
||||
sheet.addRow([...EXPORT_HEADERS]);
|
||||
sheet.addRow(cols.map((c) => c.header));
|
||||
for (const row of rows) {
|
||||
sheet.addRow(rowToCells(row));
|
||||
sheet.addRow(cols.map((c) => c.value(row)));
|
||||
}
|
||||
sheet.columns.forEach((col, i) => {
|
||||
col.width = i === 3 || i === 8 ? 40 : 16;
|
||||
const header = cols[i]?.header ?? '';
|
||||
col.width = header === '内容' || header === '附件' ? 40 : 16;
|
||||
});
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
return Buffer.from(buffer);
|
||||
|
||||
@@ -107,11 +107,13 @@ export class AdminDevPlanController {
|
||||
@Get('versions')
|
||||
listVersions(
|
||||
@Query('status') status?: string,
|
||||
@Query('keyword') keyword?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.service.listVersions({
|
||||
status,
|
||||
keyword,
|
||||
page: page ? Number(page) : undefined,
|
||||
pageSize: pageSize ? Number(pageSize) : undefined,
|
||||
});
|
||||
|
||||
@@ -590,7 +590,7 @@ export class DevPlanService {
|
||||
|
||||
|
||||
|
||||
async listVersions(query: { status?: string; page?: number; pageSize?: number }) {
|
||||
async listVersions(query: { status?: string; keyword?: string; page?: number; pageSize?: number }) {
|
||||
|
||||
const page = query.page ?? 1;
|
||||
|
||||
@@ -600,7 +600,13 @@ export class DevPlanService {
|
||||
|
||||
if (query.status) where.status = query.status as DevPlanVersionStatus;
|
||||
|
||||
|
||||
if (query.keyword?.trim()) {
|
||||
const kw = query.keyword.trim();
|
||||
where.OR = [
|
||||
{ versionNo: { contains: kw } },
|
||||
{ content: { contains: kw } },
|
||||
];
|
||||
}
|
||||
|
||||
const [rows, total] = await Promise.all([
|
||||
|
||||
@@ -1329,6 +1335,7 @@ export class DevPlanService {
|
||||
status?: string;
|
||||
type?: string;
|
||||
keyword?: string;
|
||||
columns?: string[];
|
||||
}) {
|
||||
let rows: Array<{
|
||||
id: bigint;
|
||||
@@ -1372,20 +1379,24 @@ export class DevPlanService {
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
const ticketMap = new Map(tickets.map((t) => [String(t.id), t.ticketNo] as [string, string]));
|
||||
const taskIds = rows.map((r) => r.id);
|
||||
const versionMap = await this.loadTaskVersionMap(taskIds);
|
||||
|
||||
const exportRows = rows.map((r) =>
|
||||
mapTaskToExportRow({
|
||||
const exportRows = rows.map((r) => {
|
||||
const versions = versionMap.get(String(r.id)) ?? [];
|
||||
return mapTaskToExportRow({
|
||||
taskNo: r.taskNo,
|
||||
type: r.type,
|
||||
status: r.status,
|
||||
content: r.content,
|
||||
supportTicketNo: r.supportTicketId != null ? ticketMap.get(String(r.supportTicketId)) ?? null : null,
|
||||
versionNos: versions.map((v) => v.versionNo).join('、') || null,
|
||||
creatorName: names.get(String(r.creatorHqAccountId)) ?? null,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
completedAt: r.completedAt?.toISOString() ?? null,
|
||||
attachmentUrls: parseAttachmentUrls(r.attachmentUrls),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
let buffer: Buffer;
|
||||
switch (dto.format) {
|
||||
@@ -1396,7 +1407,7 @@ export class DevPlanService {
|
||||
buffer = await buildDevPlanDocx(exportRows);
|
||||
break;
|
||||
case 'xlsx':
|
||||
buffer = await buildDevPlanXlsx(exportRows);
|
||||
buffer = await buildDevPlanXlsx(exportRows, dto.columns);
|
||||
break;
|
||||
case 'pdf':
|
||||
buffer = await buildDevPlanPdf(exportRows);
|
||||
|
||||
@@ -221,6 +221,11 @@ export class DevPlanTaskExportDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
columns?: string[];
|
||||
}
|
||||
|
||||
export class BatchReviewPreviewDto {
|
||||
|
||||
@@ -140,6 +140,7 @@ export class FulfillmentProviderService {
|
||||
? JSON.stringify({
|
||||
createShipment: true,
|
||||
getTrack: true,
|
||||
getSignPhotos: true,
|
||||
callback: true,
|
||||
cancel: true,
|
||||
})
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, Inject, forwardRef } from '@nestjs/common';
|
||||
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 {
|
||||
BOTTLES_PER_BOX,
|
||||
XFX_AUTO_DISPATCH_MAX_BOXES,
|
||||
@@ -29,6 +33,7 @@ export type ManualShipInput = {
|
||||
export type HqLogisticsShipInput = ManualShipInput;
|
||||
|
||||
export const FULFILLMENT_HOLD_LARGE_ORDER = 'LARGE_ORDER_GE_10_BOXES';
|
||||
export { FULFILLMENT_HOLD_COURIER_OUT_OF_SERVICE, FULFILLMENT_HOLD_COURIER_DISPATCH_FAILED };
|
||||
|
||||
@Injectable()
|
||||
export class FulfillmentService {
|
||||
@@ -138,6 +143,7 @@ export class FulfillmentService {
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
await this.logDispatchFailure(order, provider, message);
|
||||
await this.markCourierDispatchHold(order.id, message);
|
||||
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
||||
return;
|
||||
}
|
||||
@@ -213,6 +219,7 @@ export class FulfillmentService {
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
await this.logDispatchFailure(order, provider, message);
|
||||
await this.markCourierDispatchHold(order.id, message);
|
||||
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
||||
}
|
||||
}
|
||||
@@ -306,8 +313,9 @@ export class FulfillmentService {
|
||||
trackingNumber: order.delivery.trackingNo ?? undefined,
|
||||
outNumber: order.orderNo,
|
||||
};
|
||||
const cachedSignPhotoUrl = order.delivery.signPhotoResource?.url ?? null;
|
||||
|
||||
const [trackResult, signPhotoDataUris] = await Promise.all([
|
||||
const [trackResult, signPhotoResult] = await Promise.all([
|
||||
this.courier
|
||||
.getTrack(shipmentQuery, options)
|
||||
.then((nodes) => ({ nodes: Array.isArray(nodes) ? nodes : [], error: null as string | null }))
|
||||
@@ -315,12 +323,30 @@ export class FulfillmentService {
|
||||
nodes: [] as TrackNode[],
|
||||
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.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)) {
|
||||
const toAddress = this.buildReceiverAddress(order);
|
||||
@@ -424,17 +450,24 @@ export class FulfillmentService {
|
||||
},
|
||||
dataUris: string[],
|
||||
): Promise<string[]> {
|
||||
if (!order.delivery || dataUris.length === 0) {
|
||||
return order.delivery?.signPhotoResource?.url ? [order.delivery.signPhotoResource.url] : [];
|
||||
if (!order.delivery) return [];
|
||||
if (order.delivery.signPhotoResource?.url) {
|
||||
return [order.delivery.signPhotoResource.url];
|
||||
}
|
||||
if (dataUris.length === 0) return [];
|
||||
|
||||
const urls: string[] = [];
|
||||
let firstResourceId: bigint | null = order.delivery.signPhotoResourceId;
|
||||
|
||||
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;
|
||||
|
||||
try {
|
||||
if (!this.oss.isEnabled()) {
|
||||
throw new Error('OSS 未配置');
|
||||
}
|
||||
const result = await this.oss.putObject({
|
||||
bizType: 'SIGN_PHOTO',
|
||||
mediaType: 'IMAGE',
|
||||
@@ -462,6 +495,18 @@ export class FulfillmentService {
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
if (firstResourceId && firstResourceId !== order.delivery.signPhotoResourceId) {
|
||||
@@ -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) {
|
||||
if (!warehouseId) return undefined;
|
||||
const wh = await this.prisma.cityWarehouse.findUnique({ where: { id: warehouseId } });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Body, Controller, Param, Put, UseGuards } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SaveHqListColumnPrefsDto } from './dto/auth.dto';
|
||||
import { SaveHqListColumnPrefsDto, UpdateMyHqCredentialsDto } from './dto/auth.dto';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
@@ -18,4 +18,9 @@ export class AdminMeController {
|
||||
) {
|
||||
return this.authService.updateMyListColumnPrefs(user.actorType, user.actorId, listKey, dto);
|
||||
}
|
||||
|
||||
@Put('credentials')
|
||||
updateCredentials(@CurrentUser() user: AuthUser, @Body() dto: UpdateMyHqCredentialsDto) {
|
||||
return this.authService.updateMyHqCredentials(user.actorType, user.actorId, dto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import type { SmsActorRef } from '../../integrations/sms/sms.interface';
|
||||
import { SmsCodeStore } from '../../integrations/sms/sms-code.store';
|
||||
import type { IWechatProvider } from '../../integrations/wechat/wechat.interface';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
import { verifyPassword } from '../../common/crypto/password.util';
|
||||
import { verifyPassword, hashPassword } from '../../common/crypto/password.util';
|
||||
import { AnalyticsService } from '../analytics/analytics.service';
|
||||
import { UserAddressService } from './user-address.service';
|
||||
import { ResourceService } from '../common/resource.service';
|
||||
@@ -1287,6 +1287,50 @@ export class AuthService {
|
||||
return { listColumnPrefs: parseListColumnPrefs(updated.listColumnPrefs) };
|
||||
}
|
||||
|
||||
async updateMyHqCredentials(
|
||||
actorType: string,
|
||||
actorId: bigint,
|
||||
dto: { loginName?: string; oldPassword?: string; newPassword?: string },
|
||||
) {
|
||||
if (actorType !== 'HQ') throw new ForbiddenException('仅总部账号可修改');
|
||||
const account = await this.prisma.hqAccount.findUnique({ where: { id: actorId } });
|
||||
if (!account) throw new NotFoundException('账号不存在');
|
||||
|
||||
const data: { loginName?: string; passwordHash?: string } = {};
|
||||
const nextLogin = dto.loginName?.trim();
|
||||
if (nextLogin !== undefined) {
|
||||
if (!nextLogin) throw new BadRequestException('用户名不能为空');
|
||||
if (nextLogin !== account.loginName) {
|
||||
const dup = await this.prisma.hqAccount.findUnique({ where: { loginName: nextLogin } });
|
||||
if (dup && dup.id !== account.id) throw new BadRequestException('用户名已被占用');
|
||||
data.loginName = nextLogin;
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.newPassword !== undefined) {
|
||||
const pwd = dto.newPassword.trim();
|
||||
if (pwd.length < 6) throw new BadRequestException('新密码至少 6 位');
|
||||
if (account.passwordHash) {
|
||||
if (!dto.oldPassword?.trim()) throw new BadRequestException('请输入当前密码');
|
||||
if (!verifyPassword(dto.oldPassword.trim(), account.passwordHash)) {
|
||||
throw new BadRequestException('当前密码不正确');
|
||||
}
|
||||
}
|
||||
data.passwordHash = hashPassword(pwd);
|
||||
}
|
||||
|
||||
if (!Object.keys(data).length) {
|
||||
throw new BadRequestException('请填写要修改的内容');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.hqAccount.update({
|
||||
where: { id: actorId },
|
||||
data,
|
||||
});
|
||||
const { passwordHash: _ph, ...safe } = updated;
|
||||
return serializeBigInt(safe);
|
||||
}
|
||||
|
||||
wechatDisabled() {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
@@ -130,6 +130,22 @@ export class CheckPartnerPhoneDto {
|
||||
phone: string;
|
||||
}
|
||||
|
||||
export class UpdateMyHqCredentialsDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
loginName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
oldPassword?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
newPassword?: string;
|
||||
}
|
||||
|
||||
export class SaveHqListColumnPrefsDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
@@ -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 { 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>) {
|
||||
this.assertShippingFields(body);
|
||||
const isDefault = body.isDefault ? 1 : 0;
|
||||
const address = await this.prisma.$transaction(async (tx) => {
|
||||
if (isDefault) {
|
||||
@@ -52,6 +71,7 @@ export class UserAddressService {
|
||||
async update(userId: bigint, id: bigint, body: Record<string, unknown>) {
|
||||
const existing = await this.prisma.userAddress.findFirst({ where: { id, userId } });
|
||||
if (!existing) throw new NotFoundException('地址不存在');
|
||||
this.assertShippingFields(body, existing);
|
||||
const address = await this.prisma.$transaction(async (tx) => {
|
||||
if (body.isDefault) {
|
||||
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 { 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 {
|
||||
HqPermissionsResolver,
|
||||
@@ -9,43 +20,8 @@ import {
|
||||
type HqCityScope,
|
||||
} from '../../common/guards/hq-permission.guard';
|
||||
import type { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
function startOfDay(d: Date) {
|
||||
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);
|
||||
}
|
||||
import { type CityFilter } from './admin-dashboard-analytics';
|
||||
import { loadDashboardLineCharts } from './admin-dashboard-lines';
|
||||
|
||||
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
||||
const day = appliedAt.getDay();
|
||||
@@ -296,17 +272,20 @@ export class AdminDashboardService {
|
||||
};
|
||||
}
|
||||
|
||||
async getAnalytics(actorId: bigint, query: AdminDashboardAnalyticsQueryDto) {
|
||||
const today = startOfDay(new Date());
|
||||
const defaultFrom = new Date(today);
|
||||
defaultFrom.setDate(defaultFrom.getDate() - 29);
|
||||
|
||||
const from =
|
||||
(query.dateFrom ? parseYmd(query.dateFrom) : null) ?? defaultFrom;
|
||||
const to =
|
||||
(query.dateTo ? parseYmd(query.dateTo) : null) ?? today;
|
||||
const rangeStart = startOfDay(from <= to ? from : to);
|
||||
const rangeEnd = endOfDay(from <= to ? to : from);
|
||||
async getAnalytics(
|
||||
actorId: bigint,
|
||||
query: AdminDashboardAnalyticsQueryDto,
|
||||
): Promise<DashboardAnalytics> {
|
||||
const grain: DashboardGranularity = query.granularity ?? 'day';
|
||||
const defaults = defaultShanghaiRangeYmds(grain);
|
||||
const fromYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateFrom ?? '')
|
||||
? query.dateFrom!
|
||||
: defaults.from;
|
||||
const toYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateTo ?? '') ? query.dateTo! : defaults.to;
|
||||
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([
|
||||
this.hqPermissions.resolveAccess(actorId),
|
||||
@@ -314,518 +293,46 @@ export class AdminDashboardService {
|
||||
]);
|
||||
const can = (k: HqPermissionKey) => isSuperAdmin || keys.includes(k);
|
||||
|
||||
let filterCityCode: string | string[] | null | undefined;
|
||||
let filterCityId: bigint | bigint[] | null | undefined;
|
||||
let city: CityFilter = { kind: 'all' };
|
||||
if (query.cityId === 'none') {
|
||||
if (scope !== null) {
|
||||
throw new ForbiddenException('无权按未选城筛选');
|
||||
}
|
||||
filterCityCode = null;
|
||||
filterCityId = null;
|
||||
if (scope !== null) throw new ForbiddenException('无权按未选城筛选');
|
||||
city = { kind: 'none' };
|
||||
} else if (query.cityId) {
|
||||
const city = await this.prisma.commonCity.findUnique({
|
||||
const row = await this.prisma.commonCity.findUnique({
|
||||
where: { id: BigInt(query.cityId) },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
if (!city) {
|
||||
throw new ForbiddenException('无权访问该城市的门店');
|
||||
}
|
||||
assertHqCityInScope(scope, city.id);
|
||||
filterCityCode = city.code;
|
||||
filterCityId = city.id;
|
||||
if (!row) throw new ForbiddenException('无权访问该城市的门店');
|
||||
assertHqCityInScope(scope, row.id);
|
||||
city = { kind: 'ids', ids: [row.id], codes: [row.code] };
|
||||
} else if (scope !== null) {
|
||||
if (!scope.length) {
|
||||
filterCityId = [];
|
||||
filterCityCode = [];
|
||||
city = { kind: 'empty' };
|
||||
} else {
|
||||
const scopedCities = await this.prisma.commonCity.findMany({
|
||||
where: { id: { in: scope } },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
filterCityId = scope;
|
||||
filterCityCode = scopedCities.map((c) => c.code);
|
||||
city = { kind: 'ids', ids: scope, codes: scopedCities.map((c) => c.code) };
|
||||
}
|
||||
}
|
||||
|
||||
const filterPromoNone = query.promoCodeId === 'none';
|
||||
const filterPromoId =
|
||||
can('promo_codes') && query.promoCodeId && query.promoCodeId !== 'none'
|
||||
? BigInt(query.promoCodeId)
|
||||
: undefined;
|
||||
const filterPartnerId =
|
||||
can('partners') && query.partnerAccountId
|
||||
? BigInt(query.partnerAccountId)
|
||||
: undefined;
|
||||
|
||||
if (filterPartnerId !== undefined && scope !== null) {
|
||||
const partner = await this.prisma.partnerAccount.findUnique({
|
||||
where: { id: filterPartnerId },
|
||||
select: { cityId: true },
|
||||
const buckets = eachShanghaiBuckets(rangeStart, toDay, grain);
|
||||
const charts = await loadDashboardLineCharts({
|
||||
prisma: this.prisma,
|
||||
grain,
|
||||
city,
|
||||
rangeStart,
|
||||
rangeEndExclusive,
|
||||
periodKeys: buckets.map((b) => b.key),
|
||||
can,
|
||||
});
|
||||
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 {
|
||||
summary: {
|
||||
users: users.length,
|
||||
orders: orders.length,
|
||||
payingUsers: payingUserIds.size,
|
||||
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,
|
||||
})),
|
||||
granularity: grain,
|
||||
range: { from: shanghaiYmd(fromDay), to: shanghaiYmd(toDay) },
|
||||
periods: buckets.map((b) => ({ key: b.key, label: b.label })),
|
||||
charts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,20 +3,16 @@ import ExcelJS from 'exceljs';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import PDFDocument from 'pdfkit';
|
||||
import {
|
||||
pickExportColumns,
|
||||
type ExportColumnDef,
|
||||
} from '../../common/export/column-export.util';
|
||||
|
||||
const EXPORT_HEADERS = [
|
||||
'订单号',
|
||||
'下单时间',
|
||||
'状态',
|
||||
'商品',
|
||||
'规格',
|
||||
'数量',
|
||||
'实付',
|
||||
'好客权益',
|
||||
'收货人',
|
||||
'手机',
|
||||
'收货地址',
|
||||
] as const;
|
||||
const DELIVERY_TYPE_LABELS: Record<string, string> = {
|
||||
LOCAL: '同城',
|
||||
CROSS_CITY: '跨城',
|
||||
ON_SITE_PICKUP: '现场提货',
|
||||
};
|
||||
|
||||
export type OrderExportRow = {
|
||||
orderNo: string;
|
||||
@@ -25,7 +21,9 @@ export type OrderExportRow = {
|
||||
productName: string;
|
||||
productSpec: string;
|
||||
quantity: number;
|
||||
deliveryType: string;
|
||||
payAmount: number;
|
||||
logisticsFee: string;
|
||||
benefitBrief: string;
|
||||
receiverName: string;
|
||||
receiverPhone: string;
|
||||
@@ -95,7 +93,9 @@ export function mapOrderToExportRow(order: {
|
||||
productName: order.productName,
|
||||
productSpec: order.productSpec,
|
||||
quantity: order.quantity,
|
||||
deliveryType: DELIVERY_TYPE_LABELS[order.deliveryType ?? ''] || order.deliveryType || '',
|
||||
payAmount: Number(order.payAmount),
|
||||
logisticsFee: '',
|
||||
benefitBrief: formatBenefitBrief(order),
|
||||
receiverName: order.receiverName,
|
||||
receiverPhone: order.receiverPhone,
|
||||
@@ -103,22 +103,49 @@ export function mapOrderToExportRow(order: {
|
||||
};
|
||||
}
|
||||
|
||||
export function rowToCells(row: OrderExportRow): string[] {
|
||||
function orderExportColumnDefs(): ExportColumnDef<OrderExportRow>[] {
|
||||
return [
|
||||
row.orderNo,
|
||||
row.createdAt,
|
||||
row.status,
|
||||
row.productName,
|
||||
row.productSpec,
|
||||
String(row.quantity),
|
||||
row.payAmount.toFixed(2),
|
||||
row.benefitBrief,
|
||||
row.receiverName,
|
||||
row.receiverPhone,
|
||||
row.address,
|
||||
{ key: '订单号', header: '订单号', value: (r) => r.orderNo },
|
||||
{ key: '下单时间', header: '下单时间', value: (r) => r.createdAt },
|
||||
{ key: '状态', header: '状态', value: (r) => r.status },
|
||||
{ key: '商品', header: '商品', value: (r) => r.productName },
|
||||
{ key: '规格', header: '规格', value: (r) => r.productSpec },
|
||||
{ key: '数量', header: '数量', value: (r) => r.quantity },
|
||||
{ key: '配送方式', header: '配送方式', value: (r) => r.deliveryType },
|
||||
{ key: '实付', header: '实付', value: (r) => r.payAmount.toFixed(2) },
|
||||
{ key: '运费', header: '运费', value: (r) => r.logisticsFee },
|
||||
{ key: '好客权益', header: '好客权益', value: (r) => r.benefitBrief },
|
||||
{ key: '收货人', header: '收货人', value: (r) => r.receiverName },
|
||||
{ key: '电话', header: '电话', value: (r) => r.receiverPhone },
|
||||
{ key: '地址', header: '地址', value: (r) => r.address },
|
||||
];
|
||||
}
|
||||
|
||||
const ORDER_COLUMN_ALIASES: Record<string, string> = {
|
||||
orderNo: '订单号',
|
||||
createdAt: '下单时间',
|
||||
status: '状态',
|
||||
productName: '商品',
|
||||
productSpec: '规格',
|
||||
quantity: '数量',
|
||||
deliveryType: '配送方式',
|
||||
payAmount: '实付',
|
||||
logisticsFee: '运费',
|
||||
benefitBrief: '好客权益',
|
||||
receiverName: '收货人',
|
||||
receiverPhone: '电话',
|
||||
phone: '电话',
|
||||
receiverAddress: '地址',
|
||||
address: '地址',
|
||||
手机: '电话',
|
||||
收货地址: '地址',
|
||||
};
|
||||
|
||||
function normalizeOrderColumns(columnKeys?: string[]): string[] | undefined {
|
||||
if (!columnKeys?.length) return undefined;
|
||||
return columnKeys.map((k) => ORDER_COLUMN_ALIASES[k] ?? k);
|
||||
}
|
||||
|
||||
function resolvePdfFontPath(): string {
|
||||
const candidates = [
|
||||
process.env.EXPORT_PDF_FONT_PATH,
|
||||
@@ -138,79 +165,42 @@ function resolvePdfFontPath(): string {
|
||||
throw new Error('未找到可用于 PDF 的中文字体,请将字体文件放到 server/dukang-api/assets/fonts/');
|
||||
}
|
||||
|
||||
export async function buildOrdersXlsx(rows: OrderExportRow[]): Promise<Buffer> {
|
||||
export async function buildOrdersXlsx(rows: OrderExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||
const cols = pickExportColumns(orderExportColumnDefs(), normalizeOrderColumns(columnKeys));
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet('订单');
|
||||
sheet.addRow([...EXPORT_HEADERS]);
|
||||
sheet.addRow(cols.map((c) => c.header));
|
||||
for (const row of rows) {
|
||||
sheet.addRow(rowToCells(row));
|
||||
sheet.addRow(cols.map((c) => c.value(row)));
|
||||
}
|
||||
sheet.columns.forEach((col) => {
|
||||
col.width = 16;
|
||||
});
|
||||
sheet.getColumn(4).width = 22;
|
||||
sheet.getColumn(8).width = 36;
|
||||
sheet.getColumn(11).width = 36;
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
return Buffer.from(buffer);
|
||||
}
|
||||
|
||||
export async function buildOrdersPdf(rows: OrderExportRow[]): Promise<Buffer> {
|
||||
export async function buildOrdersPdf(rows: OrderExportRow[], columnKeys?: string[]): Promise<Buffer> {
|
||||
const cols = pickExportColumns(orderExportColumnDefs(), normalizeOrderColumns(columnKeys));
|
||||
const fontPath = resolvePdfFontPath();
|
||||
const chunks: Buffer[] = [];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
layout: 'landscape',
|
||||
margin: 24,
|
||||
bufferPages: true,
|
||||
});
|
||||
doc.on('data', (chunk) => chunks.push(chunk as Buffer));
|
||||
const doc = new PDFDocument({ size: 'A4', layout: 'landscape', margin: 24, bufferPages: true });
|
||||
doc.on('data', (c) => chunks.push(c as Buffer));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
|
||||
doc.registerFont('zh', fontPath);
|
||||
doc.font('zh');
|
||||
|
||||
const pageWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
|
||||
const colWidths = [72, 78, 48, 88, 64, 32, 48, 110, 48, 72, 120];
|
||||
const scale = pageWidth / colWidths.reduce((sum, w) => sum + w, 0);
|
||||
const widths = colWidths.map((w) => w * scale);
|
||||
const rowHeight = 28;
|
||||
const fontSize = 7;
|
||||
let y = doc.page.margins.top;
|
||||
|
||||
const drawRow = (cells: string[], isHeader = false) => {
|
||||
let x = doc.page.margins.left;
|
||||
const height = isHeader ? 24 : rowHeight;
|
||||
if (y + height > doc.page.height - doc.page.margins.bottom) {
|
||||
doc.addPage({ size: 'A4', layout: 'landscape', margin: 24 });
|
||||
y = doc.page.margins.top;
|
||||
}
|
||||
doc.fontSize(isHeader ? 8 : fontSize);
|
||||
cells.forEach((cell, index) => {
|
||||
doc.rect(x, y, widths[index], height).stroke('#dddddd');
|
||||
doc.text(cell || '', x + 2, y + 4, {
|
||||
width: widths[index] - 4,
|
||||
height: height - 6,
|
||||
lineBreak: true,
|
||||
});
|
||||
x += widths[index];
|
||||
});
|
||||
y += height;
|
||||
};
|
||||
|
||||
drawRow([...EXPORT_HEADERS], true);
|
||||
doc.font(fontPath);
|
||||
doc.fontSize(10).text(cols.map((c) => c.header).join(' | '));
|
||||
doc.moveDown(0.5);
|
||||
for (const row of rows) {
|
||||
drawRow(rowToCells(row));
|
||||
doc.text(cols.map((c) => String(c.value(row))).join(' | '));
|
||||
}
|
||||
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
|
||||
export function buildExportFilename(format: 'xlsx' | 'pdf', count: number): string {
|
||||
const stamp = formatShanghaiDateTime(new Date()).slice(0, 10);
|
||||
return `订单导出_${stamp}_${count}条.${format}`;
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
return `订单导出_${stamp}_${count}.${format}`;
|
||||
}
|
||||
|
||||
@@ -156,7 +156,9 @@ export class AdminOrdersService {
|
||||
|
||||
const rows = orders.map((order) => mapOrderToExportRow(order));
|
||||
const buffer =
|
||||
dto.format === 'pdf' ? await buildOrdersPdf(rows) : await buildOrdersXlsx(rows);
|
||||
dto.format === 'pdf'
|
||||
? await buildOrdersPdf(rows, dto.columns)
|
||||
: await buildOrdersXlsx(rows, dto.columns);
|
||||
const filename = buildExportFilename(dto.format, rows.length);
|
||||
const mimeType =
|
||||
dto.format === 'pdf'
|
||||
|
||||
@@ -14,6 +14,12 @@ import { contractMediaType, normalizeContractUrls } from '../../common/store-med
|
||||
import type { AdminStoreAccountsQueryDto, AdminStoreMediaQueryDto, AdminStoresQueryDto } from './dto/admin-query.dto';
|
||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||
import { StoreCategoryService } from '../store/store-category.service';
|
||||
import {
|
||||
attachStoreCategories,
|
||||
parseUniqueCategoryIds,
|
||||
storeCategoryLinkInclude,
|
||||
syncStoreCategoryLinks,
|
||||
} from '../store/store-category-link.util';
|
||||
import { AnalyticsService } from '../analytics/analytics.service';
|
||||
import type {
|
||||
CreateStoreAccountDto,
|
||||
@@ -123,6 +129,7 @@ export class AdminStoresService {
|
||||
cityRef: { select: { id: true, name: true, code: true } },
|
||||
partnerAccount: { select: { id: true, companyName: true, name: true, phone: true } },
|
||||
category: { select: { id: true, name: true, parentId: true } },
|
||||
...storeCategoryLinkInclude,
|
||||
bindings: {
|
||||
where: { storeAccount: { isPrimary: 1 } },
|
||||
take: 1,
|
||||
@@ -169,7 +176,7 @@ export class AdminStoresService {
|
||||
return serializeBigInt({
|
||||
items: items.map((s) => {
|
||||
const { visibilityPhones, ...rest } = s;
|
||||
return mapStoreCompat({
|
||||
return mapStoreCompat(attachStoreCategories({
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: s.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||
@@ -180,7 +187,7 @@ export class AdminStoresService {
|
||||
partner: s.partnerAccount,
|
||||
account: s.bindings[0]?.storeAccount ?? null,
|
||||
bindings: undefined,
|
||||
});
|
||||
}));
|
||||
}),
|
||||
total,
|
||||
page,
|
||||
@@ -196,6 +203,7 @@ export class AdminStoresService {
|
||||
cityRef: true,
|
||||
partnerAccount: true,
|
||||
category: true,
|
||||
...storeCategoryLinkInclude,
|
||||
bindings: {
|
||||
where: { storeAccount: { isPrimary: 1 } },
|
||||
take: 1,
|
||||
@@ -219,7 +227,7 @@ export class AdminStoresService {
|
||||
}),
|
||||
]);
|
||||
const { visibilityPhones, ...rest } = store;
|
||||
return serializeBigInt(mapStoreCompat({
|
||||
return serializeBigInt(mapStoreCompat(attachStoreCategories({
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: store.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||
@@ -235,7 +243,7 @@ export class AdminStoresService {
|
||||
redeemCount: store._count.redeemRecords,
|
||||
ratingCount: store._count.ratings,
|
||||
_count: undefined,
|
||||
}));
|
||||
})));
|
||||
}
|
||||
|
||||
async updateStoreStatus(id: bigint, dto: UpdateStoreStatusDto, actorId: bigint) {
|
||||
@@ -430,11 +438,22 @@ export class AdminStoresService {
|
||||
}
|
||||
|
||||
let categoryId: bigint | undefined;
|
||||
if (dto.categoryId !== undefined) {
|
||||
let categoryIds: bigint[] | undefined;
|
||||
if (dto.categoryIds !== undefined) {
|
||||
categoryIds = parseUniqueCategoryIds(dto.categoryIds);
|
||||
if (!categoryIds.length) {
|
||||
throw new BadRequestException('请选择门店分类');
|
||||
}
|
||||
for (const id of categoryIds) {
|
||||
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||
}
|
||||
categoryId = categoryIds[0];
|
||||
} else if (dto.categoryId !== undefined) {
|
||||
if (!dto.categoryId?.trim()) {
|
||||
throw new BadRequestException('请选择门店分类');
|
||||
}
|
||||
categoryId = BigInt(dto.categoryId);
|
||||
categoryIds = [categoryId];
|
||||
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
||||
}
|
||||
|
||||
@@ -661,6 +680,10 @@ export class AdminStoresService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (categoryIds !== undefined) {
|
||||
await syncStoreCategoryLinks(tx, id, categoryIds);
|
||||
}
|
||||
});
|
||||
|
||||
return this.detailStore(id, actorId);
|
||||
@@ -693,11 +716,20 @@ export class AdminStoresService {
|
||||
if (!city) throw new BadRequestException('开城城市不存在');
|
||||
await this.partnerCityService.assertPartnerAccountBoundToCity(partnerAccountId, city.id);
|
||||
|
||||
if (!dto.categoryId?.trim()) {
|
||||
if (!dto.categoryId?.trim() && (!dto.categoryIds || !dto.categoryIds.length)) {
|
||||
throw new BadRequestException('请选择门店分类');
|
||||
}
|
||||
const categoryId = BigInt(dto.categoryId);
|
||||
await this.storeCategoryService.assertLeafCategoryId(categoryId);
|
||||
const categoryIds = parseUniqueCategoryIds(dto.categoryIds);
|
||||
if (!categoryIds.length && dto.categoryId?.trim()) {
|
||||
categoryIds.push(BigInt(dto.categoryId));
|
||||
}
|
||||
if (!categoryIds.length) {
|
||||
throw new BadRequestException('请选择门店分类');
|
||||
}
|
||||
for (const id of categoryIds) {
|
||||
await this.storeCategoryService.assertLeafCategoryId(id);
|
||||
}
|
||||
const categoryId = categoryIds[0];
|
||||
|
||||
const latitude = dto.latitude != null ? Number(dto.latitude) : null;
|
||||
const longitude = dto.longitude != null ? Number(dto.longitude) : null;
|
||||
@@ -775,6 +807,8 @@ export class AdminStoresService {
|
||||
},
|
||||
});
|
||||
|
||||
await syncStoreCategoryLinks(this.prisma, store.id, categoryIds);
|
||||
|
||||
if (dto.coverUrl) {
|
||||
const cover = await this.prisma.commonResource.create({
|
||||
data: {
|
||||
|
||||
@@ -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) {
|
||||
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));
|
||||
}
|
||||
|
||||
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() {
|
||||
const fromDb = await this.fulfillmentProviderService.resolveDefaultXiaofeixiaConfig();
|
||||
return fromDb ? { xiaofeixia: fromDb } : undefined;
|
||||
|
||||
@@ -45,9 +45,15 @@ export class CreateStoreDto {
|
||||
@IsString()
|
||||
contactPhone?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
categoryId: string;
|
||||
categoryId?: string;
|
||||
|
||||
/** 多选二级分类;至少选一项 */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
categoryIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@@ -240,6 +246,12 @@ export class UpdateStoreDto {
|
||||
@IsString()
|
||||
categoryId?: string;
|
||||
|
||||
/** 多选二级分类;传此项时覆盖 categoryId */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
categoryIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@@ -1152,7 +1164,7 @@ export class CreateHqAccountDto {
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE'])
|
||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE', 'DEVELOPER'])
|
||||
adminRole?: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -1179,7 +1191,7 @@ export class UpdateHqAccountDto {
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE'])
|
||||
@IsIn(['SUPER_ADMIN', 'OPS', 'FINANCE', 'CUSTOMER_SERVICE', 'CITY_STORE_SERVICE', 'DEVELOPER'])
|
||||
adminRole?: string;
|
||||
|
||||
@IsOptional()
|
||||
|
||||
@@ -225,11 +225,21 @@ export class AdminOrdersExportDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
assocPartnerAccountId?: string;
|
||||
|
||||
/** 按列表可见列导出(中文列名或英文 key) */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
columns?: string[];
|
||||
}
|
||||
|
||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
||||
/** 概览页折线图:只吃全局粒度 / 日期 / 城市 */
|
||||
export class AdminDashboardAnalyticsQueryDto {
|
||||
/** YYYY-MM-DD,默认近 30 天 */
|
||||
@IsOptional()
|
||||
@IsIn(['day', 'week', 'month', 'quarter', 'year'])
|
||||
granularity?: 'day' | 'week' | 'month' | 'quarter' | 'year';
|
||||
|
||||
/** YYYY-MM-DD,默认随粒度 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateFrom?: string;
|
||||
@@ -242,16 +252,6 @@ export class AdminDashboardAnalyticsQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cityId?: string;
|
||||
|
||||
/** 推广码 id;`none` = 无归因 / 订单无推广码 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
|
||||
/** 城市合伙人(主账号)id */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
partnerAccountId?: string;
|
||||
}
|
||||
|
||||
export class AdminStoresQueryDto extends PaginationQueryDto {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user