Compare commits
3 Commits
6a23e79f4c
...
3fc2f23e10
| Author | SHA1 | Date | |
|---|---|---|---|
| 3fc2f23e10 | |||
| 09e732bfa3 | |||
| 50ba6e9c56 |
@@ -11,6 +11,10 @@ server/dukang-api/.env.production.local
|
||||
server/dukang-api/.env.staging
|
||||
server/dukang-api/.env.staging.local
|
||||
deploy/deploy.env
|
||||
deploy/.staging-mysql.pass
|
||||
deploy/_ops-*.log
|
||||
deploy/_ops-*.sh
|
||||
|
||||
.DS_Store
|
||||
coverage/
|
||||
*.tsbuildinfo
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -13,6 +13,8 @@
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"antd": "^5.22.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
QRCode,
|
||||
Radio,
|
||||
Select,
|
||||
Space,
|
||||
@@ -18,6 +19,8 @@ import type {
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
} from '@dukang/shared-types';
|
||||
import ChinaRegionCascader from './ChinaRegionCascader';
|
||||
import { parseRegionCodes } from '../lib/china-region';
|
||||
@@ -29,6 +32,13 @@ type ProxyOrderModalProps = {
|
||||
onSuccess: (order: { id: string; orderNo: string }) => void;
|
||||
};
|
||||
|
||||
type PayStatus = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payStatus: string;
|
||||
};
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
@@ -49,8 +59,22 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [payLoading, setPayLoading] = useState(false);
|
||||
const [mockConfirming, setMockConfirming] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setLoadingOptions(true);
|
||||
@@ -64,8 +88,8 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !productId || quantity < 1) {
|
||||
setPreview(null);
|
||||
if (!open || !productId || quantity < 1 || step !== 'form') {
|
||||
if (step === 'form') setPreview(null);
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -85,9 +109,12 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
.finally(() => setPreviewLoading(false));
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [open, productId, quantity, deliveryMode, region?.city, region?.district]);
|
||||
}, [open, productId, quantity, deliveryMode, region?.city, region?.district, step]);
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
function resetForm() {
|
||||
stopPoll();
|
||||
setPhone('');
|
||||
setReceiverName('');
|
||||
setRegionCodes([]);
|
||||
@@ -98,6 +125,11 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
setAutoReceive(false);
|
||||
setPreview(null);
|
||||
setProductId(options?.products[0]?.id);
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
setCodeUrl(null);
|
||||
setPayLoading(false);
|
||||
setMockConfirming(false);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -120,6 +152,23 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
return null;
|
||||
}
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<PayStatus>(`/admin/proxy-orders/${orderId}/pay-status`)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
message.success(`支付成功:${st.orderNo}`);
|
||||
const payload = { id: st.id, orderNo: st.orderNo };
|
||||
resetForm();
|
||||
onSuccess(payload);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const err = validateForm();
|
||||
if (err) {
|
||||
@@ -143,17 +192,46 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<{ id: string; orderNo: string }>('/admin/proxy-orders', {
|
||||
const order = await request<ProxyOrderCreateResponse>('/admin/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
message.success(`代下单成功:${order.orderNo}`);
|
||||
resetForm();
|
||||
onSuccess(order);
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setPayLoading(true);
|
||||
const pay = await request<ProxyOrderPayResponse>(`/admin/proxy-orders/${order.id}/pay`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: 'NATIVE' }),
|
||||
});
|
||||
setCodeUrl(pay.codeUrl ?? null);
|
||||
startPoll(order.id);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '下单失败');
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setPayLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMockConfirm() {
|
||||
if (!created) return;
|
||||
setMockConfirming(true);
|
||||
try {
|
||||
const st = await request<PayStatus>(`/admin/proxy-orders/${created.id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
});
|
||||
stopPoll();
|
||||
message.success(`支付成功:${st.orderNo}`);
|
||||
const payload = { id: st.id, orderNo: st.orderNo };
|
||||
resetForm();
|
||||
onSuccess(payload);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '模拟支付失败');
|
||||
} finally {
|
||||
setMockConfirming(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,138 +244,178 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title="代下单"
|
||||
title={step === 'pay' ? '代下单 · 待支付' : '代下单'}
|
||||
open={open}
|
||||
onCancel={handleClose}
|
||||
width={640}
|
||||
destroyOnClose
|
||||
footer={
|
||||
<Space>
|
||||
<Button onClick={handleClose}>取消</Button>
|
||||
<Button type="primary" loading={submitting || loadingOptions} onClick={() => void submit()}>
|
||||
确认代下单
|
||||
</Button>
|
||||
</Space>
|
||||
step === 'pay' ? (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>关闭</Button>
|
||||
<Button type="primary" loading={mockConfirming} onClick={() => void handleMockConfirm()}>
|
||||
模拟支付成功
|
||||
</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>取消</Button>
|
||||
<Button type="primary" loading={submitting || loadingOptions} onClick={() => void submit()}>
|
||||
提交并收款
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="线下已收款:提交后订单直接完成并发放好客权益"
|
||||
/>
|
||||
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="用户手机号" required>
|
||||
<Input
|
||||
placeholder="11 位手机号"
|
||||
value={phone}
|
||||
maxLength={11}
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
{step === 'pay' && created ? (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16, textAlign: 'left' }}
|
||||
message={`订单 ${created.orderNo} 待支付 ¥${fmtMoney(created.payAmount)},请扫码支付`}
|
||||
description={
|
||||
created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付完成后将进入现场提货闭环'
|
||||
: '支付完成后将进入待发货,由总部履约发货'
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="酒品" required>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
loading={loadingOptions}
|
||||
placeholder="选择商品"
|
||||
value={productId}
|
||||
onChange={setProductId}
|
||||
options={(options?.products ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.name} · ${p.spec} · ¥${fmtMoney(p.price)}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="数量" required>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={quantity}
|
||||
onChange={(v) => setQuantity(Math.max(1, Number(v) || 1))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{(options?.promoCodes.length ?? 0) > 0 ? (
|
||||
<Form.Item label="绑定推广码(选填)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不绑定"
|
||||
value={promoCodeId}
|
||||
onChange={setPromoCodeId}
|
||||
options={(options?.promoCodes ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.code} · ${p.name}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
placeholder="默认:用户+手机尾号"
|
||||
value={receiverName}
|
||||
maxLength={32}
|
||||
onChange={(e) => setReceiverName(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="省市区" required>
|
||||
<ChinaRegionCascader value={regionCodes} onChange={setRegionCodes} />
|
||||
</Form.Item>
|
||||
<Form.Item label="详细地址" required>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="街道门牌等"
|
||||
value={addressDetail}
|
||||
maxLength={256}
|
||||
onChange={(e) => setAddressDetail(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Checkbox checked={autoReceive} onChange={(e) => setAutoReceive(e.target.checked)}>
|
||||
同意自动收货(配送到址必选)
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div style={{ background: '#fafafa', borderRadius: 8, padding: 12 }}>
|
||||
<Typography.Text type="secondary">费用预览</Typography.Text>
|
||||
{previewLoading ? (
|
||||
<div>计算中…</div>
|
||||
) : preview ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', marginTop: 8 }}>
|
||||
<div>履约:{deliveryLabel}</div>
|
||||
<div>商品金额:¥{fmtMoney(preview.productAmount)}</div>
|
||||
<div>实付:¥{fmtMoney(preview.payAmount)}</div>
|
||||
<div>好客权益:¥{fmtMoney(preview.benefitAmount)}</div>
|
||||
{payLoading && !codeUrl ? (
|
||||
<Typography.Text type="secondary">正在生成收款码…</Typography.Text>
|
||||
) : codeUrl ? (
|
||||
<Space direction="vertical" size={12} align="center">
|
||||
<QRCode value={codeUrl} size={200} />
|
||||
<Typography.Text type="secondary">请使用微信扫一扫完成支付(本地可用下方模拟支付)</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, wordBreak: 'break-all' }}>
|
||||
{codeUrl}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Typography.Text type="secondary">请完善商品与数量</Typography.Text>
|
||||
</div>
|
||||
<Typography.Text type="danger">收款码生成失败,请关闭后重试</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="提交后生成微信收款码,支付成功后发放好客权益;配送单进入待发货"
|
||||
/>
|
||||
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="用户手机号" required>
|
||||
<Input
|
||||
placeholder="11 位手机号"
|
||||
value={phone}
|
||||
maxLength={11}
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="酒品" required>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
loading={loadingOptions}
|
||||
placeholder="选择商品"
|
||||
value={productId}
|
||||
onChange={setProductId}
|
||||
options={(options?.products ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.name} · ${p.spec} · ¥${fmtMoney(p.price)}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="数量" required>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={quantity}
|
||||
onChange={(v) => setQuantity(Math.max(1, Number(v) || 1))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{(options?.promoCodes.length ?? 0) > 0 ? (
|
||||
<Form.Item label="绑定推广码(选填)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不绑定"
|
||||
value={promoCodeId}
|
||||
onChange={setPromoCodeId}
|
||||
options={(options?.promoCodes ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.code} · ${p.name}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
placeholder="默认:用户+手机尾号"
|
||||
value={receiverName}
|
||||
maxLength={32}
|
||||
onChange={(e) => setReceiverName(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="省市区" required>
|
||||
<ChinaRegionCascader value={regionCodes} onChange={setRegionCodes} />
|
||||
</Form.Item>
|
||||
<Form.Item label="详细地址" required>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="街道门牌等"
|
||||
value={addressDetail}
|
||||
maxLength={256}
|
||||
onChange={(e) => setAddressDetail(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Checkbox checked={autoReceive} onChange={(e) => setAutoReceive(e.target.checked)}>
|
||||
同意自动收货(配送到址必选)
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div style={{ background: '#fafafa', borderRadius: 8, padding: 12 }}>
|
||||
<Typography.Text type="secondary">费用预览</Typography.Text>
|
||||
{previewLoading ? (
|
||||
<div>计算中…</div>
|
||||
) : preview ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', marginTop: 8 }}>
|
||||
<div>履约:{deliveryLabel}</div>
|
||||
<div>商品金额:¥{fmtMoney(preview.productAmount)}</div>
|
||||
<div>实付:¥{fmtMoney(preview.payAmount)}</div>
|
||||
<div>好客权益:¥{fmtMoney(preview.benefitAmount)}</div>
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Typography.Text type="secondary">请完善商品与数量</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -88,6 +88,51 @@ 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 SystemVersion = {
|
||||
id: string;
|
||||
gitTag: string | null;
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Button, Card, Col, Descriptions, Modal, Row, Space, Statistic, Table, Typography, message,
|
||||
Button, Card, Col, DatePicker, Descriptions, Form, Modal, Row, Select, Space, Statistic, Table, Typography, message,
|
||||
} from 'antd';
|
||||
import { CloudUploadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import {
|
||||
request,
|
||||
type DashboardAnalytics,
|
||||
type DashboardStats,
|
||||
type DeployTriggerResult,
|
||||
type HqProfile,
|
||||
type Paginated,
|
||||
type SystemVersion,
|
||||
} from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
@@ -31,6 +36,26 @@ const DEPLOYED_BY_LABELS: Record<string, string> = {
|
||||
admin: 'Admin 发布',
|
||||
};
|
||||
|
||||
type CityOption = { id: string; name: string; code: string };
|
||||
type PromoOption = { id: string; code: string; name: string };
|
||||
|
||||
type AnalyticsFilters = {
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
};
|
||||
|
||||
function buildAnalyticsQs(f: AnalyticsFilters) {
|
||||
const qs = new URLSearchParams();
|
||||
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();
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||
const [version, setVersion] = useState<SystemVersion | null>(null);
|
||||
@@ -40,6 +65,21 @@ export default function DashboardPage() {
|
||||
const [deploying, setDeploying] = useState(false);
|
||||
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
||||
|
||||
const [filterForm] = Form.useForm<{
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}>();
|
||||
const [filters, setFilters] = useState<AnalyticsFilters>({
|
||||
range: [dayjs().subtract(29, 'day'), dayjs()],
|
||||
});
|
||||
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 loadVersion = useCallback(() => {
|
||||
setVersionLoading(true);
|
||||
return request<SystemVersion | null>('/admin/dashboard/version')
|
||||
@@ -48,6 +88,17 @@ export default function DashboardPage() {
|
||||
.finally(() => setVersionLoading(false));
|
||||
}, []);
|
||||
|
||||
const loadAnalytics = useCallback((f: AnalyticsFilters) => {
|
||||
setAnalyticsLoading(true);
|
||||
return request<DashboardAnalytics>(`/admin/dashboard/analytics?${buildAnalyticsQs(f)}`)
|
||||
.then(setAnalytics)
|
||||
.catch((e) => {
|
||||
message.error(e instanceof Error ? e.message : '加载统计失败');
|
||||
setAnalytics(null);
|
||||
})
|
||||
.finally(() => setAnalyticsLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
request<DashboardStats>('/admin/dashboard/stats')
|
||||
.then(setStats)
|
||||
@@ -64,8 +115,64 @@ export default function DashboardPage() {
|
||||
.catch(() => {
|
||||
setVersionLoading(false);
|
||||
});
|
||||
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setCities(res.items ?? []))
|
||||
.catch(() => setCities([]));
|
||||
void request<Paginated<PromoOption>>(`/admin/promo-codes?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setPromos(res.items ?? []))
|
||||
.catch(() => setPromos([]));
|
||||
void request<Paginated<{ id: string; companyName?: string | null; name: string }>>(
|
||||
`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`,
|
||||
)
|
||||
.then((res) => setPartners(res.items ?? []))
|
||||
.catch(() => setPartners([]));
|
||||
}, [loadVersion]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadAnalytics(filters);
|
||||
}, [filters, loadAnalytics]);
|
||||
|
||||
function applyFilters(values: {
|
||||
range?: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}) {
|
||||
const next: AnalyticsFilters = {
|
||||
range: values.range ?? filters.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 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 handleDeploy() {
|
||||
Modal.confirm({
|
||||
title: '确认发布更新?',
|
||||
@@ -89,6 +196,176 @@ export default function DashboardPage() {
|
||||
|
||||
const shortSha = version?.commitId ? version.commitId.slice(0, 7) : '—';
|
||||
|
||||
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 ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增用户', '订单数'] },
|
||||
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: [
|
||||
{ name: '新增用户', type: 'line', smooth: true, data: rows.map((r) => r.users) },
|
||||
{ name: '订单数', type: 'line', smooth: true, data: rows.map((r) => r.orders) },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
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: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byPromoOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPromo ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
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: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByDateOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byDate ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增合伙人', '新签门店', '核销笔数', '核销金额'] },
|
||||
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: [
|
||||
{ name: '新增合伙人', type: 'line', smooth: true, data: rows.map((r) => r.partners) },
|
||||
{ name: '新签门店', type: 'line', smooth: true, data: rows.map((r) => r.stores) },
|
||||
{ name: '核销笔数', type: 'line', smooth: true, data: rows.map((r) => r.redeems) },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['合伙人', '门店', '核销笔数'] },
|
||||
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: [
|
||||
{ name: '合伙人', type: 'bar', data: rows.map((r) => r.partners), barMaxWidth: 28 },
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByPartnerOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPartner ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['门店', '核销笔数', '核销金额'] },
|
||||
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: [
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
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>
|
||||
<Typography.Title level={4}>数据概览</Typography.Title>
|
||||
@@ -176,6 +453,237 @@ export default function DashboardPage() {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
title="数据统计筛选"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
size="small"
|
||||
onClick={() => void loadAnalytics(filters)}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Form
|
||||
form={filterForm}
|
||||
layout="inline"
|
||||
initialValues={{ range: filters.range }}
|
||||
onFinish={applyFilters}
|
||||
>
|
||||
<Form.Item name="range" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
|
||||
<DatePicker.RangePicker allowClear={false} />
|
||||
</Form.Item>
|
||||
<Form.Item name="cityId" label="城市">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部开城"
|
||||
style={{ width: 160 }}
|
||||
options={[
|
||||
{ value: 'none', label: '未选城' },
|
||||
...cities.map((c) => ({ value: c.id, label: c.name })),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<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>
|
||||
<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>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="用户 / 订单统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to={`/orders?${ordersDrillQs}`}>查看订单</Link>
|
||||
<Link to="/users">查看用户</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间新增用户" value={analytics?.summary.users ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间订单数" value={analytics?.summary.orders ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间付费用户" value={analytics?.summary.payingUsers ?? 0} />
|
||||
</Col>
|
||||
</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={12}>
|
||||
<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>
|
||||
<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>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="合伙人 / 门店 / 核销统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to="/city-partners">查看合伙人</Link>
|
||||
<Link to="/stores">查看门店</Link>
|
||||
<Link to="/redeem-records">查看核销</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新增合伙人" value={analytics?.summary.partners ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新签门店" value={analytics?.summary.stores ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销笔数" value={analytics?.summary.redeems ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销金额" value={analytics?.summary.redeemAmount ?? 0} precision={2} />
|
||||
</Col>
|
||||
</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={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card
|
||||
|
||||
@@ -9,15 +9,17 @@
|
||||
"lint": "echo ok"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/weixin-sdk": "workspace:*",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getPartnerProfile } from '../lib/api';
|
||||
import { getPartnerProfile, hasPartnerWxSession } from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getPartnerProfile();
|
||||
if (profile && hasPartnerWxSession() && profile.hasWechat) {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -113,6 +113,10 @@ export function clearAuth(options?: { keepProfile?: boolean }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
export function isLoggedIn() {
|
||||
return !!localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
PENDING_SHIP: '待发货',
|
||||
OUT_WAREHOUSE: '已出库',
|
||||
SHIPPING: '配送中',
|
||||
PENDING_RECEIVE: '待收货',
|
||||
COMPLETED: '已完成',
|
||||
CANCELLED: '已取消',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
const PAY_LABELS: Record<string, string> = {
|
||||
UNPAID: '未支付',
|
||||
PAYING: '支付中',
|
||||
PAID: '已付款',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
export function proxyOrderStatusLabel(status?: string | null) {
|
||||
if (!status) return '—';
|
||||
return STATUS_LABELS[status] || status;
|
||||
}
|
||||
|
||||
export function proxyOrderPayLabel(payStatus?: string | null) {
|
||||
if (!payStatus) return '—';
|
||||
return PAY_LABELS[payStatus] || payStatus;
|
||||
}
|
||||
|
||||
export function proxyOrderStatusColor(status?: string | null) {
|
||||
if (status === 'PENDING_PAY') return 'var(--color-warning, #d48806)';
|
||||
if (status === 'COMPLETED') return 'var(--color-success-green)';
|
||||
if (status === 'CANCELLED' || status === 'REFUNDED') return 'var(--color-text-muted, #999)';
|
||||
return 'var(--color-primary, #8b1e1e)';
|
||||
}
|
||||
@@ -1,14 +1,25 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { WECHAT_INAPP_REQUIRED_MSG } from '@dukang/weixin-sdk';
|
||||
import {
|
||||
getLastPhone,
|
||||
getPartnerProfile,
|
||||
hasPartnerWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type PartnerSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
import {
|
||||
bindPartnerWechatAfterSmsLogin,
|
||||
canPartnerUseWechatLogin,
|
||||
fetchClientConfig,
|
||||
loginPartnerWithWechat,
|
||||
PARTNER_WECHAT_LOGIN_HINT,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
const REMEMBER_PHONE_KEY = 'partner_remember_phone';
|
||||
const REMEMBER_FLAG_KEY = 'partner_remember_account';
|
||||
@@ -39,6 +50,11 @@ function AgreementCheckbox({
|
||||
);
|
||||
}
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function loadRememberedPhone(): { phone: string; remember: boolean } {
|
||||
try {
|
||||
const remember = localStorage.getItem(REMEMBER_FLAG_KEY) === '1';
|
||||
@@ -60,9 +76,19 @@ function formatPartnerError(e: unknown): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession, refresh, account } = usePartnerSession();
|
||||
const [params] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getPartnerProfile();
|
||||
const remembered = loadRememberedPhone();
|
||||
const [phone, setPhone] = useState(remembered.phone || getLastPhone());
|
||||
@@ -70,10 +96,22 @@ export default function LoginPage() {
|
||||
const [rememberAccount, setRememberAccount] = useState(remembered.remember);
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
const quickName = savedProfile?.name ?? '城市合伙人';
|
||||
const quickCompany = savedProfile?.companyName ?? '';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先勾选并同意用户协议');
|
||||
@@ -140,6 +178,11 @@ export default function LoginPage() {
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
persistRememberAccount(phone);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindPartnerWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
await finishLoginNavigate();
|
||||
} catch (e) {
|
||||
setMsg(formatPartnerError(e));
|
||||
@@ -148,6 +191,116 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg(WECHAT_INAPP_REQUIRED_MSG);
|
||||
return;
|
||||
}
|
||||
const canUseWechat = await canPartnerUseWechatLogin({
|
||||
profile: savedProfile,
|
||||
phone,
|
||||
});
|
||||
if (!canUseWechat) {
|
||||
setMsg(PARTNER_WECHAT_LOGIN_HINT);
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
const session = await loginPartnerWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
await finishLoginNavigate();
|
||||
}
|
||||
} catch (e) {
|
||||
setMsg(formatWechatError(e));
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick =
|
||||
wxAuthorize &&
|
||||
isWechatEnv() &&
|
||||
hasPartnerWxSession() &&
|
||||
!!savedProfile &&
|
||||
savedProfile.hasWechat === true;
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page partner-auth-page--quick">
|
||||
<header className="partner-auth-brand">
|
||||
<div className="partner-quick-avatar" style={{ width: 120, height: 120, margin: '0 auto 16px' }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 48 }}>wine_bar</span>
|
||||
</div>
|
||||
<h1 className="partner-auth-title" style={{ fontSize: 20 }}>杜康好客</h1>
|
||||
<p className="partner-auth-subtitle" style={{ fontSize: 12, letterSpacing: '0.2em', textTransform: 'uppercase' }}>城市合伙人端</p>
|
||||
</header>
|
||||
|
||||
<section className="partner-glass-card">
|
||||
<div className="partner-quick-badge">已识别账号</div>
|
||||
<div className="partner-quick-avatar">
|
||||
<span className="material-symbols-outlined">person</span>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<h2 className="headline-md">
|
||||
{quickName}
|
||||
{quickCompany ? (
|
||||
<span className="text-muted body-md" style={{ fontWeight: 400 }}> ({quickCompany})</span>
|
||||
) : null}
|
||||
</h2>
|
||||
<p className="text-muted body-md" style={{ letterSpacing: '0.1em', marginTop: 4 }}>
|
||||
{quickPhone ? maskPhone(quickPhone) : '暂无已保存账号'}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<nav style={{ width: '100%', maxWidth: 384, marginTop: 16 }}>
|
||||
{msg && <p className="partner-auth-msg" style={{ color: 'var(--color-error, #d33)', fontSize: 13, textAlign: 'center', marginBottom: 12 }}>{msg}</p>}
|
||||
<AgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
inputRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center', marginTop: 12, marginBottom: 12 }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="partner-btn-primary" style={{ display: 'block', textAlign: 'center', textDecoration: 'none', marginTop: 12 }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<Link to="/login" className="partner-btn-ghost" style={{ display: 'block', marginTop: 12 }}>切换账号</Link>
|
||||
</nav>
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
<span className="label-md" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
|
||||
{canWechatQuick ? '微信验证 · 7 天内免登录' : 'Secured by Dukang Heritage'}
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page">
|
||||
<div className="partner-auth-brand">
|
||||
@@ -214,12 +367,29 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="partner-auth-divider"><span>其他登录方式</span></div>
|
||||
<button type="button" className="partner-btn-wechat" onClick={() => void wechatLogin()} disabled={wxLoading}>
|
||||
<svg viewBox="0 0 24 24" fill="#07C160" aria-hidden>
|
||||
<path d="M8.25 4.5C4.52 4.5 1.5 7.04 1.5 10.17c0 1.78.98 3.37 2.5 4.48l-.63 1.88 2.19-1.09c.84.24 1.74.38 2.69.38.25 0 .5 0 .75-.03-.16-.53-.25-1.09-.25-1.66 0-3.13 3.02-5.67 6.75-5.67.57 0 1.13.06 1.66.17C15.17 6.13 12 4.5 8.25 4.5zm10.5 6.33c-3.11 0-5.62 2.12-5.62 4.73 0 2.61 2.51 4.73 5.62 4.73.79 0 1.54-.14 2.24-.38l1.83.91-.53-1.57c1.27-.92 2.08-2.25 2.08-3.73 0-2.61-2.51-4.73-5.62-4.73z" />
|
||||
</svg>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center' }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
手机号验证成功后,7 天内无需再次输入验证码;微信内登录将自动关联微信
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{hasPartnerWxSession() && savedProfile?.hasWechat && (
|
||||
<Link to="/login?quick=1" className="partner-link">微信快捷登录</Link>
|
||||
)}
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
|
||||
@@ -3,6 +3,12 @@ import { useNavigate, useParams } from 'react-router-dom';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import type { PartnerProxyOrderListItem } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderPayLabel,
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
@@ -21,14 +27,30 @@ function deliveryLabel(order: PartnerProxyOrderListItem) {
|
||||
if (t === 'ON_SITE_PICKUP') return '现场提货';
|
||||
if (t === 'CROSS_CITY') return '跨城配送';
|
||||
if (t === 'LOCAL') return '同城配送';
|
||||
return '线下代下单';
|
||||
return '代下单';
|
||||
}
|
||||
|
||||
type TrackNode = {
|
||||
time?: string;
|
||||
status?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
type TrackResult = {
|
||||
nodes?: TrackNode[];
|
||||
trackingNo?: string | null;
|
||||
provider?: string | null;
|
||||
manualQueryUrl?: string | null;
|
||||
};
|
||||
|
||||
export default function ProxyOrderDetailPage() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [order, setOrder] = useState<PartnerProxyOrderListItem | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [track, setTrack] = useState<TrackResult | null>(null);
|
||||
const [trackError, setTrackError] = useState('');
|
||||
const [paying, setPaying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = '代下单详情';
|
||||
@@ -41,7 +63,42 @@ export default function ProxyOrderDetailPage() {
|
||||
.catch((e) => setError(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !order) return;
|
||||
const dt = String(order.deliveryType || '').toUpperCase();
|
||||
if (dt === 'ON_SITE_PICKUP' || order.payStatus !== 'PAID') {
|
||||
setTrack(null);
|
||||
return;
|
||||
}
|
||||
void request<TrackResult>('PARTNER_H5', `/partner/proxy-orders/${id}/track`, { silent: true })
|
||||
.then(setTrack)
|
||||
.catch((e) => setTrackError(e instanceof Error ? e.message : '物流暂不可用'));
|
||||
}, [id, order]);
|
||||
|
||||
async function continuePay() {
|
||||
if (!id) return;
|
||||
setPaying(true);
|
||||
try {
|
||||
await request('PARTNER_H5', `/partner/proxy-orders/${id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
silent: true,
|
||||
});
|
||||
toastSuccess('支付成功');
|
||||
const refreshed = await request<PartnerProxyOrderListItem>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${id}`,
|
||||
);
|
||||
setOrder(refreshed);
|
||||
} catch (e) {
|
||||
toastError(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const img = order?.imageResource?.url || '';
|
||||
const isOnSite = String(order?.deliveryType || '').toUpperCase() === 'ON_SITE_PICKUP';
|
||||
|
||||
return (
|
||||
<div className="page-no-tab partner-orders-page">
|
||||
@@ -60,8 +117,11 @@ export default function ProxyOrderDetailPage() {
|
||||
<div className="partner-order-card" style={{ pointerEvents: 'none' }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {order.orderNo}</span>
|
||||
<span className="label-md" style={{ color: 'var(--color-success-green)', fontWeight: 600 }}>
|
||||
已完成
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(order.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(order.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
@@ -99,7 +159,7 @@ export default function ProxyOrderDetailPage() {
|
||||
<p className="body-md">姓名:{order.receiverName || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>手机:{order.receiverPhone || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
地址:{order.receiverAddress || (String(order.deliveryType).toUpperCase() === 'ON_SITE_PICKUP' ? '现场提货' : '—')}
|
||||
地址:{order.receiverAddress || (isOnSite ? '现场提货' : '—')}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -107,9 +167,64 @@ export default function ProxyOrderDetailPage() {
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>订单信息</h3>
|
||||
<p className="body-md">配送方式:{deliveryLabel(order)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>下单时间:{fmtTime(order.createdAt)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>支付状态:已付款(线下)</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>订单状态:已完成并发放权益</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
支付状态:{proxyOrderPayLabel(order.payStatus)}
|
||||
</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
订单状态:{proxyOrderStatusLabel(order.status)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{order.payStatus === 'UNPAID' || order.status === 'PENDING_PAY' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={paying}
|
||||
onClick={() => void continuePay()}
|
||||
>
|
||||
{paying ? '处理中…' : '继续支付(模拟)'}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{!isOnSite && order.payStatus === 'PAID' ? (
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>物流信息</h3>
|
||||
{trackError ? (
|
||||
<p className="label-md text-muted">{trackError}</p>
|
||||
) : !track ? (
|
||||
<p className="label-md text-muted">加载物流…</p>
|
||||
) : (
|
||||
<>
|
||||
{track.trackingNo ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
运单号:{track.trackingNo}
|
||||
{track.provider ? `(${track.provider})` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
{track.manualQueryUrl ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
<a href={track.manualQueryUrl} target="_blank" rel="noreferrer">
|
||||
查看物流官网
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
{(track.nodes ?? []).length === 0 ? (
|
||||
<p className="label-md text-muted">暂无物流轨迹(待总部发货后更新)</p>
|
||||
) : (
|
||||
<ul style={{ paddingLeft: 18, margin: 0 }}>
|
||||
{(track.nodes ?? []).map((n, i) => (
|
||||
<li key={`${n.time}-${i}`} className="body-md" style={{ marginBottom: 8 }}>
|
||||
<div className="label-md text-muted">{fmtTime(n.time)}</div>
|
||||
<div>{n.description || n.status || '—'}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,10 @@ import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import type { PartnerProxyOrderListItem, PartnerProxyOrderListResponse } from '@dukang/shared-types';
|
||||
import { isLoggedIn, request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
@@ -98,8 +102,11 @@ export default function ProxyOrderListPage() {
|
||||
<Link key={orderId} to={`/center/proxy-orders/${orderId}`} className="partner-order-card" style={{ marginBottom: 12 }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {o.orderNo}</span>
|
||||
<span className="label-md" style={{ color: 'var(--color-success-green)', fontWeight: 600 }}>
|
||||
已完成
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(o.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(o.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
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 ChinaRegionPicker from '../components/ChinaRegionPicker';
|
||||
import { request } from '../lib/api';
|
||||
import { getToken, request } from '../lib/api';
|
||||
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
||||
import {
|
||||
clearProxyOrderDraft,
|
||||
@@ -11,11 +13,16 @@ import {
|
||||
type ProxyOrderDraft,
|
||||
} from '../lib/proxyOrderDraft';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { fetchPartnerProfile, partnerHasWechatBinding } from '../lib/wechat-auth';
|
||||
import type {
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderCreateRequest,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
ProxyPayMethod,
|
||||
} from '@dukang/shared-types';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
@@ -57,10 +64,34 @@ export default function ProxyOrderPage() {
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [payMethod, setPayMethod] = useState<ProxyPayMethod>('NATIVE');
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
const [paying, setPaying] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
const regionLabel = region ? formatRegionLabel(region) : '';
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!codeUrl) {
|
||||
setQrDataUrl(null);
|
||||
return;
|
||||
}
|
||||
void QRCode.toDataURL(codeUrl, { width: 220, margin: 1 }).then(setQrDataUrl).catch(() => setQrDataUrl(null));
|
||||
}, [codeUrl]);
|
||||
|
||||
function persistDraft(overrides?: Partial<ProxyOrderDraft>) {
|
||||
saveProxyOrderDraft({
|
||||
phone,
|
||||
@@ -157,6 +188,82 @@ export default function ProxyOrderPage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<{ payStatus: string; orderNo: string }>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay-status`,
|
||||
{ silent: true },
|
||||
)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
toastSuccess(`支付成功:${st.orderNo}`);
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function startPay(orderId: string, method: ProxyPayMethod) {
|
||||
setPaying(true);
|
||||
setMsg('');
|
||||
try {
|
||||
if (method === 'JSAPI') {
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开合伙人端以使用微信代付');
|
||||
}
|
||||
const profile = await fetchPartnerProfile();
|
||||
if (!partnerHasWechatBinding(profile)) {
|
||||
throw new Error('请先绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const pay = await request<ProxyOrderPayResponse>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: method }),
|
||||
silent: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (pay.mode === 'mock') {
|
||||
toastSuccess('支付成功');
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'native' && pay.codeUrl) {
|
||||
setCodeUrl(pay.codeUrl);
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'jsapi' && pay.prepay) {
|
||||
await invokeWechatPay(pay.prepay, {
|
||||
apiBase: '/api/v1',
|
||||
clientApp: 'PARTNER_H5',
|
||||
getAccessToken: getToken,
|
||||
platform: 'wechat-h5',
|
||||
});
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('支付发起失败');
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
setMsg('');
|
||||
const err = validateForm();
|
||||
@@ -181,14 +288,16 @@ export default function ProxyOrderPage() {
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<{ id: string; orderNo: string }>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
const order = await request<ProxyOrderCreateResponse>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
silent: true,
|
||||
});
|
||||
toastSuccess(`代下单成功:${order.orderNo}`);
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${order.id}`);
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setCodeUrl(null);
|
||||
await startPay(order.id, payMethod);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '下单失败');
|
||||
} finally {
|
||||
@@ -196,6 +305,25 @@ export default function ProxyOrderPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMockConfirm() {
|
||||
if (!created) return;
|
||||
setPaying(true);
|
||||
try {
|
||||
await request('PARTNER_H5', `/partner/proxy-orders/${created.id}/pay/mock-confirm`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
silent: true,
|
||||
});
|
||||
stopPoll();
|
||||
toastSuccess('支付成功');
|
||||
navigate(`/center/proxy-orders/${created.id}`, { replace: true });
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '模拟支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const deliveryLabel =
|
||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||
@@ -206,10 +334,97 @@ export default function ProxyOrderPage() {
|
||||
|
||||
return (
|
||||
<div className="page partner-proxy-order-page">
|
||||
<PageHeader title="代下单" onBack={() => navigate(-1)} />
|
||||
<PageHeader title={step === 'pay' ? '代下单支付' : '代下单'} onBack={() => navigate(-1)} />
|
||||
|
||||
<main className="partner-form-card" style={{ margin: '0 16px 24px' }}>
|
||||
{loadingOptions ? (
|
||||
{step === 'pay' && created ? (
|
||||
<>
|
||||
<p className="body-md">
|
||||
订单 {created.orderNo} · 应付 ¥{fmtMoney(created.payAmount)}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
{created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付成功后进入现场提货闭环'
|
||||
: '支付成功后进入待发货,由总部履约'}
|
||||
</p>
|
||||
|
||||
<section className="partner-form-section" style={{ marginTop: 16 }}>
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('NATIVE');
|
||||
void startPay(created.id, 'NATIVE');
|
||||
}}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('JSAPI');
|
||||
void startPay(created.id, 'JSAPI');
|
||||
}}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{payMethod === 'NATIVE' ? (
|
||||
<div style={{ textAlign: 'center', marginTop: 16 }}>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt="收款码" width={220} height={220} style={{ margin: '0 auto' }} />
|
||||
) : (
|
||||
<p className="label-md text-muted">{paying ? '生成收款码中…' : '暂无收款码'}</p>
|
||||
)}
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
请使用微信扫码支付
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={paying}
|
||||
onClick={() => void handleMockConfirm()}
|
||||
>
|
||||
{paying ? '处理中…' : '模拟支付成功'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<p className="label-md text-muted">将调起微信支付(本地 Mock 可能直接入账)</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 12 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay(created.id, 'JSAPI')}
|
||||
>
|
||||
{paying ? '支付中…' : '重新调起微信代付'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block"
|
||||
style={{ marginTop: 8 }}
|
||||
disabled={paying}
|
||||
onClick={() => void handleMockConfirm()}
|
||||
>
|
||||
模拟支付成功
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{msg ? (
|
||||
<p className="partner-form-error" role="alert" style={{ marginTop: 12 }}>
|
||||
{msg}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : loadingOptions ? (
|
||||
<p className="label-md text-muted">加载商品…</p>
|
||||
) : (
|
||||
<>
|
||||
@@ -350,11 +565,36 @@ export default function ProxyOrderPage() {
|
||||
checked={autoReceive}
|
||||
onChange={(e) => setAutoReceive(e.target.checked)}
|
||||
/>
|
||||
<span>同意自动收货(线下代下单提交后视为已送达并发放权益)</span>
|
||||
<span>同意自动收货(配送到址必选)</span>
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('NATIVE')}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('JSAPI')}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8, lineHeight: 1.5 }}>
|
||||
{payMethod === 'NATIVE'
|
||||
? '提交后展示商家收款码,客户或现场扫码支付'
|
||||
: '提交后在微信内由您代客户完成支付(需已绑定微信)'}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="partner-proxy-fee-card">
|
||||
<h3 className="headline-md">费用明细</h3>
|
||||
{previewLoading ? (
|
||||
@@ -398,15 +638,15 @@ export default function ProxyOrderPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
disabled={submitting || !preview}
|
||||
disabled={submitting || paying || !preview}
|
||||
onClick={() => void submit()}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
{submitting ? '提交中…' : '确认代下单'}
|
||||
{submitting || paying ? '处理中…' : '提交并支付'}
|
||||
</button>
|
||||
|
||||
<p className="label-md text-muted" style={{ marginTop: 12, lineHeight: 1.5 }}>
|
||||
确认线下已收款后提交:将自动创建/关联用户,订单标记为代下单并直接完成,同时发放对应权益。客户订单列表会显示您的姓名。
|
||||
提交后进入在线支付;支付成功后发放权益。配送单将进入待发货由总部履约,现场提货走自提闭环。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getStoreProfile, hasShopWxSession } from '../lib/api';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
|
||||
const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
|
||||
@@ -25,6 +26,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getStoreProfile();
|
||||
if (profile && hasShopWxSession() && location.pathname !== '/login') {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import {
|
||||
clearAuth,
|
||||
ensureSession,
|
||||
@@ -14,6 +16,12 @@ import {
|
||||
type ShopSessionPayload,
|
||||
type StoreSessionStore,
|
||||
} from '../lib/api';
|
||||
import {
|
||||
fetchClientConfig,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
type StoreSessionContextValue = {
|
||||
ready: boolean;
|
||||
@@ -26,6 +34,12 @@ type StoreSessionContextValue = {
|
||||
|
||||
const StoreSessionContext = createContext<StoreSessionContextValue | null>(null);
|
||||
|
||||
function deriveSelectStore(session: ShopSessionPayload, nextStore: StoreSessionStore | null) {
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
return stores.length > 1 && !storeId;
|
||||
}
|
||||
|
||||
export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [authenticated, setAuthenticated] = useState(false);
|
||||
@@ -43,9 +57,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
: null;
|
||||
setStore(nextStore);
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
setNeedsSelectStore(stores.length > 1 && !storeId);
|
||||
setNeedsSelectStore(deriveSelectStore(session, nextStore));
|
||||
}, []);
|
||||
|
||||
const resetSession = useCallback(() => {
|
||||
@@ -59,6 +71,23 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (isWechatEnv() && params.get('code')) {
|
||||
try {
|
||||
const config = await fetchClientConfig();
|
||||
if (isWxAuthorizeEnabled(config)) {
|
||||
const result = await handleShopWechatCallback();
|
||||
if (result && !cancelled) {
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) applySession(session);
|
||||
}
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
} catch {
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await ensureSession();
|
||||
if (cancelled) return;
|
||||
setAuthenticated(result.authenticated);
|
||||
@@ -73,7 +102,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [resetSession]);
|
||||
}, [applySession, resetSession]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ ready, authenticated, needsSelectStore, store, applySession, resetSession }),
|
||||
|
||||
@@ -1,14 +1,39 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import AppImage from '@dukang/shared-ui/AppImage';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
import {
|
||||
getLastPhone,
|
||||
getStoreProfile,
|
||||
hasShopWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type ShopSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { routeAfterShopLogin } from './SelectStorePage';
|
||||
import {
|
||||
bindShopWechatAfterSmsLogin,
|
||||
fetchClientConfig,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
loginShopWithWechat,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定门店账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function ShopAgreementCheckbox({
|
||||
agreed,
|
||||
@@ -43,14 +68,44 @@ function ShopAgreementCheckbox({
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession } = useStoreSession();
|
||||
const [params, setSearchParams] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getStoreProfile();
|
||||
const [phone, setPhone] = useState(getLastPhone());
|
||||
const [code, setCode] = useState('');
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||
void handleShopWechatCallback()
|
||||
.then((result) => {
|
||||
if (!result) return;
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) {
|
||||
applySession(session);
|
||||
stripOAuthParamsFromLocation();
|
||||
setSearchParams({}, { replace: true });
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
})
|
||||
.catch((e) => setMsg(formatWechatError(e)));
|
||||
}, [applySession, navigate, params, setSearchParams, wxAuthorize]);
|
||||
|
||||
const quickStoreName = savedProfile?.storeName ?? '门店管理中心';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先阅读并同意用户协议');
|
||||
@@ -95,6 +150,11 @@ export default function LoginPage() {
|
||||
});
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindShopWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
routeAfterShopLogin(data, navigate);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '登录失败');
|
||||
@@ -103,6 +163,103 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg('请在微信内打开以使用微信一键登录');
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
const session = await loginShopWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
} catch (e) {
|
||||
setMsg(formatWechatError(e));
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick = wxAuthorize && isWechatEnv() && hasShopWxSession() && !!savedProfile;
|
||||
|
||||
return (
|
||||
<div className="shop-quick-login-page">
|
||||
<header className="shop-quick-header">
|
||||
<AppImage src="/logo.png" alt="杜康好客" wrapperClassName="shop-quick-logo" fit="contain" />
|
||||
<h1 className="shop-quick-welcome">欢迎回来</h1>
|
||||
<div className="shop-quick-welcome-line" />
|
||||
</header>
|
||||
|
||||
<section className="shop-quick-store-card">
|
||||
<div className="shop-quick-store-inner">
|
||||
<div className="shop-quick-store-icon">
|
||||
<span className="material-symbols-outlined shop-fill-icon">storefront</span>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="shop-quick-store-name">{quickStoreName}</h2>
|
||||
<p className="shop-quick-store-phone">{maskPhone(quickPhone)}</p>
|
||||
</div>
|
||||
<span className="shop-quick-verified">
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 14 }}>verified_user</span>
|
||||
认证门店
|
||||
</span>
|
||||
<div className="shop-quick-switch">
|
||||
<Link to="/login">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>sync</span>
|
||||
切换账号
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="shop-quick-actions">
|
||||
{msg && <p className="shop-login-msg">{msg}</p>}
|
||||
<ShopAgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
labelRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shop-quick-login-btn shop-quick-login-btn--wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center' }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="shop-quick-login-btn" style={{ textAlign: 'center', textDecoration: 'none' }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<div className="shop-quick-secure">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 16 }}>lock</span>
|
||||
<span>{canWechatQuick ? '微信验证 · 7 天内免登录' : '加密环境安全登录中'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="shop-quick-footer">
|
||||
<p className="shop-login-footer-brand">SECURED BY DUKANG HERITAGE</p>
|
||||
<p style={{ fontSize: 10, fontFamily: 'var(--font-label)' }}>© 2024 杜康酒业门店管理系统</p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="shop-login-page">
|
||||
<header className="shop-login-hero">
|
||||
@@ -172,8 +329,29 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="shop-login-divider">
|
||||
<span className="shop-login-divider-line" />
|
||||
<span className="shop-login-divider-text">或者</span>
|
||||
<span className="shop-login-divider-line" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="shop-login-wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center', marginTop: 12 }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
手机号验证成功后,7 天内无需再次输入验证码;微信内登录将自动关联微信
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
@@ -183,6 +361,11 @@ export default function LoginPage() {
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ opacity: 0.3, fontSize: 20, color: 'var(--color-outline)' }}>
|
||||
security
|
||||
</span>
|
||||
{hasShopWxSession() && savedProfile && (
|
||||
<p style={{ marginTop: 16, textAlign: 'center' }}>
|
||||
<Link to="/login?quick=1" className="text-primary body-md">微信快捷登录</Link>
|
||||
</p>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -13,6 +13,8 @@ server {
|
||||
default_type "text/plain";
|
||||
}
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
@@ -55,6 +57,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
@@ -91,6 +95,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
@@ -127,6 +133,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang-staging/deploy/nginx-mp-verify-staging.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8190;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -9,6 +9,8 @@ server {
|
||||
default_type "text/plain";
|
||||
}
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
@@ -53,6 +55,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
@@ -89,6 +93,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
@@ -125,6 +131,8 @@ server {
|
||||
|
||||
client_max_body_size 50m;
|
||||
|
||||
include /opt/dukang/deploy/nginx-mp-verify.conf;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8090;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# 微信 JS 安全域名校验文件(Staging)
|
||||
# 文件放在 /opt/dukang-staging/public/MP_verify_*.txt
|
||||
location ~ ^/MP_verify_.*\.txt$ {
|
||||
root /opt/dukang-staging/public;
|
||||
default_type text/plain;
|
||||
charset utf-8;
|
||||
access_log off;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# 微信 JS 安全域名校验文件(根目录直出,勿走 SPA)
|
||||
# 文件放在 /opt/dukang/public/MP_verify_*.txt
|
||||
location ~ ^/MP_verify_.*\.txt$ {
|
||||
root /opt/dukang/public;
|
||||
default_type text/plain;
|
||||
charset utf-8;
|
||||
access_log off;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { WechatJsapiPrepayParams } from './wechat';
|
||||
|
||||
export interface OrderDto {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
@@ -27,11 +29,41 @@ export interface OrderPreviewResult {
|
||||
deliveryType: 'LOCAL' | 'CROSS_CITY';
|
||||
}
|
||||
|
||||
export type ProxyPayMethod = 'NATIVE' | 'JSAPI';
|
||||
|
||||
export interface PayOrderResult {
|
||||
mode?: 'jsapi' | 'mock';
|
||||
mode?: 'jsapi' | 'mock' | 'native';
|
||||
orderId?: string;
|
||||
codeUrl?: string;
|
||||
prepay?: WechatJsapiPrepayParams;
|
||||
payExpireAt?: string | null;
|
||||
}
|
||||
|
||||
export type ProxyOrderPayRequest = {
|
||||
payMethod: ProxyPayMethod;
|
||||
};
|
||||
|
||||
export type ProxyOrderPayResponse = {
|
||||
mode: 'jsapi' | 'mock' | 'native';
|
||||
orderId: string;
|
||||
orderNo?: string;
|
||||
codeUrl?: string;
|
||||
prepay?: WechatJsapiPrepayParams;
|
||||
payExpireAt?: string | null;
|
||||
};
|
||||
|
||||
export type ProxyOrderCreateResponse = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payStatus: string;
|
||||
payAmount: number;
|
||||
benefitAmount: number;
|
||||
deliveryType: string;
|
||||
payExpireAt: string | null;
|
||||
proxyPartnerName?: string | null;
|
||||
};
|
||||
|
||||
export interface DeliveryDto {
|
||||
provider?: string;
|
||||
shippingAt?: string;
|
||||
@@ -127,7 +159,7 @@ export type PartnerProxyOrderListResponse = {
|
||||
pageSize: number;
|
||||
};
|
||||
|
||||
/** 总部代下单(线下完成发权益,无需短信验证) */
|
||||
/** 总部代下单(在线支付后发权益) */
|
||||
export type HqProxyOrderCreateRequest = {
|
||||
phone: string;
|
||||
deliveryMode: PartnerProxyDeliveryMode;
|
||||
|
||||
Generated
+50
@@ -35,6 +35,12 @@ importers:
|
||||
dayjs:
|
||||
specifier: ^1.11.13
|
||||
version: 1.11.21
|
||||
echarts:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
echarts-for-react:
|
||||
specifier: ^3.0.6
|
||||
version: 3.0.6(echarts@6.1.0)(react@18.3.1)
|
||||
element-china-area-data:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
@@ -78,6 +84,9 @@ importers:
|
||||
element-china-area-data:
|
||||
specifier: ^6.1.0
|
||||
version: 6.1.0
|
||||
qrcode:
|
||||
specifier: ^1.5.4
|
||||
version: 1.5.4
|
||||
react:
|
||||
specifier: ^18.3.1
|
||||
version: 18.3.1
|
||||
@@ -88,6 +97,9 @@ importers:
|
||||
specifier: ^6.26.0
|
||||
version: 6.30.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
devDependencies:
|
||||
'@types/qrcode':
|
||||
specifier: ^1.5.6
|
||||
version: 1.5.6
|
||||
'@types/react':
|
||||
specifier: ^18.3.3
|
||||
version: 18.3.31
|
||||
@@ -3579,6 +3591,15 @@ packages:
|
||||
ecdsa-sig-formatter@1.0.11:
|
||||
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
|
||||
|
||||
echarts-for-react@3.0.6:
|
||||
resolution: {integrity: sha512-4zqLgTGWS3JvkQDXjzkR1k1CHRdpd6by0988TWMJgnvDytegWLbeP/VNZmMa+0VJx2eD7Y632bi2JquXDgiGJg==}
|
||||
peerDependencies:
|
||||
echarts: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0
|
||||
react: ^15.0.0 || >=16.0.0
|
||||
|
||||
echarts@6.1.0:
|
||||
resolution: {integrity: sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==}
|
||||
|
||||
ee-first@1.1.1:
|
||||
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
|
||||
|
||||
@@ -5835,6 +5856,9 @@ packages:
|
||||
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
size-sensor@1.0.3:
|
||||
resolution: {integrity: sha512-+k9mJ2/rQMiRmQUcjn+qznch260leIXY8r4FyYKKyRBO/s5UoeMAHGkCJyE1R/4wrIhTJONfyloY55SkE7ve3A==}
|
||||
|
||||
slash@3.0.0:
|
||||
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -6189,6 +6213,9 @@ packages:
|
||||
tslib@1.14.1:
|
||||
resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
|
||||
|
||||
tslib@2.3.0:
|
||||
resolution: {integrity: sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==}
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
@@ -6597,6 +6624,9 @@ packages:
|
||||
yup@1.7.1:
|
||||
resolution: {integrity: sha512-GKHFX2nXul2/4Dtfxhozv701jLQHdf6J34YDh2cEkpqoo8le5Mg6/LrdseVLrFarmFygZTlfIhHx/QKfb/QWXw==}
|
||||
|
||||
zrender@6.1.0:
|
||||
resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@alicloud/credentials@2.4.5':
|
||||
@@ -10333,6 +10363,18 @@ snapshots:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
echarts-for-react@3.0.6(echarts@6.1.0)(react@18.3.1):
|
||||
dependencies:
|
||||
echarts: 6.1.0
|
||||
fast-deep-equal: 3.1.3
|
||||
react: 18.3.1
|
||||
size-sensor: 1.0.3
|
||||
|
||||
echarts@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
zrender: 6.1.0
|
||||
|
||||
ee-first@1.1.1: {}
|
||||
|
||||
electron-to-chromium@1.5.380: {}
|
||||
@@ -12806,6 +12848,8 @@ snapshots:
|
||||
|
||||
signal-exit@4.1.0: {}
|
||||
|
||||
size-sensor@1.0.3: {}
|
||||
|
||||
slash@3.0.0: {}
|
||||
|
||||
slice-ansi@4.0.0:
|
||||
@@ -13170,6 +13214,8 @@ snapshots:
|
||||
|
||||
tslib@1.14.1: {}
|
||||
|
||||
tslib@2.3.0: {}
|
||||
|
||||
tslib@2.8.1: {}
|
||||
|
||||
tunnel-agent@0.6.0:
|
||||
@@ -13665,3 +13711,7 @@ snapshots:
|
||||
tiny-case: 1.0.3
|
||||
toposort: 2.0.2
|
||||
type-fest: 2.19.0
|
||||
|
||||
zrender@6.1.0:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"prisma:validate": "prisma validate",
|
||||
"prisma:seed": "ts-node --transpile-only prisma/seed-v31.ts",
|
||||
"prisma:seed-finance": "ts-node --transpile-only prisma/seed-finance-mock.ts",
|
||||
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
||||
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
||||
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
||||
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
/**
|
||||
* 概览页统计 Mock(用户/订单/合伙人/门店/核销,幂等可重复跑)
|
||||
* 用法:cd server/dukang-api && pnpm prisma:seed-stats
|
||||
*/
|
||||
import { PrismaClient, type OrderStatus, type PayStatus } from '@prisma/client';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const USER_PREFIX = 'STAT';
|
||||
const ORDER_PREFIX = 'STAT';
|
||||
const COUPON_PREFIX = 'STATCPN';
|
||||
const REDEEM_PREFIX = 'STATRD';
|
||||
const STORE_NAME_PREFIX = 'STAT门店';
|
||||
const PARTNER_PHONE_PREFIX = '13788';
|
||||
|
||||
const PROMO_CODES = [
|
||||
{ code: 'STAT_A', name: '统计演示·品鉴会A', scene: 'EVENT' as const },
|
||||
{ code: 'STAT_B', name: '统计演示·线下提货B', scene: 'OFFLINE_PICKUP' as const },
|
||||
{ code: 'STAT_C', name: '统计演示·线上渠道C', scene: 'ONLINE_LINK' as const },
|
||||
];
|
||||
|
||||
const CITY_DEFS = [
|
||||
{ code: '410100', name: '郑州市', province: '河南省', district: '金水区' },
|
||||
{ code: '410300', name: '洛阳市', province: '河南省', district: '涧西区' },
|
||||
];
|
||||
|
||||
function startOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function qrcodeIdFor(code: string) {
|
||||
return createHash('sha256').update(`stats-mock:${code}`).digest('hex');
|
||||
}
|
||||
|
||||
function mulberry32(seed: number) {
|
||||
return () => {
|
||||
let t = (seed += 0x6d2b79f5);
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
async function cleanup() {
|
||||
console.log('Cleaning previous STAT* mock...');
|
||||
|
||||
const redeemIds = (
|
||||
await prisma.redeemRecord.findMany({
|
||||
where: { redeemNo: { startsWith: REDEEM_PREFIX } },
|
||||
select: { id: true },
|
||||
})
|
||||
).map((r) => r.id);
|
||||
if (redeemIds.length) {
|
||||
await prisma.redeemRecordAllocation.deleteMany({
|
||||
where: { redeemRecordId: { in: redeemIds } },
|
||||
});
|
||||
await prisma.storeRating.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await prisma.storePayout.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await prisma.redeemPendingRecord.deleteMany({
|
||||
where: { redeemRecordId: { in: redeemIds } },
|
||||
});
|
||||
await prisma.redeemRecord.deleteMany({ where: { id: { in: redeemIds } } });
|
||||
}
|
||||
|
||||
await prisma.benefitCoupon.deleteMany({
|
||||
where: { couponNo: { startsWith: COUPON_PREFIX } },
|
||||
});
|
||||
|
||||
const statOrders = await prisma.order.findMany({
|
||||
where: { orderNo: { startsWith: ORDER_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const orderIds = statOrders.map((o) => o.id);
|
||||
if (orderIds.length) {
|
||||
await prisma.benefitCoupon.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.orderDelivery.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.userInvoice.deleteMany({ where: { orderId: { in: orderIds } } });
|
||||
await prisma.order.deleteMany({ where: { id: { in: orderIds } } });
|
||||
}
|
||||
|
||||
const statUsers = await prisma.user.findMany({
|
||||
where: { userNo: { startsWith: USER_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const userIds = statUsers.map((u) => u.id);
|
||||
if (userIds.length) {
|
||||
await prisma.userPromoAttribution.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.userCityPreference.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.userAddress.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.benefitCoupon.deleteMany({ where: { userId: { in: userIds } } });
|
||||
await prisma.user.deleteMany({ where: { id: { in: userIds } } });
|
||||
}
|
||||
|
||||
await prisma.commonPromoCode.deleteMany({
|
||||
where: { code: { in: PROMO_CODES.map((p) => p.code) } },
|
||||
});
|
||||
|
||||
const statStores = await prisma.store.findMany({
|
||||
where: { name: { startsWith: STORE_NAME_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const storeIds = statStores.map((s) => s.id);
|
||||
if (storeIds.length) {
|
||||
await prisma.storeAccountStore.deleteMany({ where: { storeId: { in: storeIds } } });
|
||||
await prisma.storeBill.deleteMany({ where: { storeId: { in: storeIds } } });
|
||||
await prisma.store.deleteMany({ where: { id: { in: storeIds } } });
|
||||
}
|
||||
|
||||
const statPartners = await prisma.partnerAccount.findMany({
|
||||
where: { phone: { startsWith: PARTNER_PHONE_PREFIX } },
|
||||
select: { id: true },
|
||||
});
|
||||
const partnerIds = statPartners.map((p) => p.id);
|
||||
if (partnerIds.length) {
|
||||
await prisma.partnerBill.deleteMany({ where: { partnerAccountId: { in: partnerIds } } });
|
||||
await prisma.partnerAccount.deleteMany({
|
||||
where: { OR: [{ id: { in: partnerIds } }, { parentAccountId: { in: partnerIds } }] },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureCities() {
|
||||
const cities = [];
|
||||
for (const def of CITY_DEFS) {
|
||||
const city = await prisma.commonCity.upsert({
|
||||
where: { code: def.code },
|
||||
create: {
|
||||
code: def.code,
|
||||
name: def.name,
|
||||
province: def.province,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
update: {
|
||||
name: def.name,
|
||||
province: def.province,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
});
|
||||
cities.push({ ...city, district: def.district });
|
||||
}
|
||||
return cities;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Seeding stats mock (users/orders/partners/stores/redeems)...');
|
||||
await cleanup();
|
||||
|
||||
const cities = await ensureCities();
|
||||
const product = await prisma.commonProductItem.findFirst({
|
||||
orderBy: { id: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
barcode69: true,
|
||||
name: true,
|
||||
spec: true,
|
||||
price: true,
|
||||
},
|
||||
});
|
||||
if (!product) throw new Error('没有商品,请先 pnpm prisma:seed');
|
||||
|
||||
const category = await prisma.commonStoreCategory.findFirst({ orderBy: { id: 'asc' } });
|
||||
|
||||
const promos = [];
|
||||
for (const def of PROMO_CODES) {
|
||||
const promo = await prisma.commonPromoCode.create({
|
||||
data: {
|
||||
code: def.code,
|
||||
name: def.name,
|
||||
scene: def.scene,
|
||||
qrcodeId: qrcodeIdFor(def.code),
|
||||
status: 'ACTIVE',
|
||||
scanCount: 0,
|
||||
orderCount: 0,
|
||||
},
|
||||
});
|
||||
promos.push(promo);
|
||||
}
|
||||
|
||||
const rand = mulberry32(20260731);
|
||||
const today = startOfDay(new Date());
|
||||
|
||||
// ── 城市合伙人 + 门店(近 30 天分散创建) ──
|
||||
const createdPartners: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
city: (typeof cities)[0];
|
||||
}> = [];
|
||||
const createdStores: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
partnerAccountId: bigint;
|
||||
settlementRate: number;
|
||||
}> = [];
|
||||
|
||||
for (let i = 0; i < cities.length; i++) {
|
||||
const city = cities[i];
|
||||
// 每城 2 个主合伙人
|
||||
for (let j = 0; j < 2; j++) {
|
||||
const dayOffset = Math.floor(rand() * 28);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(9, 0, 0, 0);
|
||||
const phone = `${PARTNER_PHONE_PREFIX}${String(i * 10 + j + 1).padStart(5, '0')}`;
|
||||
const partner = await prisma.partnerAccount.create({
|
||||
data: {
|
||||
phone,
|
||||
name: `${city.name}统计合伙人${j + 1}`,
|
||||
companyName: `STAT${city.name}合伙人${j + 1}`,
|
||||
isPrimary: 1,
|
||||
status: 'ACTIVE',
|
||||
cityId: city.id,
|
||||
scopeType: 'CITY_WIDE',
|
||||
bindingStatus: 'ACTIVE',
|
||||
orderCommissionRate: 0,
|
||||
redeemCommissionRate: 0.03,
|
||||
bankAccountName: `${city.name}统计合伙人${j + 1}`,
|
||||
bankAccountNo: `622202${String(1000000000 + i * 10 + j)}`,
|
||||
bankBranch: `${city.name}工商银行`,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
createdPartners.push({ id: partner.id, cityId: city.id, city });
|
||||
|
||||
// 每位合伙人 3~5 家门店
|
||||
const storeN = 3 + Math.floor(rand() * 3);
|
||||
for (let k = 0; k < storeN; k++) {
|
||||
const sDay = Math.floor(rand() * Math.max(1, dayOffset + 1));
|
||||
const sCreated = new Date(today);
|
||||
sCreated.setDate(sCreated.getDate() - sDay);
|
||||
sCreated.setHours(11, Math.floor(rand() * 40), 0, 0);
|
||||
const rate = 0.6;
|
||||
const store = await prisma.store.create({
|
||||
data: {
|
||||
cityId: city.id,
|
||||
partnerAccountId: partner.id,
|
||||
categoryId: category?.id,
|
||||
name: `${STORE_NAME_PREFIX}-${city.name}-${j + 1}-${k + 1}`,
|
||||
phone: `1399${String(100000 + i * 100 + j * 10 + k).slice(-7)}`,
|
||||
province: city.province,
|
||||
cityName: city.name,
|
||||
district: city.district,
|
||||
address: `统计路${k + 1}号`,
|
||||
settlementRate: rate,
|
||||
status: 'OPEN',
|
||||
auditStatus: 'APPROVED',
|
||||
openTime: '10:00',
|
||||
closeTime: '22:00',
|
||||
createdAt: sCreated,
|
||||
updatedAt: sCreated,
|
||||
},
|
||||
});
|
||||
createdStores.push({
|
||||
id: store.id,
|
||||
cityId: city.id,
|
||||
partnerAccountId: partner.id,
|
||||
settlementRate: rate,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 用户 + 订单 ──
|
||||
const userCount = 100;
|
||||
const createdUsers: Array<{
|
||||
id: bigint;
|
||||
cityId: bigint;
|
||||
city: (typeof cities)[0];
|
||||
promoId: bigint | null;
|
||||
phone: string;
|
||||
}> = [];
|
||||
const paidOrders: Array<{
|
||||
id: bigint;
|
||||
userId: bigint;
|
||||
cityId: bigint;
|
||||
payAmount: number;
|
||||
productName: string;
|
||||
}> = [];
|
||||
|
||||
for (let i = 0; i < userCount; i++) {
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(8 + Math.floor(rand() * 12), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const city = cities[Math.floor(rand() * cities.length)];
|
||||
const promo = rand() < 0.7 ? promos[Math.floor(rand() * promos.length)] : null;
|
||||
const seq = String(i + 1).padStart(4, '0');
|
||||
const phone = `13888${String(10000 + i).slice(-5)}`;
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
userNo: `${USER_PREFIX}${seq}`,
|
||||
phone,
|
||||
phoneVerifiedAt: createdAt,
|
||||
nickname: `统计用户${seq}`,
|
||||
deviceKey: `stat-device-${seq}-${randomBytes(4).toString('hex')}`,
|
||||
sourceType: promo ? 'PROMO_CODE' : 'ORGANIC',
|
||||
sourceRefId: promo?.id ?? null,
|
||||
sourceLabel: promo?.name ?? null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
cityPreference: {
|
||||
create: {
|
||||
selectedCityCode: city.code,
|
||||
selectedDistrict: city.district,
|
||||
locateCityCode: city.code,
|
||||
locateDistrict: city.district,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
...(promo
|
||||
? {
|
||||
promoTouch: {
|
||||
create: {
|
||||
promoCodeId: promo.id,
|
||||
channelName: promo.name,
|
||||
firstTouchAt: createdAt,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
createdUsers.push({
|
||||
id: user.id,
|
||||
cityId: city.id,
|
||||
city,
|
||||
promoId: promo?.id ?? null,
|
||||
phone,
|
||||
});
|
||||
}
|
||||
|
||||
const statuses: Array<{ status: OrderStatus; payStatus: PayStatus }> = [
|
||||
{ status: 'COMPLETED', payStatus: 'PAID' },
|
||||
{ status: 'COMPLETED', payStatus: 'PAID' },
|
||||
{ status: 'PENDING_SHIP', payStatus: 'PAID' },
|
||||
{ status: 'SHIPPING', payStatus: 'PAID' },
|
||||
{ status: 'PENDING_PAY', payStatus: 'UNPAID' },
|
||||
{ status: 'CANCELLED', payStatus: 'UNPAID' },
|
||||
];
|
||||
|
||||
let orderCount = 0;
|
||||
const promoOrderInc = new Map<string, number>();
|
||||
|
||||
for (const u of createdUsers) {
|
||||
const n = 1 + Math.floor(rand() * 3);
|
||||
for (let j = 0; j < n; j++) {
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(10 + Math.floor(rand() * 10), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const qty = 2 + Math.floor(rand() * 3);
|
||||
const unit = Number(product.price);
|
||||
const listAmount = unit * qty;
|
||||
const st = statuses[Math.floor(rand() * statuses.length)];
|
||||
const paid = st.payStatus === 'PAID';
|
||||
orderCount += 1;
|
||||
const orderNo = `${ORDER_PREFIX}${String(orderCount).padStart(6, '0')}`;
|
||||
|
||||
const order = await prisma.order.create({
|
||||
data: {
|
||||
orderNo,
|
||||
userId: u.id,
|
||||
cityId: u.cityId,
|
||||
promoCodeId: u.promoId,
|
||||
channelSource: u.promoId ? 'STATS_MOCK' : null,
|
||||
status: st.status,
|
||||
payStatus: st.payStatus,
|
||||
deliveryType: 'LOCAL',
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
productName: product.name,
|
||||
productSpec: product.spec,
|
||||
quantity: qty,
|
||||
listUnitPrice: unit,
|
||||
listAmount,
|
||||
productAmount: listAmount,
|
||||
payAmount: listAmount,
|
||||
benefitAmount: listAmount,
|
||||
receiverName: `统计用户`,
|
||||
receiverPhone: u.phone,
|
||||
receiverAddress: `${u.city.name}${u.city.district}统计路1号`,
|
||||
receiverProvince: u.city.province,
|
||||
receiverCity: u.city.name,
|
||||
receiverDistrict: u.city.district,
|
||||
paidAt: paid ? createdAt : null,
|
||||
completedAt: st.status === 'COMPLETED' ? createdAt : null,
|
||||
cancelledAt: st.status === 'CANCELLED' ? createdAt : null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (paid) {
|
||||
paidOrders.push({
|
||||
id: order.id,
|
||||
userId: u.id,
|
||||
cityId: u.cityId,
|
||||
payAmount: listAmount,
|
||||
productName: product.name,
|
||||
});
|
||||
}
|
||||
|
||||
if (u.promoId) {
|
||||
const key = u.promoId.toString();
|
||||
promoOrderInc.set(key, (promoOrderInc.get(key) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, inc] of promoOrderInc) {
|
||||
await prisma.commonPromoCode.update({
|
||||
where: { id: BigInt(id) },
|
||||
data: { orderCount: { increment: inc }, scanCount: { increment: Math.floor(inc * 1.5) } },
|
||||
});
|
||||
}
|
||||
|
||||
// ── 权益券 + 核销(约 80 笔,分散近 30 天) ──
|
||||
const storesByCity = new Map<string, typeof createdStores>();
|
||||
for (const s of createdStores) {
|
||||
const key = s.cityId.toString();
|
||||
const list = storesByCity.get(key) ?? [];
|
||||
list.push(s);
|
||||
storesByCity.set(key, list);
|
||||
}
|
||||
|
||||
let redeemCount = 0;
|
||||
const redeemTarget = Math.min(80, paidOrders.length);
|
||||
for (let i = 0; i < redeemTarget; i++) {
|
||||
const order = paidOrders[i];
|
||||
const cityStores = storesByCity.get(order.cityId.toString()) ?? createdStores;
|
||||
if (!cityStores.length) continue;
|
||||
const store = cityStores[Math.floor(rand() * cityStores.length)];
|
||||
|
||||
const dayOffset = Math.floor(rand() * 30);
|
||||
const createdAt = new Date(today);
|
||||
createdAt.setDate(createdAt.getDate() - dayOffset);
|
||||
createdAt.setHours(14 + Math.floor(rand() * 6), Math.floor(rand() * 60), 0, 0);
|
||||
|
||||
const amount = Math.round((40 + rand() * 200) * 100) / 100;
|
||||
const settleAmount = Math.round(amount * store.settlementRate * 100) / 100;
|
||||
|
||||
const coupon = await prisma.benefitCoupon.create({
|
||||
data: {
|
||||
couponNo: `${COUPON_PREFIX}${String(i + 1).padStart(5, '0')}`,
|
||||
userId: order.userId,
|
||||
orderId: order.id,
|
||||
totalAmount: order.payAmount,
|
||||
usedAmount: amount,
|
||||
balance: Math.max(0, order.payAmount - amount),
|
||||
status: amount >= order.payAmount ? 'USED_UP' : 'ACTIVE',
|
||||
sourceProduct: order.productName,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
redeemCount += 1;
|
||||
await prisma.redeemRecord.create({
|
||||
data: {
|
||||
redeemNo: `${REDEEM_PREFIX}${String(redeemCount).padStart(5, '0')}`,
|
||||
userId: order.userId,
|
||||
couponId: coupon.id,
|
||||
storeId: store.id,
|
||||
amount,
|
||||
settleAmount,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Done: cities=${cities.length}, promos=${promos.length}, partners=${createdPartners.length}, ` +
|
||||
`stores=${createdStores.length}, users=${createdUsers.length}, orders=${orderCount}, redeems=${redeemCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const apiRoot = path.join(__dirname, '..');
|
||||
const prod = fs.readFileSync(path.join(apiRoot, '.env.production'), 'utf8');
|
||||
const m = prod.match(/^DATABASE_URL=(.*)$/m);
|
||||
if (!m) throw new Error('no prod DATABASE_URL');
|
||||
let url = m[1].trim();
|
||||
if (
|
||||
(url.startsWith('"') && url.endsWith('"')) ||
|
||||
(url.startsWith("'") && url.endsWith("'"))
|
||||
) {
|
||||
url = url.slice(1, -1);
|
||||
}
|
||||
if (!url.includes('/dukang_prod')) throw new Error('unexpected prod url');
|
||||
const stg = url.replace('/dukang_prod', '/dukang_staging');
|
||||
|
||||
const envPath = path.join(apiRoot, '.env.staging');
|
||||
let t = fs.readFileSync(envPath, 'utf8');
|
||||
if (!/^DATABASE_URL=/m.test(t)) {
|
||||
t = `DATABASE_URL=\n${t}`;
|
||||
}
|
||||
t = t.replace(/^DATABASE_URL=.*$/m, `DATABASE_URL=${JSON.stringify(stg)}`);
|
||||
fs.writeFileSync(envPath, t);
|
||||
|
||||
const u = new URL(stg);
|
||||
console.log(`ok ${u.hostname}:${u.port || 3306}${u.pathname}`);
|
||||
@@ -1,9 +1,17 @@
|
||||
import type { WechatJsapiPrepayParams } from '@dukang/shared-types';
|
||||
|
||||
export type PayMethod = 'JSAPI' | 'NATIVE';
|
||||
|
||||
export type PayOrderResult =
|
||||
| { mode: 'mock'; externalNo: string }
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams };
|
||||
| { mode: 'jsapi'; prepay: WechatJsapiPrepayParams }
|
||||
| { mode: 'native'; codeUrl: string; externalNo: string };
|
||||
|
||||
export interface IPayProvider {
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult>;
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult>;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayMockProvider implements IPayProvider {
|
||||
async payOrder(_orderId: bigint, _openId?: string, _platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
_openId?: string,
|
||||
_platform?: 'h5' | 'mini',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (!loadAppConfig().mockPay) {
|
||||
throw new Error('Real WeChat pay requires PayWechatProvider');
|
||||
}
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { loadAppConfig } from '@dukang/shared-types';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
import { PayMockProvider } from './pay.mock.provider';
|
||||
import { PayWechatProvider } from './pay.wechat.provider';
|
||||
|
||||
/** 按当前 process.env 动态选择 Mock / 微信 JSAPI 支付 */
|
||||
/** 按当前 process.env 动态选择 Mock / 微信支付 */
|
||||
@Injectable()
|
||||
export class PayRouterProvider implements IPayProvider {
|
||||
constructor(
|
||||
@@ -16,7 +16,12 @@ export class PayRouterProvider implements IPayProvider {
|
||||
return loadAppConfig().mockPay ? this.mock : this.wechat;
|
||||
}
|
||||
|
||||
payOrder(orderId: bigint, openId?: string, platform?: 'h5' | 'mini'): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform);
|
||||
payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform?: 'h5' | 'mini',
|
||||
payMethod?: PayMethod,
|
||||
): Promise<PayOrderResult> {
|
||||
return this.resolve().payOrder(orderId, openId, platform, payMethod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { loadAppConfig } from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { WECHAT_PROVIDER } from '../integrations.constants';
|
||||
import type { IWechatProvider } from '../wechat/wechat.interface';
|
||||
import type { IPayProvider, PayOrderResult } from './pay.interface';
|
||||
import type { IPayProvider, PayMethod, PayOrderResult } from './pay.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PayWechatProvider implements IPayProvider {
|
||||
@@ -14,28 +14,60 @@ export class PayWechatProvider implements IPayProvider {
|
||||
@Inject(WECHAT_PROVIDER) private readonly wechat: IWechatProvider,
|
||||
) {}
|
||||
|
||||
async payOrder(orderId: bigint, openId?: string, platform: 'h5' | 'mini' = 'h5'): Promise<PayOrderResult> {
|
||||
async payOrder(
|
||||
orderId: bigint,
|
||||
openId?: string,
|
||||
platform: 'h5' | 'mini' = 'h5',
|
||||
payMethod: PayMethod = 'JSAPI',
|
||||
): Promise<PayOrderResult> {
|
||||
if (loadAppConfig().mockPay) {
|
||||
if (payMethod === 'NATIVE') {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
const orderNo = order?.orderNo ?? orderId.toString();
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl: `mock://wechat-pay/native?orderNo=${encodeURIComponent(orderNo)}`,
|
||||
externalNo: `MOCK-NATIVE-${Date.now()}`,
|
||||
};
|
||||
}
|
||||
return { mode: 'mock', externalNo: `MOCK-${Date.now()}` };
|
||||
}
|
||||
if (!this.wechat.isPayEnabled()) {
|
||||
throw new Error('微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID 等商户参数');
|
||||
}
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new Error('订单不存在');
|
||||
|
||||
const amountFen = Math.round(Number(order.payAmount) * 100);
|
||||
const notifyUrl = process.env.WX_PAY_NOTIFY_URL ?? '';
|
||||
|
||||
if (payMethod === 'NATIVE') {
|
||||
this.logger.log(`create NATIVE prepay order=${order.orderNo} mchid=${this.wechat.getMchId()}`);
|
||||
const { codeUrl } = await this.wechat.createNativePrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
notifyUrl,
|
||||
});
|
||||
return {
|
||||
mode: 'native',
|
||||
codeUrl,
|
||||
externalNo: `NATIVE-${order.orderNo}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!openId) {
|
||||
throw new Error('微信支付需要用户 openId,请先完成微信授权登录');
|
||||
}
|
||||
|
||||
this.logger.log(`create JSAPI prepay order=${order.orderNo} mchid=${this.wechat.getMchId()} platform=${platform}`);
|
||||
const prepay = await this.wechat.createJsapiPrepay({
|
||||
orderNo: order.orderNo,
|
||||
description: `杜康好客订单 ${order.orderNo}`,
|
||||
amountFen,
|
||||
openId,
|
||||
notifyUrl: process.env.WX_PAY_NOTIFY_URL ?? '',
|
||||
notifyUrl,
|
||||
platform,
|
||||
});
|
||||
return { mode: 'jsapi', prepay };
|
||||
|
||||
@@ -553,6 +553,55 @@ export class WechatApiProvider implements IWechatProvider {
|
||||
};
|
||||
}
|
||||
|
||||
async createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
if (!this.isPayEnabled()) {
|
||||
throw new InternalServerErrorException(
|
||||
'微信支付未配置:请关闭 MOCK_PAY 并配置 WX_MCH_ID、WX_MCH_SERIAL_NO、WX_MCH_PRIVATE_KEY、WX_API_V3_KEY',
|
||||
);
|
||||
}
|
||||
const notifyUrl = params.notifyUrl || this.notifyUrl;
|
||||
if (!notifyUrl) {
|
||||
throw new InternalServerErrorException('请配置 WX_PAY_NOTIFY_URL');
|
||||
}
|
||||
const payAppId = this.appId || this.miniAppId;
|
||||
if (!payAppId) {
|
||||
throw new InternalServerErrorException('微信支付未配置:请设置 WX_APP_ID');
|
||||
}
|
||||
const body = {
|
||||
appid: payAppId,
|
||||
mchid: this.mchId,
|
||||
description: params.description,
|
||||
out_trade_no: params.orderNo,
|
||||
notify_url: notifyUrl,
|
||||
amount: { total: params.amountFen, currency: 'CNY' },
|
||||
};
|
||||
const path = '/v3/pay/transactions/native';
|
||||
const payload = JSON.stringify(body);
|
||||
const auth = this.signPayRequest('POST', path, payload);
|
||||
const res = await this.fetchPayJson<{ code_url?: string }>(
|
||||
`https://api.mch.weixin.qq.com${path}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: auth,
|
||||
},
|
||||
body: payload,
|
||||
},
|
||||
);
|
||||
if (!res.code_url) {
|
||||
throw new InternalServerErrorException('微信 Native 下单失败');
|
||||
}
|
||||
this.logger.log(`NATIVE prepay ok mchid=${this.mchId} orderNo=${params.orderNo}`);
|
||||
return { codeUrl: res.code_url };
|
||||
}
|
||||
|
||||
async parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -51,6 +51,10 @@ export class WechatDisabledProvider implements IWechatProvider {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
createNativePrepay() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
parsePayNotification() {
|
||||
return this.disabled();
|
||||
}
|
||||
|
||||
@@ -132,6 +132,14 @@ export interface IWechatProvider {
|
||||
platform?: 'h5' | 'mini';
|
||||
}): Promise<WechatJsapiPrepayParams>;
|
||||
|
||||
/** 创建 Native 扫码支付 code_url */
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}): Promise<{ codeUrl: string }>;
|
||||
|
||||
/** 解析并验签支付回调通知 */
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
|
||||
@@ -80,6 +80,10 @@ export class WechatMockProvider implements IWechatProvider {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
createNativePrepay(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
parsePayNotification(): never {
|
||||
throw new NotImplementedException('FEATURE_DISABLED');
|
||||
}
|
||||
|
||||
@@ -80,6 +80,15 @@ export class WechatRouterProvider implements IWechatProvider {
|
||||
return this.resolve().createJsapiPrepay(params);
|
||||
}
|
||||
|
||||
createNativePrepay(params: {
|
||||
orderNo: string;
|
||||
description: string;
|
||||
amountFen: number;
|
||||
notifyUrl: string;
|
||||
}) {
|
||||
return this.resolve().createNativePrepay(params);
|
||||
}
|
||||
|
||||
parsePayNotification(
|
||||
headers: Record<string, string | string[] | undefined>,
|
||||
rawBody: string,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import { SuperAdminGuard } from '../../common/guards/super-admin.guard';
|
||||
import { AdminDashboardService } from './admin-dashboard.service';
|
||||
import { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
@Controller('admin/dashboard')
|
||||
@UseGuards(HqAuthGuard)
|
||||
@@ -13,6 +14,11 @@ export class AdminDashboardController {
|
||||
return this.dashboardService.getStats();
|
||||
}
|
||||
|
||||
@Get('analytics')
|
||||
analytics(@Query() query: AdminDashboardAnalyticsQueryDto) {
|
||||
return this.dashboardService.getAnalytics(query);
|
||||
}
|
||||
|
||||
@Get('version')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
version() {
|
||||
|
||||
@@ -1,5 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
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);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminDashboardService {
|
||||
@@ -59,7 +98,6 @@ export class AdminDashboardService {
|
||||
redeemToday,
|
||||
deliveriesTotal,
|
||||
pendingPayouts,
|
||||
/** 合伙人已确认、待总部审核打款 */
|
||||
pendingBills,
|
||||
pendingPartnerDraftBills,
|
||||
openTickets,
|
||||
@@ -85,4 +123,426 @@ export class AdminDashboardService {
|
||||
deployedAt: row.deployedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
async getAnalytics(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);
|
||||
|
||||
let filterCityCode: string | null | undefined;
|
||||
let filterCityId: bigint | null | undefined;
|
||||
if (query.cityId === 'none') {
|
||||
filterCityCode = null;
|
||||
filterCityId = null;
|
||||
} else if (query.cityId) {
|
||||
const city = await this.prisma.commonCity.findUnique({
|
||||
where: { id: BigInt(query.cityId) },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
if (city) {
|
||||
filterCityCode = city.code;
|
||||
filterCityId = city.id;
|
||||
}
|
||||
}
|
||||
|
||||
const filterPromoNone = query.promoCodeId === 'none';
|
||||
const filterPromoId =
|
||||
query.promoCodeId && query.promoCodeId !== 'none'
|
||||
? BigInt(query.promoCodeId)
|
||||
: undefined;
|
||||
const filterPartnerId = query.partnerAccountId
|
||||
? BigInt(query.partnerAccountId)
|
||||
: undefined;
|
||||
|
||||
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 (filterCityCode) {
|
||||
userWhere.cityPreference = { selectedCityCode: filterCityCode };
|
||||
}
|
||||
if (filterPromoNone) {
|
||||
userWhere.promoTouch = { is: null };
|
||||
} else if (filterPromoId !== undefined) {
|
||||
userWhere.promoTouch = { promoCodeId: filterPromoId };
|
||||
}
|
||||
|
||||
const orderWhere: Prisma.OrderWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId !== undefined && filterCityId !== null) {
|
||||
orderWhere.cityId = filterCityId;
|
||||
}
|
||||
if (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 (filterCityId !== undefined) {
|
||||
partnerWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) {
|
||||
partnerWhere.id = filterPartnerId;
|
||||
}
|
||||
|
||||
const storeWhere: Prisma.StoreWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
// 门店必有 cityId
|
||||
storeWhere.id = { in: [] };
|
||||
} 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 (filterCityId !== undefined) storeFilter.cityId = filterCityId;
|
||||
if (filterPartnerId !== undefined) storeFilter.partnerAccountId = filterPartnerId;
|
||||
if (Object.keys(storeFilter).length) {
|
||||
redeemWhere.store = storeFilter;
|
||||
}
|
||||
}
|
||||
|
||||
const skipOrders = filterCityId === null;
|
||||
|
||||
const [users, orders, partners, stores, redeems, cities, promos, partnerNames] =
|
||||
await Promise.all([
|
||||
this.prisma.user.findMany({
|
||||
where: userWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityPreference: { select: { selectedCityCode: true } },
|
||||
promoTouch: { select: { promoCodeId: true } },
|
||||
},
|
||||
}),
|
||||
skipOrders
|
||||
? Promise.resolve([])
|
||||
: this.prisma.order.findMany({
|
||||
where: orderWhere,
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
promoCodeId: true,
|
||||
payStatus: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.partnerAccount.findMany({
|
||||
where: partnerWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
companyName: true,
|
||||
name: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.store.findMany({
|
||||
where: storeWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
partnerAccountId: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.redeemRecord.findMany({
|
||||
where: redeemWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
amount: true,
|
||||
settleAmount: true,
|
||||
store: { select: { cityId: true, partnerAccountId: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.commonCity.findMany({
|
||||
select: { id: true, code: true, name: true },
|
||||
}),
|
||||
this.prisma.commonPromoCode.findMany({
|
||||
select: { id: true, code: true, name: true },
|
||||
}),
|
||||
this.prisma.partnerAccount.findMany({
|
||||
where: { isPrimary: 1 },
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
@@ -10,7 +10,11 @@ import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||
import { TradeService } from '../trade/trade.service';
|
||||
import { HqProxyOrderCreateDto, HqProxyOrderPreviewDto } from './dto/hq-proxy-order.dto';
|
||||
import {
|
||||
HqProxyOrderCreateDto,
|
||||
HqProxyOrderPayDto,
|
||||
HqProxyOrderPreviewDto,
|
||||
} from './dto/hq-proxy-order.dto';
|
||||
|
||||
@Controller('admin/proxy-orders')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@@ -42,4 +46,19 @@ export class AdminProxyOrdersController {
|
||||
) {
|
||||
return this.tradeService.createHqProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(@Param('id') id: string, @Body() dto: HqProxyOrderPayDto) {
|
||||
return this.tradeService.payHqProxyOrder(BigInt(id), dto.payMethod ?? 'NATIVE');
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), { hq: true });
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
payStatus(@Param('id') id: string) {
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,33 @@ export class AdminOrdersQueryDto extends PaginationQueryDto {
|
||||
createdTo?: string;
|
||||
}
|
||||
|
||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
||||
export class AdminDashboardAnalyticsQueryDto {
|
||||
/** YYYY-MM-DD,默认近 30 天 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateFrom?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateTo?: string;
|
||||
|
||||
/** 开城城市 id;`none` = 用户未选城 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cityId?: string;
|
||||
|
||||
/** 推广码 id;`none` = 无归因 / 订单无推广码 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
|
||||
/** 城市合伙人(主账号)id */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
partnerAccountId?: string;
|
||||
}
|
||||
|
||||
export class AdminStoresQueryDto extends PaginationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -85,3 +85,9 @@ export class HqProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class HqProxyOrderPayDto {
|
||||
@IsOptional()
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod?: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -93,3 +93,8 @@ export class PartnerProxyOrderCreateDto {
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
}
|
||||
|
||||
export class PartnerProxyOrderPayDto {
|
||||
@IsIn(['NATIVE', 'JSAPI'])
|
||||
payMethod: 'NATIVE' | 'JSAPI';
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { PartnerPermissionGuard } from '../../common/guards/partner-permission.g
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import {
|
||||
PartnerProxyOrderCreateDto,
|
||||
PartnerProxyOrderPayDto,
|
||||
PartnerProxyOrderPreviewDto,
|
||||
} from './dto/partner-proxy-order.dto';
|
||||
import { ManualShipOrderDto } from '../ops/dto/admin-mutate.dto';
|
||||
@@ -223,11 +224,6 @@ export class PartnerProxyOrderController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Post('preview')
|
||||
preview(@CurrentUser() user: AuthUser, @Body() dto: PartnerProxyOrderPreviewDto) {
|
||||
return this.tradeService.previewPartnerProxyOrderForPartner(user.actorId, dto);
|
||||
@@ -241,4 +237,36 @@ export class PartnerProxyOrderController {
|
||||
) {
|
||||
return this.tradeService.createPartnerProxyOrder(user.actorId, dto, req);
|
||||
}
|
||||
|
||||
@Post(':id/pay')
|
||||
pay(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: PartnerProxyOrderPayDto,
|
||||
) {
|
||||
return this.tradeService.payPartnerProxyOrder(user.actorId, BigInt(id), dto.payMethod);
|
||||
}
|
||||
|
||||
@Post(':id/pay/mock-confirm')
|
||||
mockConfirmPay(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.mockConfirmProxyPay(BigInt(id), {
|
||||
partnerAccountId: user.actorId,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id/pay-status')
|
||||
async payStatus(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
await this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
return this.tradeService.getProxyPayStatus(BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id/track')
|
||||
track(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrderTrack(user.actorId, BigInt(id));
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@CurrentUser() user: AuthUser, @Param('id') id: string) {
|
||||
return this.tradeService.getPartnerProxyOrder(user.actorId, BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1257,7 +1257,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1271,10 +1271,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1299,9 +1299,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? primary.id,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: primary.id,
|
||||
@@ -1312,23 +1310,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'PARTNER_PROXY',
|
||||
remark: `合伙人线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
remark: `合伙人代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} partner=${primary.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1342,8 +1330,6 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
this.analyticsService.trackPartnerOneSafe(partnerAccountId, 'PARTNER_H5', {
|
||||
partnerAccountId: primary.id,
|
||||
eventName: 'partner_proxy_order_create',
|
||||
@@ -1359,7 +1345,17 @@ export class TradeService {
|
||||
},
|
||||
});
|
||||
|
||||
return serializeBigInt(mapOrderCompat(order));
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: primary.name,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单列表:按 proxyPartnerAccountId 归属,与管仓订单无关 */
|
||||
@@ -1547,7 +1543,7 @@ export class TradeService {
|
||||
}
|
||||
|
||||
const orderNo = generateOrderNo();
|
||||
const now = new Date();
|
||||
const payExpireAt = new Date(Date.now() + 30 * 60 * 1000);
|
||||
const location = buildOrderClientLocationSnapshot(
|
||||
req,
|
||||
this.ipGeoService.resolve(extractClientIp(req)),
|
||||
@@ -1561,10 +1557,10 @@ export class TradeService {
|
||||
orderType: 'PROXY',
|
||||
userId: user.id,
|
||||
cityId: city.id,
|
||||
status: 'COMPLETED',
|
||||
payStatus: 'PAID',
|
||||
status: 'PENDING_PAY',
|
||||
payStatus: 'UNPAID',
|
||||
deliveryType: preview.deliveryType,
|
||||
channelSource: 'OFFLINE_PROXY',
|
||||
channelSource: 'PROXY_ONLINE',
|
||||
promoCodeId,
|
||||
productId: product.id,
|
||||
barcode69: product.barcode69,
|
||||
@@ -1589,9 +1585,7 @@ export class TradeService {
|
||||
ipProvince: location.ipProvince,
|
||||
ipCity: location.ipCity,
|
||||
ipDistrict: location.ipDistrict,
|
||||
paidAt: now,
|
||||
shippedAt: now,
|
||||
completedAt: now,
|
||||
payExpireAt,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? null,
|
||||
orderCommissionRateAtPay: paySnapshot?.orderCommissionRate ?? null,
|
||||
proxyPartnerAccountId: null,
|
||||
@@ -1602,23 +1596,13 @@ export class TradeService {
|
||||
include: { product: true, imageResource: true },
|
||||
});
|
||||
|
||||
await tx.orderDelivery.create({
|
||||
data: {
|
||||
orderId: created.id,
|
||||
provider: 'MANUAL',
|
||||
outWarehouseAt: now,
|
||||
shippingAt: now,
|
||||
deliveredAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: created.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus: 'COMPLETED',
|
||||
toStatus: 'PENDING_PAY',
|
||||
operator: 'HQ_PROXY',
|
||||
remark: `总部线下代下单 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
remark: `总部代下单待支付 mode=${body.deliveryMode} customer=${normalizedPhone} hq=${hq.id}`,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1632,15 +1616,245 @@ export class TradeService {
|
||||
return created;
|
||||
});
|
||||
|
||||
await this.benefitService.grantOnOrderPaid(order.id);
|
||||
|
||||
return serializeBigInt({
|
||||
id: order.id,
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
benefitAmount: Number(order.benefitAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
proxyPartnerName: proxyDisplayName,
|
||||
};
|
||||
}
|
||||
|
||||
/** 合伙人代下单支付:NATIVE 商家码 / JSAPI 合伙人微信代付 */
|
||||
async payPartnerProxyOrder(
|
||||
partnerAccountId: bigint,
|
||||
orderId: bigint,
|
||||
payMethod: 'NATIVE' | 'JSAPI',
|
||||
) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
let openId: string | undefined;
|
||||
if (payMethod === 'JSAPI') {
|
||||
openId = primary.wxOpenId ?? undefined;
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay && !openId) {
|
||||
throw new BadRequestException('请先在微信内登录并绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, openId, 'h5', payMethod);
|
||||
|
||||
if (payResult.mode === 'native') {
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (payResult.mode === 'jsapi') {
|
||||
return {
|
||||
mode: 'jsapi' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
prepay: payResult.prepay,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(order.id, payResult.externalNo, 'PARTNER_PROXY_MOCK_PAY');
|
||||
return {
|
||||
mode: 'mock' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 总部代下单支付:仅 Native 收款码 */
|
||||
async payHqProxyOrder(orderId: bigint, payMethod: 'NATIVE' | 'JSAPI' = 'NATIVE') {
|
||||
if (payMethod !== 'NATIVE') {
|
||||
throw new BadRequestException('总部代下单仅支持收款码支付');
|
||||
}
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.status !== 'PENDING_PAY' || order.payStatus !== 'UNPAID') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
if (order.payExpireAt && order.payExpireAt.getTime() < Date.now()) {
|
||||
throw new BadRequestException('订单已超时未支付');
|
||||
}
|
||||
|
||||
const payResult = await this.payProvider.payOrder(orderId, undefined, 'h5', 'NATIVE');
|
||||
if (payResult.mode !== 'native') {
|
||||
throw new BadRequestException('无法生成收款码');
|
||||
}
|
||||
return {
|
||||
mode: 'native' as const,
|
||||
orderId: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
codeUrl: payResult.codeUrl,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mock 环境确认代下单支付 */
|
||||
async mockConfirmProxyPay(
|
||||
orderId: bigint,
|
||||
opts: { partnerAccountId?: bigint; hq?: boolean },
|
||||
) {
|
||||
const appConfig = loadAppConfig();
|
||||
if (!appConfig.mockPay) {
|
||||
throw new BadRequestException('仅 MOCK_PAY 环境可用');
|
||||
}
|
||||
|
||||
let order;
|
||||
if (opts.partnerAccountId != null) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(opts.partnerAccountId);
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
order = await this.prisma.order.findFirst({
|
||||
where: { id: orderId, orderType: 'PROXY' },
|
||||
});
|
||||
}
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
if (order.payStatus === 'PAID') {
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
if (order.status !== 'PENDING_PAY') {
|
||||
throw new BadRequestException('订单状态不可支付');
|
||||
}
|
||||
|
||||
await this.markProxyOrderPaid(
|
||||
order.id,
|
||||
`MOCK-CONFIRM-${Date.now()}`,
|
||||
opts.hq ? 'HQ_PROXY_MOCK_PAY' : 'PARTNER_PROXY_MOCK_PAY',
|
||||
);
|
||||
return this.getProxyPayStatus(order.id);
|
||||
}
|
||||
|
||||
async getProxyPayStatus(orderId: bigint) {
|
||||
const order = await this.prisma.order.findUnique({
|
||||
where: { id: orderId },
|
||||
select: {
|
||||
id: true,
|
||||
orderNo: true,
|
||||
status: true,
|
||||
payStatus: true,
|
||||
payAmount: true,
|
||||
deliveryType: true,
|
||||
payExpireAt: true,
|
||||
paidAt: true,
|
||||
},
|
||||
});
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
return {
|
||||
id: order.id.toString(),
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
payStatus: order.payStatus,
|
||||
payAmount: Number(order.payAmount),
|
||||
deliveryType: order.deliveryType,
|
||||
payExpireAt: order.payExpireAt?.toISOString() ?? null,
|
||||
paidAt: order.paidAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async getPartnerProxyOrderTrack(partnerAccountId: bigint, orderId: bigint) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const order = await this.prisma.order.findFirst({
|
||||
where: {
|
||||
id: orderId,
|
||||
orderType: 'PROXY',
|
||||
proxyPartnerAccountId: primary.id,
|
||||
},
|
||||
select: { id: true, deliveryType: true },
|
||||
});
|
||||
if (!order) throw new NotFoundException('代下单不存在');
|
||||
return this.fulfillmentService.getOrderTrack(orderId);
|
||||
}
|
||||
|
||||
private async markProxyOrderPaid(orderId: bigint, externalNo: string, operator: string) {
|
||||
const order = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||
if (!order) throw new NotFoundException('订单不存在');
|
||||
if (order.payStatus === 'PAID') return;
|
||||
|
||||
const now = new Date();
|
||||
const paySnapshot = await this.partnerCityService.resolveForOrder(
|
||||
order.cityId,
|
||||
order.receiverDistrict,
|
||||
);
|
||||
const toStatus =
|
||||
order.deliveryType === 'ON_SITE_PICKUP' ? 'PENDING_RECEIVE' : 'PENDING_SHIP';
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.order.update({
|
||||
where: { id: order.id },
|
||||
data: {
|
||||
status: toStatus,
|
||||
payStatus: 'PAID',
|
||||
paidAt: now,
|
||||
payExternalNo: externalNo,
|
||||
partnerAccountIdAtPay: paySnapshot?.partnerAccountId ?? order.partnerAccountIdAtPay,
|
||||
orderCommissionRateAtPay:
|
||||
paySnapshot?.orderCommissionRate ?? order.orderCommissionRateAtPay,
|
||||
},
|
||||
});
|
||||
await tx.logThirdParty.create({
|
||||
data: {
|
||||
provider: 'WECHAT_PAY',
|
||||
scene: 'ORDER_PAY',
|
||||
refType: 'ORDER',
|
||||
refId: order.id,
|
||||
externalNo,
|
||||
amount: order.payAmount,
|
||||
status: 'SUCCESS',
|
||||
},
|
||||
});
|
||||
await tx.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId: order.id,
|
||||
fromStatus: 'PENDING_PAY',
|
||||
toStatus,
|
||||
operator,
|
||||
}),
|
||||
});
|
||||
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
||||
if (!delivery) {
|
||||
await tx.orderDelivery.create({
|
||||
data: { orderId: order.id, provider: 'MANUAL' },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await this.afterOrderPaid(order.id);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -97,7 +97,7 @@
|
||||
| SC-04 | 门店核销 | 出码/报手机号→核销→权益扣减→门店账本×60% |
|
||||
| SC-05 | 拓店入驻 | 合伙人录入→负责人复核→总部审核→试核销100元→营业 |
|
||||
| SC-06 | 售后工单 | 用户四类型→总部审→仓/合伙人协同→补发/退款 |
|
||||
| SC-07 | 代下单 | 总部/合伙人手机号建用户下单(Wave 3);合伙人侧:双短信确认、线下完成发权益、订单记代下单人;总部本期对齐后续 |
|
||||
| SC-07 | 代下单 | 总部/合伙人手机号建用户下单;在线支付(商家收款码 / 合伙人微信代付)后发权益;配送进入待发货由总部履约,现场提货走自提闭环;订单记代下单人 |
|
||||
| SC-08 | 问卷+评价 | 成交后问卷;核销后门店评价 |
|
||||
| SC-09 | 推广归因 | 推广码进小程序→绑定合伙人→统计成交/佣金 |
|
||||
|
||||
@@ -403,7 +403,7 @@
|
||||
|
||||
| OPT | 波次 | 说明 |
|
||||
|-----|------|------|
|
||||
| OPT-002 代下单 | W3 | 合伙人主账号:客户验码→选品/履约(配送须勾选自动收货或现场提货选门店)→合伙人确认码;线下已收款直接完成发权益;新用户 sourceType=PARTNER_PROXY;总部代下单后续对齐 |
|
||||
| OPT-002 代下单 | W3 | 合伙人主账号:选品/履约(配送须勾选自动收货或现场提货)→创建待支付订单→收款码或微信代付(合伙人 openId)→支付成功发权益;配送单 PENDING_SHIP 由总部发货,合伙人可看物流;现场提货支付后自提闭环;新用户 sourceType=PARTNER_PROXY;总部代下单同为在线收款码支付 |
|
||||
| OPT-006 弱网 | W3 | W1~2 重试+人工补核销 |
|
||||
| OPT-010 未出账提现 | W2 | 含 FIN-001~003 |
|
||||
| OPT-005 现场提货 | W2 | — |
|
||||
@@ -432,6 +432,7 @@
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
|------|------|------|
|
||||
| v3.0.2 | 2026-08-02 | OPT-002/SC-07:代下单改为在线支付(收款码/合伙人微信代付);去掉线下已收款直完成;配送单总部履约、合伙人可看物流 |
|
||||
| v3.0.1 | 2026-07-27 | ACC-012/OPT-002/SC-07:明确合伙人代下单双短信、线下完成、来源 PARTNER_PROXY、C 端展示代下单人 |
|
||||
| v3.0 | 2026-07-11 | 由产品 PRD v1.3 整理为工程 V3.0 事实源;配套 `@dukang-v3` skill 与 `v3-delivery-lead` agent |
|
||||
|
||||
|
||||
Reference in New Issue
Block a user