Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b32c68d56b | |||
| 6816835fb8 | |||
| 571959900b | |||
| 7bc710f139 | |||
| 397bdad73f | |||
| 83b1b0e5f6 | |||
| 91fed31b10 | |||
| 1933b9b608 | |||
| a2abbb6169 | |||
| 53a79d1255 | |||
| 0181af09c5 | |||
| 9cd0c9508a | |||
| 4f363fa9e7 | |||
| 291137a15d | |||
| e2a5f21f9d | |||
| 3ef4432b2f | |||
| 33b868dfac | |||
| 5c4ad1d8db | |||
| a346fae7a4 | |||
| 37bc297d1a | |||
| bc1616c3f7 | |||
| 46a200e0ba | |||
| 429eaabe6b | |||
| 607a0224cd | |||
| 53e0db6a98 | |||
| 456b3af461 | |||
| 1f7ecffe4c | |||
| 8df0a2bea7 | |||
| 672a995c59 | |||
| 69f52921a7 | |||
| 9cb88dc181 | |||
| 345d5db9c9 | |||
| 7c9240fc84 | |||
| 2610288df0 | |||
| 62652cd072 | |||
| 9d49ed5e70 | |||
| bdbd135318 | |||
| 8ca893efab | |||
| d0ab838da6 | |||
| 50ab0f1748 | |||
| fa6fb80d19 | |||
| bd1930f6b1 | |||
| dc4295d1bd | |||
| 256526c5ec | |||
| 1c4b986924 | |||
| bf501d2374 | |||
| 442500b1a1 | |||
| 490c26a7e1 | |||
| b40eb83f27 | |||
| f80a0f2c27 | |||
| 528669f662 |
@@ -11,7 +11,7 @@
|
|||||||
| **V3.0 唯一需求源** | [`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md) | 产品需求与三波交付(**只看这个**) |
|
| **V3.0 唯一需求源** | [`杜康好客-v3-PRD.md`](./杜康好客-v3-PRD.md) | 产品需求与三波交付(**只看这个**) |
|
||||||
| **现状对照** | [`杜康好客-v3-现状对照.md`](./杜康好客-v3-现状对照.md) | 已完成 / 冲突 / 缺口审计 |
|
| **现状对照** | [`杜康好客-v3-现状对照.md`](./杜康好客-v3-现状对照.md) | 已完成 / 冲突 / 缺口审计 |
|
||||||
| **V3 实现验收** | [`杜康好客-v3编码手册.md`](./杜康好客-v3编码手册.md) | 核销规则、分工、闭环 |
|
| **V3 实现验收** | [`杜康好客-v3编码手册.md`](./杜康好客-v3编码手册.md) | 核销规则、分工、闭环 |
|
||||||
| ~~V2 / preV1~~ | 历史参考 | **不再作为需求依据** |
|
| ~~V2 / preV1~~ | 历史参考(**已压缩**;V2 全文见 git 2026-08-06 前) | **不再作为需求依据** |
|
||||||
|
|
||||||
**禁止**:臆造 PRD 未定义规则;依赖 `doc/` 下过时文档;跨 OWNER 直写他人 Prisma 表。
|
**禁止**:臆造 PRD 未定义规则;依赖 `doc/` 下过时文档;跨 OWNER 直写他人 Prisma 表。
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ant-design/icons": "^5.5.1",
|
"@ant-design/icons": "^5.5.1",
|
||||||
"@dukang/shared-types": "workspace:*",
|
"@dukang/shared-types": "workspace:*",
|
||||||
|
"@dukang/shared-ui": "workspace:*",
|
||||||
"antd": "^5.22.0",
|
"antd": "^5.22.0",
|
||||||
"dayjs": "^1.11.13",
|
"dayjs": "^1.11.13",
|
||||||
"echarts": "^6.1.0",
|
"echarts": "^6.1.0",
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ type OssUploadProps = {
|
|||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MAX_MB = 10;
|
|
||||||
|
|
||||||
export default function OssUpload({
|
export default function OssUpload({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -24,7 +22,6 @@ export default function OssUpload({
|
|||||||
bizType,
|
bizType,
|
||||||
mediaType = 'IMAGE',
|
mediaType = 'IMAGE',
|
||||||
accept,
|
accept,
|
||||||
maxSizeMb = DEFAULT_MAX_MB,
|
|
||||||
placeholder = '上传后自动填入,或手动粘贴 URL',
|
placeholder = '上传后自动填入,或手动粘贴 URL',
|
||||||
}: OssUploadProps) {
|
}: OssUploadProps) {
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
@@ -34,12 +31,6 @@ export default function OssUpload({
|
|||||||
|
|
||||||
const customRequest: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
const customRequest: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
||||||
const raw = file as File;
|
const raw = file as File;
|
||||||
if (raw.size > maxSizeMb * 1024 * 1024) {
|
|
||||||
const err = new Error(`文件不能超过 ${maxSizeMb}MB`);
|
|
||||||
message.error(err.message);
|
|
||||||
onError?.(err);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
try {
|
try {
|
||||||
const result = await uploadFileToOss(raw, { bizType, mediaType });
|
const result = await uploadFileToOss(raw, { bizType, mediaType });
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Descriptions } from 'antd';
|
||||||
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
|
||||||
|
function maskPhone(phone: string | null | undefined) {
|
||||||
|
if (!phone || phone.length < 7) return phone ?? '—';
|
||||||
|
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
detail: Record<string, unknown>;
|
||||||
|
/** 列表页已脱敏展示时可设为 false,详情抽屉展示完整手机号 */
|
||||||
|
maskUserPhone?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone = false }: Props) {
|
||||||
|
const user = detail.user as
|
||||||
|
| { userNo?: string; nickname?: string | null; phone?: string | null }
|
||||||
|
| undefined;
|
||||||
|
const store = detail.store as
|
||||||
|
| {
|
||||||
|
name?: string;
|
||||||
|
cityName?: string;
|
||||||
|
address?: string;
|
||||||
|
partnerAccount?: { companyName?: string };
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
const coupon = detail.coupon as { couponNo?: string; order?: { orderNo?: string } } | undefined;
|
||||||
|
const channel = detail.channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Descriptions column={1} bordered size="small">
|
||||||
|
<Descriptions.Item label="核销号">{String(detail.redeemNo ?? '—')}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="方式">{REDEEM_CHANNEL_LABELS[channel as RedeemChannel]}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="核销额">¥{Number(detail.amount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结算额">¥{Number(detail.settleAmount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt ?? ''))}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户编号">{user?.userNo ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户昵称">{user?.nickname?.trim() || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户手机">
|
||||||
|
{maskUserPhone ? maskPhone(user?.phone) : user?.phone || '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="门店">
|
||||||
|
{store?.name ?? '—'}
|
||||||
|
{store?.cityName ? `(${store.cityName})` : ''}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="门店地址">{store?.address ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="合伙人">{store?.partnerAccount?.companyName ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="权益券号">{coupon?.couponNo ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="关联订单">{coupon?.order?.orderNo ?? '—'}</Descriptions.Item>
|
||||||
|
{Array.isArray(detail.allocations) && (detail.allocations as unknown[]).length > 0 ? (
|
||||||
|
<Descriptions.Item label="券分摊">
|
||||||
|
{(
|
||||||
|
detail.allocations as Array<{
|
||||||
|
couponNo?: string;
|
||||||
|
orderNo?: string | null;
|
||||||
|
amount?: number;
|
||||||
|
}>
|
||||||
|
)
|
||||||
|
.map((a, idx) => {
|
||||||
|
const role = idx === 0 ? '主' : '次';
|
||||||
|
return `${role} ${a.couponNo ?? '—'}¥${Number(a.amount ?? 0).toFixed(2)}${
|
||||||
|
a.orderNo ? `(订单 ${a.orderNo})` : ''
|
||||||
|
}`;
|
||||||
|
})
|
||||||
|
.join(';')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
{detail.payout ? (
|
||||||
|
<Descriptions.Item label="门店结算单">
|
||||||
|
¥{Number((detail.payout as { settleAmount?: number }).settleAmount ?? 0).toFixed(2)}
|
||||||
|
{' / '}
|
||||||
|
{String((detail.payout as { status?: string }).status ?? '—')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
{detail.rating ? (
|
||||||
|
<Descriptions.Item label="评价">
|
||||||
|
服务 {(detail.rating as { serviceScore?: number }).serviceScore ?? '—'} 分 / 环境{' '}
|
||||||
|
{(detail.rating as { envScore?: number }).envScore ?? '—'} 分
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
</Descriptions>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase, CLIENT_APP, getToken, clearAuth } from './api';
|
import { apiBase, CLIENT_APP, getToken, clearAuth } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||||
|
|
||||||
@@ -9,14 +14,24 @@ export type UploadFileResult = {
|
|||||||
mock: boolean;
|
mock: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async function prepareUploadFile(file: File, mediaType: OssMediaType): Promise<File> {
|
||||||
|
if (mediaType !== 'IMAGE') return file;
|
||||||
|
const compressed = await compressImageFileIfNeeded(file);
|
||||||
|
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||||
|
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||||
|
}
|
||||||
|
return compressed;
|
||||||
|
}
|
||||||
|
|
||||||
/** 经 API 服务端转存 OSS,避免浏览器直传跨域 */
|
/** 经 API 服务端转存 OSS,避免浏览器直传跨域 */
|
||||||
export async function uploadFileToOss(
|
export async function uploadFileToOss(
|
||||||
file: File,
|
file: File,
|
||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||||
|
const prepared = await prepareUploadFile(file, mediaType);
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import type { ColumnsType } from 'antd/es/table';
|
|||||||
import type { AdminBenefitGrantRequest } from '@dukang/shared-types';
|
import type { AdminBenefitGrantRequest } from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants';
|
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants';
|
||||||
|
import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
type Row = {
|
type Row = {
|
||||||
@@ -242,7 +243,8 @@ export default function BenefitCouponsPage() {
|
|||||||
|
|
||||||
<Drawer
|
<Drawer
|
||||||
title="权益券详情"
|
title="权益券详情"
|
||||||
width={720}
|
width={980}
|
||||||
|
styles={{ body: { paddingBottom: 24 } }}
|
||||||
open={drawerOpen}
|
open={drawerOpen}
|
||||||
onClose={() => setDrawerOpen(false)}
|
onClose={() => setDrawerOpen(false)}
|
||||||
extra={
|
extra={
|
||||||
@@ -310,14 +312,15 @@ export default function BenefitCouponsPage() {
|
|||||||
size="small"
|
size="small"
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
pagination={false}
|
pagination={false}
|
||||||
|
tableLayout="fixed"
|
||||||
locale={{ emptyText: '暂无关联核销单' }}
|
locale={{ emptyText: '暂无关联核销单' }}
|
||||||
dataSource={detail.redeemRecords ?? []}
|
dataSource={detail.redeemRecords ?? []}
|
||||||
columns={[
|
columns={[
|
||||||
{ title: '核销号', dataIndex: 'redeemNo', width: 160, ellipsis: true },
|
{ title: '核销号', dataIndex: 'redeemNo', ellipsis: true },
|
||||||
{
|
{
|
||||||
title: '角色',
|
title: '角色',
|
||||||
dataIndex: 'role',
|
dataIndex: 'role',
|
||||||
width: 70,
|
width: 72,
|
||||||
render: (v: string | undefined) =>
|
render: (v: string | undefined) =>
|
||||||
v === 'SECONDARY' ? <Tag color="orange">次券</Tag> : <Tag color="blue">主券</Tag>,
|
v === 'SECONDARY' ? <Tag color="orange">次券</Tag> : <Tag color="blue">主券</Tag>,
|
||||||
},
|
},
|
||||||
@@ -331,31 +334,31 @@ export default function BenefitCouponsPage() {
|
|||||||
{
|
{
|
||||||
title: '本券分摊',
|
title: '本券分摊',
|
||||||
dataIndex: 'couponAmount',
|
dataIndex: 'couponAmount',
|
||||||
width: 95,
|
width: 96,
|
||||||
render: (v: number | undefined, row: CouponRedeemRecord) =>
|
render: (v: number | undefined, row: CouponRedeemRecord) =>
|
||||||
`¥${Number(v ?? row.amount).toFixed(2)}`,
|
`¥${Number(v ?? row.amount).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '核销总额',
|
title: '核销总额',
|
||||||
dataIndex: 'amount',
|
dataIndex: 'amount',
|
||||||
width: 90,
|
width: 96,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '结算额',
|
title: '结算额',
|
||||||
dataIndex: 'settleAmount',
|
dataIndex: 'settleAmount',
|
||||||
width: 90,
|
width: 96,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '时间',
|
title: '时间',
|
||||||
dataIndex: 'createdAt',
|
dataIndex: 'createdAt',
|
||||||
width: 150,
|
width: 148,
|
||||||
render: (v: string) => fmtTime(v),
|
render: (v: string) => fmtTime(v),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 70,
|
width: 64,
|
||||||
render: (_: unknown, row: CouponRedeemRecord) => (
|
render: (_: unknown, row: CouponRedeemRecord) => (
|
||||||
<Button type="link" size="small" onClick={() => void openRedeemDetail(row.id)}>
|
<Button type="link" size="small" onClick={() => void openRedeemDetail(row.id)}>
|
||||||
详情
|
详情
|
||||||
@@ -374,7 +377,7 @@ export default function BenefitCouponsPage() {
|
|||||||
|
|
||||||
<Drawer
|
<Drawer
|
||||||
title="核销单详情"
|
title="核销单详情"
|
||||||
width={520}
|
width={640}
|
||||||
open={redeemDrawerOpen}
|
open={redeemDrawerOpen}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setRedeemDrawerOpen(false);
|
setRedeemDrawerOpen(false);
|
||||||
@@ -385,79 +388,7 @@ export default function BenefitCouponsPage() {
|
|||||||
{redeemDetailLoading ? (
|
{redeemDetailLoading ? (
|
||||||
<Typography.Text type="secondary">加载中…</Typography.Text>
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
) : redeemDetail ? (
|
) : redeemDetail ? (
|
||||||
<Descriptions column={1} bordered size="small">
|
<RedeemRecordDetailDescriptions detail={redeemDetail} />
|
||||||
<Descriptions.Item label="核销号">{String(redeemDetail.redeemNo ?? '—')}</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="核销额">
|
|
||||||
¥{Number(redeemDetail.amount ?? 0).toFixed(2)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="结算额">
|
|
||||||
¥{Number(redeemDetail.settleAmount ?? 0).toFixed(2)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="时间">{fmtTime(String(redeemDetail.createdAt ?? ''))}</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="用户">
|
|
||||||
{String((redeemDetail.user as { userNo?: string } | undefined)?.userNo ?? '—')}
|
|
||||||
{(redeemDetail.user as { phone?: string | null } | undefined)?.phone
|
|
||||||
? ` / ${(redeemDetail.user as { phone?: string | null }).phone}`
|
|
||||||
: ''}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="门店">
|
|
||||||
{String((redeemDetail.store as { name?: string } | undefined)?.name ?? '—')}
|
|
||||||
{(redeemDetail.store as { cityName?: string } | undefined)?.cityName
|
|
||||||
? `(${(redeemDetail.store as { cityName?: string }).cityName})`
|
|
||||||
: ''}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="门店地址">
|
|
||||||
{String((redeemDetail.store as { address?: string } | undefined)?.address ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="合伙人">
|
|
||||||
{String(
|
|
||||||
(redeemDetail.store as { partnerAccount?: { companyName?: string } } | undefined)
|
|
||||||
?.partnerAccount?.companyName ?? '—',
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="权益券号">
|
|
||||||
{String((redeemDetail.coupon as { couponNo?: string } | undefined)?.couponNo ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="关联订单">
|
|
||||||
{String(
|
|
||||||
(redeemDetail.coupon as { order?: { orderNo?: string } } | undefined)?.order?.orderNo ??
|
|
||||||
'—',
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
{Array.isArray(redeemDetail.allocations) &&
|
|
||||||
(redeemDetail.allocations as unknown[]).length > 0 ? (
|
|
||||||
<Descriptions.Item label="券分摊">
|
|
||||||
{(
|
|
||||||
redeemDetail.allocations as Array<{
|
|
||||||
couponNo?: string;
|
|
||||||
orderNo?: string | null;
|
|
||||||
amount?: number;
|
|
||||||
sortOrder?: number;
|
|
||||||
}>
|
|
||||||
)
|
|
||||||
.map((a, idx) => {
|
|
||||||
const role = idx === 0 ? '主' : '次';
|
|
||||||
return `${role} ${a.couponNo ?? '—'}¥${Number(a.amount ?? 0).toFixed(2)}${
|
|
||||||
a.orderNo ? `(订单 ${a.orderNo})` : ''
|
|
||||||
}`;
|
|
||||||
})
|
|
||||||
.join(';')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
{redeemDetail.payout ? (
|
|
||||||
<Descriptions.Item label="门店结算单">
|
|
||||||
¥{Number((redeemDetail.payout as { settleAmount?: number }).settleAmount ?? 0).toFixed(2)}
|
|
||||||
{' / '}
|
|
||||||
{String((redeemDetail.payout as { status?: string }).status ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
{redeemDetail.rating ? (
|
|
||||||
<Descriptions.Item label="评价">
|
|
||||||
服务 {(redeemDetail.rating as { serviceScore?: number }).serviceScore ?? '—'} 分 / 环境{' '}
|
|
||||||
{(redeemDetail.rating as { envScore?: number }).envScore ?? '—'} 分
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
</Descriptions>
|
|
||||||
) : null}
|
) : null}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -16,10 +16,12 @@ import type { ColumnsType } from 'antd/es/table';
|
|||||||
import {
|
import {
|
||||||
DEV_PLAN_TASK_STATUS_LABELS,
|
DEV_PLAN_TASK_STATUS_LABELS,
|
||||||
DEV_PLAN_TASK_TYPE_LABELS,
|
DEV_PLAN_TASK_TYPE_LABELS,
|
||||||
|
SUPPORT_TICKET_STATUS_LABELS,
|
||||||
type DevPlanTaskDto,
|
type DevPlanTaskDto,
|
||||||
type DevPlanTaskStatusDto,
|
type DevPlanTaskStatusDto,
|
||||||
type DevPlanTaskTypeDto,
|
type DevPlanTaskTypeDto,
|
||||||
type DevPlanVersionDto,
|
type DevPlanVersionDto,
|
||||||
|
type SupportTicketDto,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
@@ -50,6 +52,7 @@ export default function DevPlanTasksPage() {
|
|||||||
const [batchEditOpen, setBatchEditOpen] = useState(false);
|
const [batchEditOpen, setBatchEditOpen] = useState(false);
|
||||||
const [batchSaving, setBatchSaving] = useState(false);
|
const [batchSaving, setBatchSaving] = useState(false);
|
||||||
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
||||||
|
const [supportTickets, setSupportTickets] = useState<SupportTicketDto[]>([]);
|
||||||
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [dispatching, setDispatching] = useState(false);
|
const [dispatching, setDispatching] = useState(false);
|
||||||
@@ -64,6 +67,13 @@ export default function DevPlanTasksPage() {
|
|||||||
.catch(() => setVersions([]));
|
.catch(() => setVersions([]));
|
||||||
}, [batchEditOpen]);
|
}, [batchEditOpen]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!modalOpen || editing) return;
|
||||||
|
request<{ items: SupportTicketDto[] }>('/admin/support-tickets?pageSize=100')
|
||||||
|
.then((res) => setSupportTickets(res.items ?? []))
|
||||||
|
.catch(() => setSupportTickets([]));
|
||||||
|
}, [modalOpen, editing]);
|
||||||
|
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<DevPlanTaskDto>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<DevPlanTaskDto>(
|
||||||
'/admin/dev-plan/tasks',
|
'/admin/dev-plan/tasks',
|
||||||
() => {
|
() => {
|
||||||
@@ -78,7 +88,7 @@ export default function DevPlanTasksPage() {
|
|||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
form.setFieldsValue({ content: '', type: 'BUG', status: 'TODO' });
|
form.setFieldsValue({ content: '', type: 'BUG', status: 'TODO', supportTicketId: undefined });
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +111,11 @@ export default function DevPlanTasksPage() {
|
|||||||
} else {
|
} else {
|
||||||
await request('/admin/dev-plan/tasks', {
|
await request('/admin/dev-plan/tasks', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ content: values.content, type: values.type }),
|
body: JSON.stringify({
|
||||||
|
content: values.content,
|
||||||
|
type: values.type,
|
||||||
|
supportTicketId: values.supportTicketId || undefined,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
}
|
}
|
||||||
@@ -305,7 +319,20 @@ export default function DevPlanTasksPage() {
|
|||||||
<Form.Item name="status" label="状态" rules={[{ required: true }]}>
|
<Form.Item name="status" label="状态" rules={[{ required: true }]}>
|
||||||
<Select options={STATUS_OPTIONS} />
|
<Select options={STATUS_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
) : null}
|
) : (
|
||||||
|
<Form.Item name="supportTicketId" label="绑定技术支持工单">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
placeholder="可选:关联工单"
|
||||||
|
options={supportTickets.map((t) => ({
|
||||||
|
value: t.id,
|
||||||
|
label: `${t.ticketNo} · ${SUPPORT_TICKET_STATUS_LABELS[t.status]} · ${t.title}`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
import { Button, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||||
|
import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
@@ -13,11 +14,16 @@ type Row = {
|
|||||||
settleAmount: number;
|
settleAmount: number;
|
||||||
channel?: RedeemChannel;
|
channel?: RedeemChannel;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
user?: { userNo: string; phone: string | null };
|
user?: { userNo: string; phone: string | null; nickname?: string | null };
|
||||||
store?: { name: string; cityName: string };
|
store?: { name: string; cityName: string };
|
||||||
coupon?: { couponNo: string };
|
coupon?: { couponNo: string };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function maskPhone(phone: string | null | undefined) {
|
||||||
|
if (!phone || phone.length < 7) return phone ?? '—';
|
||||||
|
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
||||||
|
}
|
||||||
|
|
||||||
export default function RedeemRecordsPage() {
|
export default function RedeemRecordsPage() {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
@@ -34,6 +40,17 @@ export default function RedeemRecordsPage() {
|
|||||||
);
|
);
|
||||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [detailLoading, setDetailLoading] = useState(false);
|
||||||
|
|
||||||
|
async function openDetail(id: string) {
|
||||||
|
setDetailLoading(true);
|
||||||
|
setDrawerOpen(true);
|
||||||
|
try {
|
||||||
|
setDetail(await request(`/admin/redeem-records/${id}`));
|
||||||
|
} finally {
|
||||||
|
setDetailLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const columns: ColumnsType<Row> = [
|
const columns: ColumnsType<Row> = [
|
||||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||||
@@ -50,7 +67,19 @@ export default function RedeemRecordsPage() {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ title: '用户', dataIndex: ['user', 'userNo'], width: 110 },
|
{ title: '用户编号', dataIndex: ['user', 'userNo'], width: 110 },
|
||||||
|
{
|
||||||
|
title: '用户昵称',
|
||||||
|
dataIndex: ['user', 'nickname'],
|
||||||
|
width: 100,
|
||||||
|
render: (v: string | null | undefined) => v || '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '用户手机',
|
||||||
|
dataIndex: ['user', 'phone'],
|
||||||
|
width: 120,
|
||||||
|
render: (v: string | null | undefined) => maskPhone(v),
|
||||||
|
},
|
||||||
{ title: '门店', dataIndex: ['store', 'name'] },
|
{ title: '门店', dataIndex: ['store', 'name'] },
|
||||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||||
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
|
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
|
||||||
@@ -60,14 +89,7 @@ export default function RedeemRecordsPage() {
|
|||||||
title: '操作',
|
title: '操作',
|
||||||
width: 80,
|
width: 80,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Button
|
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
||||||
type="link"
|
|
||||||
size="small"
|
|
||||||
onClick={async () => {
|
|
||||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
|
||||||
setDrawerOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
详情
|
详情
|
||||||
</Button>
|
</Button>
|
||||||
),
|
),
|
||||||
@@ -113,7 +135,7 @@ export default function RedeemRecordsPage() {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data?.items ?? []}
|
dataSource={data?.items ?? []}
|
||||||
scroll={{ x: 1100 }}
|
scroll={{ x: 1300 }}
|
||||||
pagination={{
|
pagination={{
|
||||||
current: page,
|
current: page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -125,22 +147,21 @@ export default function RedeemRecordsPage() {
|
|||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
|
<Drawer
|
||||||
{detail && (
|
title="核销详情"
|
||||||
<Descriptions column={1} bordered size="small">
|
width={640}
|
||||||
<Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
|
open={drawerOpen}
|
||||||
<Descriptions.Item label="方式">
|
onClose={() => {
|
||||||
{
|
setDrawerOpen(false);
|
||||||
REDEEM_CHANNEL_LABELS[
|
setDetail(null);
|
||||||
(detail.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel
|
}}
|
||||||
]
|
destroyOnClose
|
||||||
}
|
>
|
||||||
</Descriptions.Item>
|
{detailLoading ? (
|
||||||
<Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
) : detail ? (
|
||||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
<RedeemRecordDetailDescriptions detail={detail} />
|
||||||
</Descriptions>
|
) : null}
|
||||||
)}
|
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -376,7 +376,7 @@ type StoreRow = {
|
|||||||
visibilityWhitelistEnabled?: boolean;
|
visibilityWhitelistEnabled?: boolean;
|
||||||
visibilityPhones?: string[];
|
visibilityPhones?: string[];
|
||||||
cityRef?: { name: string; code: string };
|
cityRef?: { name: string; code: string };
|
||||||
partner?: { companyName: string };
|
partner?: { id?: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||||
account?: {
|
account?: {
|
||||||
phone: string;
|
phone: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -394,13 +394,14 @@ type StoreRow = {
|
|||||||
category?: { id: string; name: string; parentId?: string | null } | null;
|
category?: { id: string; name: string; parentId?: string | null } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PartnerOption = { id: string; companyName: string; name?: string };
|
type PartnerOption = { id: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||||
|
|
||||||
function partnerOptionLabel(p: PartnerOption): string {
|
function partnerOptionLabel(p: PartnerOption): string {
|
||||||
const company = (p.companyName || '').trim();
|
const company = (p.companyName || '').trim();
|
||||||
const person = (p.name || '').trim();
|
const person = (p.name || '').trim();
|
||||||
|
const phone = (p.phone || '').trim();
|
||||||
if (company && person) return `${company}-${person}`;
|
if (company && person) return `${company}-${person}`;
|
||||||
return company || person || p.id;
|
return company || person || phone || p.id;
|
||||||
}
|
}
|
||||||
type CityOption = {
|
type CityOption = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -867,7 +868,13 @@ export default function StoresPage() {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 120 },
|
{
|
||||||
|
title: '开城合伙人',
|
||||||
|
dataIndex: 'partner',
|
||||||
|
width: 140,
|
||||||
|
render: (partner: StoreRow['partner']) =>
|
||||||
|
partner ? partnerOptionLabel({ id: partner.id ?? '', ...partner }) : '—',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '可见',
|
title: '可见',
|
||||||
dataIndex: 'visibilityWhitelistEnabled',
|
dataIndex: 'visibilityWhitelistEnabled',
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import {
|
|||||||
DEV_PLAN_TASK_TYPE_LABELS,
|
DEV_PLAN_TASK_TYPE_LABELS,
|
||||||
SUPPORT_TICKET_STATUS_LABELS,
|
SUPPORT_TICKET_STATUS_LABELS,
|
||||||
SUPPORT_TICKET_TYPE_LABELS,
|
SUPPORT_TICKET_TYPE_LABELS,
|
||||||
|
SUPPORT_TICKET_PRIORITY_LABELS,
|
||||||
mapSupportTicketTypeToDevPlanTask,
|
mapSupportTicketTypeToDevPlanTask,
|
||||||
type BatchReviewPreviewItem,
|
type BatchReviewPreviewItem,
|
||||||
type BatchReviewPreviewResponse,
|
type BatchReviewPreviewResponse,
|
||||||
@@ -37,6 +38,7 @@ import {
|
|||||||
type DevPlanVersionDto,
|
type DevPlanVersionDto,
|
||||||
type SupportTicketDto,
|
type SupportTicketDto,
|
||||||
type SupportTicketLinkedTaskDto,
|
type SupportTicketLinkedTaskDto,
|
||||||
|
type SupportTicketPriorityDto,
|
||||||
type SupportTicketStatusDto,
|
type SupportTicketStatusDto,
|
||||||
type SupportTicketTypeDto,
|
type SupportTicketTypeDto,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -54,6 +56,7 @@ const STATUS_COLOR: Record<SupportTicketStatusDto, string> = {
|
|||||||
DEVELOPING: 'blue',
|
DEVELOPING: 'blue',
|
||||||
TESTING: 'purple',
|
TESTING: 'purple',
|
||||||
PASSED: 'green',
|
PASSED: 'green',
|
||||||
|
PUBLISHED: 'cyan',
|
||||||
};
|
};
|
||||||
|
|
||||||
const TYPE_OPTIONS = (Object.keys(SUPPORT_TICKET_TYPE_LABELS) as SupportTicketTypeDto[]).map(
|
const TYPE_OPTIONS = (Object.keys(SUPPORT_TICKET_TYPE_LABELS) as SupportTicketTypeDto[]).map(
|
||||||
@@ -64,6 +67,17 @@ const STATUS_OPTIONS = (Object.keys(SUPPORT_TICKET_STATUS_LABELS) as SupportTick
|
|||||||
(value) => ({ value, label: SUPPORT_TICKET_STATUS_LABELS[value] }),
|
(value) => ({ value, label: SUPPORT_TICKET_STATUS_LABELS[value] }),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const PRIORITY_COLOR: Record<SupportTicketPriorityDto, string> = {
|
||||||
|
LOW: 'default',
|
||||||
|
NORMAL: 'blue',
|
||||||
|
HIGH: 'orange',
|
||||||
|
URGENT: 'red',
|
||||||
|
};
|
||||||
|
|
||||||
|
const PRIORITY_OPTIONS = (Object.keys(SUPPORT_TICKET_PRIORITY_LABELS) as SupportTicketPriorityDto[]).map(
|
||||||
|
(value) => ({ value, label: SUPPORT_TICKET_PRIORITY_LABELS[value] }),
|
||||||
|
);
|
||||||
|
|
||||||
const TASK_TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map(
|
const TASK_TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map(
|
||||||
(v) => ({ value: v, label: DEV_PLAN_TASK_TYPE_LABELS[v] }),
|
(v) => ({ value: v, label: DEV_PLAN_TASK_TYPE_LABELS[v] }),
|
||||||
);
|
);
|
||||||
@@ -80,6 +94,7 @@ export default function SupportTicketsPage() {
|
|||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (filters.ticketType) qs.set('ticketType', filters.ticketType);
|
if (filters.ticketType) qs.set('ticketType', filters.ticketType);
|
||||||
if (filters.status) qs.set('status', filters.status);
|
if (filters.status) qs.set('status', filters.status);
|
||||||
|
if (filters.priority) qs.set('priority', filters.priority);
|
||||||
return qs;
|
return qs;
|
||||||
},
|
},
|
||||||
[filters],
|
[filters],
|
||||||
@@ -154,6 +169,7 @@ export default function SupportTicketsPage() {
|
|||||||
title: values.title.trim(),
|
title: values.title.trim(),
|
||||||
content: values.content?.trim() || undefined,
|
content: values.content?.trim() || undefined,
|
||||||
remark: values.remark?.trim() || undefined,
|
remark: values.remark?.trim() || undefined,
|
||||||
|
priority: values.priority,
|
||||||
attachmentUrls: (values.attachmentUrls ?? []).map((u: string) => u?.trim()).filter(Boolean),
|
attachmentUrls: (values.attachmentUrls ?? []).map((u: string) => u?.trim()).filter(Boolean),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -217,6 +233,7 @@ export default function SupportTicketsPage() {
|
|||||||
title: detail.title,
|
title: detail.title,
|
||||||
content: detail.content || '',
|
content: detail.content || '',
|
||||||
remark: detail.remark || '',
|
remark: detail.remark || '',
|
||||||
|
priority: detail.priority ?? 'NORMAL',
|
||||||
attachmentUrls: detail.attachmentUrls?.length ? detail.attachmentUrls : [''],
|
attachmentUrls: detail.attachmentUrls?.length ? detail.attachmentUrls : [''],
|
||||||
});
|
});
|
||||||
setEditOpen(true);
|
setEditOpen(true);
|
||||||
@@ -233,6 +250,7 @@ export default function SupportTicketsPage() {
|
|||||||
title: values.title.trim(),
|
title: values.title.trim(),
|
||||||
content: values.content?.trim() || undefined,
|
content: values.content?.trim() || undefined,
|
||||||
remark: values.remark?.trim() || undefined,
|
remark: values.remark?.trim() || undefined,
|
||||||
|
priority: values.priority,
|
||||||
attachmentUrls: (values.attachmentUrls ?? []).map((u: string) => u?.trim()).filter(Boolean),
|
attachmentUrls: (values.attachmentUrls ?? []).map((u: string) => u?.trim()).filter(Boolean),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -451,12 +469,29 @@ export default function SupportTicketsPage() {
|
|||||||
width: 90,
|
width: 90,
|
||||||
render: (t: SupportTicketTypeDto) => SUPPORT_TICKET_TYPE_LABELS[t] ?? t,
|
render: (t: SupportTicketTypeDto) => SUPPORT_TICKET_TYPE_LABELS[t] ?? t,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: '优先级',
|
||||||
|
dataIndex: 'priority',
|
||||||
|
width: 90,
|
||||||
|
render: (p: SupportTicketPriorityDto) => (
|
||||||
|
<Tag color={PRIORITY_COLOR[p] ?? 'default'}>
|
||||||
|
{SUPPORT_TICKET_PRIORITY_LABELS[p] ?? p ?? '普通'}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 100,
|
width: 100,
|
||||||
render: (s: SupportTicketStatusDto) => (
|
render: (s: SupportTicketStatusDto, row) => (
|
||||||
<Tag color={STATUS_COLOR[s]}>{SUPPORT_TICKET_STATUS_LABELS[s] ?? s}</Tag>
|
<Space size={4} direction="vertical" style={{ lineHeight: 1.2 }}>
|
||||||
|
<Tag color={STATUS_COLOR[s]}>{SUPPORT_TICKET_STATUS_LABELS[s] ?? s}</Tag>
|
||||||
|
{row.releasedVersionNo ? (
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||||
|
{row.releasedVersionNo}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{ title: '标题', dataIndex: 'title', ellipsis: true },
|
{ title: '标题', dataIndex: 'title', ellipsis: true },
|
||||||
@@ -562,6 +597,9 @@ export default function SupportTicketsPage() {
|
|||||||
<Form.Item name="status" label="状态">
|
<Form.Item name="status" label="状态">
|
||||||
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item name="priority" label="优先级">
|
||||||
|
<Select allowClear style={{ width: 120 }} options={PRIORITY_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
<Button type="primary" htmlType="submit">
|
<Button type="primary" htmlType="submit">
|
||||||
筛选
|
筛选
|
||||||
</Button>
|
</Button>
|
||||||
@@ -577,11 +615,7 @@ export default function SupportTicketsPage() {
|
|||||||
isSuperAdmin
|
isSuperAdmin
|
||||||
? {
|
? {
|
||||||
selectedRowKeys,
|
selectedRowKeys,
|
||||||
onChange: (keys, rows) => {
|
onChange: (keys) => setSelectedRowKeys(keys as string[]),
|
||||||
const pending = rows.filter((r) => r.status === 'PENDING_REVIEW').map((r) => String(r.id));
|
|
||||||
setSelectedRowKeys(pending.length === rows.length ? (keys as string[]) : pending);
|
|
||||||
},
|
|
||||||
getCheckboxProps: (row) => ({ disabled: row.status !== 'PENDING_REVIEW' }),
|
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
@@ -607,6 +641,9 @@ export default function SupportTicketsPage() {
|
|||||||
{detail.ticketNo}
|
{detail.ticketNo}
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
<Tag>{SUPPORT_TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}</Tag>
|
<Tag>{SUPPORT_TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}</Tag>
|
||||||
|
<Tag color={PRIORITY_COLOR[detail.priority ?? 'NORMAL']}>
|
||||||
|
{SUPPORT_TICKET_PRIORITY_LABELS[detail.priority ?? 'NORMAL']}
|
||||||
|
</Tag>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
@@ -637,6 +674,11 @@ export default function SupportTicketsPage() {
|
|||||||
{detail.status === 'PASSED' && (
|
{detail.status === 'PASSED' && (
|
||||||
<Typography.Text type="success">此工单已测试通过</Typography.Text>
|
<Typography.Text type="success">此工单已测试通过</Typography.Text>
|
||||||
)}
|
)}
|
||||||
|
{detail.status === 'PUBLISHED' && (
|
||||||
|
<Typography.Text type="success">
|
||||||
|
已发布{detail.releasedVersionNo ? ` · ${detail.releasedVersionNo}` : ''}
|
||||||
|
</Typography.Text>
|
||||||
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
创建于 {fmtTime(detail.createdAt)}
|
创建于 {fmtTime(detail.createdAt)}
|
||||||
@@ -660,6 +702,7 @@ export default function SupportTicketsPage() {
|
|||||||
{ key: 'DEVELOPING' as SupportTicketStatusDto, label: '开发中', time: detail.reviewedAt },
|
{ key: 'DEVELOPING' as SupportTicketStatusDto, label: '开发中', time: detail.reviewedAt },
|
||||||
{ key: 'TESTING' as SupportTicketStatusDto, label: '测试中', time: null },
|
{ key: 'TESTING' as SupportTicketStatusDto, label: '测试中', time: null },
|
||||||
{ key: 'PASSED' as SupportTicketStatusDto, label: '已通过', time: detail.completedAt },
|
{ key: 'PASSED' as SupportTicketStatusDto, label: '已通过', time: detail.completedAt },
|
||||||
|
{ key: 'PUBLISHED' as SupportTicketStatusDto, label: '已发布', time: detail.publishedAt },
|
||||||
]
|
]
|
||||||
: [{ key: 'REJECTED' as SupportTicketStatusDto, label: '已驳回', time: detail.reviewedAt }]),
|
: [{ key: 'REJECTED' as SupportTicketStatusDto, label: '已驳回', time: detail.reviewedAt }]),
|
||||||
];
|
];
|
||||||
@@ -865,10 +908,13 @@ export default function SupportTicketsPage() {
|
|||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
<Modal title="创建技术支持工单" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={() => void submitCreate()} confirmLoading={creating} destroyOnClose okText="提交">
|
<Modal title="创建技术支持工单" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={() => void submitCreate()} confirmLoading={creating} destroyOnClose okText="提交">
|
||||||
<Form form={createForm} layout="vertical" initialValues={{ ticketType: 'BUG', attachmentUrls: [''] }}>
|
<Form form={createForm} layout="vertical" initialValues={{ ticketType: 'BUG', priority: 'NORMAL', attachmentUrls: [''] }}>
|
||||||
<Form.Item name="ticketType" label="类型" rules={[{ required: true }]}>
|
<Form.Item name="ticketType" label="类型" rules={[{ required: true }]}>
|
||||||
<Select options={TYPE_OPTIONS} />
|
<Select options={TYPE_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item name="priority" label="优先级" rules={[{ required: true }]}>
|
||||||
|
<Select options={PRIORITY_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
||||||
<Input maxLength={128} showCount />
|
<Input maxLength={128} showCount />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -972,6 +1018,9 @@ export default function SupportTicketsPage() {
|
|||||||
<Form.Item name="ticketType" label="类型" rules={[{ required: true }]}>
|
<Form.Item name="ticketType" label="类型" rules={[{ required: true }]}>
|
||||||
<Select options={TYPE_OPTIONS} />
|
<Select options={TYPE_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<Form.Item name="priority" label="优先级" rules={[{ required: true }]}>
|
||||||
|
<Select options={PRIORITY_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
||||||
<Input maxLength={128} showCount />
|
<Input maxLength={128} showCount />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|||||||
@@ -10,11 +10,18 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Table,
|
Table,
|
||||||
|
Tag,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { TICKET_TYPE_LABELS, type TicketTypeDto } from '@dukang/shared-types';
|
import {
|
||||||
|
TICKET_STATUS_LABELS,
|
||||||
|
TICKET_TYPE_LABELS,
|
||||||
|
ticketStatusLabel,
|
||||||
|
type TicketStatusDto,
|
||||||
|
type TicketTypeDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
@@ -31,6 +38,21 @@ type Row = {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const STATUS_COLOR: Partial<Record<TicketStatusDto, string>> = {
|
||||||
|
PENDING: 'orange',
|
||||||
|
OPEN: 'blue',
|
||||||
|
COLLABORATING: 'cyan',
|
||||||
|
RESOLVED: 'green',
|
||||||
|
REJECTED: 'red',
|
||||||
|
COMPLETED: 'green',
|
||||||
|
CLOSED: 'default',
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = (Object.keys(TICKET_STATUS_LABELS) as TicketStatusDto[]).map((value) => ({
|
||||||
|
value,
|
||||||
|
label: TICKET_STATUS_LABELS[value],
|
||||||
|
}));
|
||||||
|
|
||||||
export default function TicketsPage() {
|
export default function TicketsPage() {
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||||
@@ -101,7 +123,14 @@ export default function TicketsPage() {
|
|||||||
width: 110,
|
width: 110,
|
||||||
render: (t: TicketTypeDto) => TICKET_TYPE_LABELS[t] ?? t,
|
render: (t: TicketTypeDto) => TICKET_TYPE_LABELS[t] ?? t,
|
||||||
},
|
},
|
||||||
{ title: '状态', dataIndex: 'status', width: 90 },
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 100,
|
||||||
|
render: (s: string) => (
|
||||||
|
<Tag color={STATUS_COLOR[s as TicketStatusDto] ?? 'default'}>{ticketStatusLabel(s)}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
{ title: '关联', width: 140, render: (_, r) => `${r.refType}#${r.refId}` },
|
{ title: '关联', width: 140, render: (_, r) => `${r.refType}#${r.refId}` },
|
||||||
{ title: '备注', dataIndex: 'remark', ellipsis: true },
|
{ title: '备注', dataIndex: 'remark', ellipsis: true },
|
||||||
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
@@ -165,7 +194,7 @@ export default function TicketsPage() {
|
|||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="status" label="状态">
|
<Form.Item name="status" label="状态">
|
||||||
<Input allowClear placeholder="PENDING" />
|
<Select allowClear style={{ width: 140 }} placeholder="全部" options={STATUS_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Button type="primary" htmlType="submit">
|
<Button type="primary" htmlType="submit">
|
||||||
筛选
|
筛选
|
||||||
@@ -212,7 +241,11 @@ export default function TicketsPage() {
|
|||||||
<Descriptions.Item label="类型">
|
<Descriptions.Item label="类型">
|
||||||
{TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
|
{TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="状态">{String(detail.status)}</Descriptions.Item>
|
<Descriptions.Item label="状态">
|
||||||
|
<Tag color={STATUS_COLOR[detail.status as TicketStatusDto] ?? 'default'}>
|
||||||
|
{ticketStatusLabel(detail.status)}
|
||||||
|
</Tag>
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="关联">
|
<Descriptions.Item label="关联">
|
||||||
{String(detail.refType)} #{String(detail.refId)}
|
{String(detail.refType)} #{String(detail.refId)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
|||||||
@@ -258,7 +258,7 @@ export default function WineryBillsPage() {
|
|||||||
酒厂对账单
|
酒厂对账单
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
每日 8:00 汇总昨日已付订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
</Space>
|
</Space>
|
||||||
{canEditWineryBank ? (
|
{canEditWineryBank ? (
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
import { request } from '../../lib/api';
|
import { request } from '../../lib/api';
|
||||||
import { fmtTime } from '../../lib/constants';
|
import { fmtTime } from '../../lib/constants';
|
||||||
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';
|
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';
|
||||||
|
import PromoCodeMetricsPanel from './PromoCodeMetricsPanel';
|
||||||
|
|
||||||
const descLabelStyle: CSSProperties = {
|
const descLabelStyle: CSSProperties = {
|
||||||
whiteSpace: 'nowrap',
|
whiteSpace: 'nowrap',
|
||||||
@@ -212,6 +213,14 @@ export default function PromoCodeDetailPage() {
|
|||||||
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
|
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</Col>
|
||||||
|
<Col xs={12} sm={6}>
|
||||||
|
<Card size="small">
|
||||||
|
<Statistic
|
||||||
|
title="归因用户数"
|
||||||
|
value={stats?.attributionCount ?? 0}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
<Col xs={12} sm={6}>
|
<Col xs={12} sm={6}>
|
||||||
<Card size="small">
|
<Card size="small">
|
||||||
<Statistic
|
<Statistic
|
||||||
@@ -235,6 +244,8 @@ export default function PromoCodeDetailPage() {
|
|||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
|
|
||||||
|
<PromoCodeMetricsPanel promoId={detail.id} />
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
title="编辑推广码"
|
title="编辑推广码"
|
||||||
open={editOpen}
|
open={editOpen}
|
||||||
|
|||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
DatePicker,
|
||||||
|
Radio,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
|
import ReactECharts from 'echarts-for-react';
|
||||||
|
import type { EChartsOption } from 'echarts';
|
||||||
|
import {
|
||||||
|
PROMO_METRIC_EVENT_LABELS,
|
||||||
|
type PromoMetricEventItem,
|
||||||
|
type PromoMetricEventType,
|
||||||
|
type PromoMetricTimelineDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request, type Paginated } from '../../lib/api';
|
||||||
|
import { fmtTime } from '../../lib/constants';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
promoId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SERIES = [
|
||||||
|
{ key: 'scan', name: '扫码进入', color: '#1677ff' },
|
||||||
|
{ key: 'attribution', name: '归因用户', color: '#52c41a' },
|
||||||
|
{ key: 'register', name: '扫码注册', color: '#faad14' },
|
||||||
|
{ key: 'order', name: '订单', color: '#eb2f96' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function buildTimelineQs(promoId: string, range: [Dayjs, Dayjs], granularity: 'day' | 'hour') {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('dateFrom', range[0].format('YYYY-MM-DD'));
|
||||||
|
qs.set('dateTo', range[1].format('YYYY-MM-DD'));
|
||||||
|
qs.set('granularity', granularity);
|
||||||
|
return `/admin/promo-codes/${promoId}/metrics/timeline?${qs.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEventsQs(
|
||||||
|
promoId: string,
|
||||||
|
page: number,
|
||||||
|
pageSize: number,
|
||||||
|
range: [Dayjs, Dayjs],
|
||||||
|
eventType?: PromoMetricEventType,
|
||||||
|
) {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('page', String(page));
|
||||||
|
qs.set('pageSize', String(pageSize));
|
||||||
|
qs.set('dateFrom', range[0].format('YYYY-MM-DD'));
|
||||||
|
qs.set('dateTo', range[1].format('YYYY-MM-DD'));
|
||||||
|
if (eventType) qs.set('eventType', eventType);
|
||||||
|
return `/admin/promo-codes/${promoId}/metrics/events?${qs.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRefId(row: PromoMetricEventItem): string {
|
||||||
|
if (row.orderId) return `订单 ${row.orderId}`;
|
||||||
|
if (row.userId) return `用户 ${row.userId}`;
|
||||||
|
if (row.sessionId) return `会话 ${row.sessionId}`;
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatLocation(row: PromoMetricEventItem): string {
|
||||||
|
const parts = [row.ipProvince, row.ipCity].filter(Boolean);
|
||||||
|
if (parts.length) return parts.join(' ');
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PromoCodeMetricsPanel({ promoId }: Props) {
|
||||||
|
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(6, 'day'), dayjs()]);
|
||||||
|
const [granularity, setGranularity] = useState<'day' | 'hour'>('day');
|
||||||
|
const [timeline, setTimeline] = useState<PromoMetricTimelineDto | null>(null);
|
||||||
|
const [timelineLoading, setTimelineLoading] = useState(false);
|
||||||
|
const [eventType, setEventType] = useState<PromoMetricEventType | undefined>();
|
||||||
|
const [eventsPage, setEventsPage] = useState(1);
|
||||||
|
const [events, setEvents] = useState<Paginated<PromoMetricEventItem> | null>(null);
|
||||||
|
const [eventsLoading, setEventsLoading] = useState(false);
|
||||||
|
|
||||||
|
const loadTimeline = useCallback(() => {
|
||||||
|
setTimelineLoading(true);
|
||||||
|
return request<PromoMetricTimelineDto>(buildTimelineQs(promoId, range, granularity))
|
||||||
|
.then(setTimeline)
|
||||||
|
.catch((e) => {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载趋势失败');
|
||||||
|
setTimeline(null);
|
||||||
|
})
|
||||||
|
.finally(() => setTimelineLoading(false));
|
||||||
|
}, [promoId, range, granularity]);
|
||||||
|
|
||||||
|
const loadEvents = useCallback(() => {
|
||||||
|
setEventsLoading(true);
|
||||||
|
return request<Paginated<PromoMetricEventItem>>(
|
||||||
|
buildEventsQs(promoId, eventsPage, 20, range, eventType),
|
||||||
|
)
|
||||||
|
.then(setEvents)
|
||||||
|
.catch((e) => {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载事件失败');
|
||||||
|
setEvents(null);
|
||||||
|
})
|
||||||
|
.finally(() => setEventsLoading(false));
|
||||||
|
}, [promoId, eventsPage, range, eventType]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadTimeline();
|
||||||
|
}, [loadTimeline]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadEvents();
|
||||||
|
}, [loadEvents]);
|
||||||
|
|
||||||
|
const chartOption = useMemo<EChartsOption>(() => {
|
||||||
|
const buckets = timeline?.buckets ?? [];
|
||||||
|
const xData = buckets.map((b) => b.key);
|
||||||
|
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { data: SERIES.map((s) => s.name), bottom: 0 },
|
||||||
|
grid: { left: 48, right: 24, top: 24, bottom: 48 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: xData,
|
||||||
|
axisLabel: {
|
||||||
|
rotate: granularity === 'hour' ? 45 : 0,
|
||||||
|
formatter: (v: string) => (granularity === 'hour' ? v.slice(5, 16) : v.slice(5)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value', minInterval: 1 },
|
||||||
|
series: SERIES.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
type: 'line',
|
||||||
|
smooth: true,
|
||||||
|
data: buckets.map((b) => b[s.key]),
|
||||||
|
itemStyle: { color: s.color },
|
||||||
|
markPoint: {
|
||||||
|
symbol: 'pin',
|
||||||
|
symbolSize: 42,
|
||||||
|
data: (() => {
|
||||||
|
const peak = timeline?.peak[s.key];
|
||||||
|
if (!peak || peak.count <= 0) return [];
|
||||||
|
return [{ name: '高峰', coord: [peak.key, peak.count], value: peak.count }];
|
||||||
|
})(),
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}, [timeline, granularity]);
|
||||||
|
|
||||||
|
const columns: ColumnsType<PromoMetricEventItem> = [
|
||||||
|
{
|
||||||
|
title: '时间',
|
||||||
|
dataIndex: 'createdAt',
|
||||||
|
width: 168,
|
||||||
|
render: (v: string) => fmtTime(v),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '类型',
|
||||||
|
dataIndex: 'eventType',
|
||||||
|
width: 108,
|
||||||
|
render: (v: PromoMetricEventType) => PROMO_METRIC_EVENT_LABELS[v],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'ID',
|
||||||
|
key: 'ref',
|
||||||
|
render: (_, row) => formatRefId(row),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'IP',
|
||||||
|
dataIndex: 'clientIp',
|
||||||
|
width: 128,
|
||||||
|
render: (v: string | null) => v ?? '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '地点',
|
||||||
|
key: 'location',
|
||||||
|
width: 120,
|
||||||
|
render: (_, row) => formatLocation(row),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
title="数据趋势"
|
||||||
|
style={{ marginTop: 16 }}
|
||||||
|
extra={
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
仅统计功能上线后的新事件
|
||||||
|
</Typography.Text>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
|
<DatePicker.RangePicker
|
||||||
|
value={range}
|
||||||
|
onChange={(v) => {
|
||||||
|
if (v?.[0] && v[1]) {
|
||||||
|
setRange([v[0], v[1]]);
|
||||||
|
setEventsPage(1);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
allowClear={false}
|
||||||
|
/>
|
||||||
|
<Radio.Group
|
||||||
|
value={granularity}
|
||||||
|
onChange={(e) => setGranularity(e.target.value as 'day' | 'hour')}
|
||||||
|
optionType="button"
|
||||||
|
buttonStyle="solid"
|
||||||
|
options={[
|
||||||
|
{ label: '按日', value: 'day' },
|
||||||
|
{ label: '按时', value: 'hour' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
|
||||||
|
<ReactECharts
|
||||||
|
option={chartOption}
|
||||||
|
style={{ height: 360 }}
|
||||||
|
showLoading={timelineLoading}
|
||||||
|
notMerge
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Typography.Title level={5} style={{ marginTop: 24, marginBottom: 12 }}>
|
||||||
|
事件日志
|
||||||
|
</Typography.Title>
|
||||||
|
<Space wrap style={{ marginBottom: 12 }}>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部类型"
|
||||||
|
style={{ width: 160 }}
|
||||||
|
value={eventType}
|
||||||
|
onChange={(v) => {
|
||||||
|
setEventType(v);
|
||||||
|
setEventsPage(1);
|
||||||
|
}}
|
||||||
|
options={Object.entries(PROMO_METRIC_EVENT_LABELS).map(([value, label]) => ({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
size="small"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={events?.items ?? []}
|
||||||
|
loading={eventsLoading}
|
||||||
|
pagination={{
|
||||||
|
current: eventsPage,
|
||||||
|
pageSize: events?.pageSize ?? 20,
|
||||||
|
total: events?.total ?? 0,
|
||||||
|
showSizeChanger: false,
|
||||||
|
onChange: (p) => setEventsPage(p),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -19,8 +19,6 @@ type OssUploadFieldProps = {
|
|||||||
onWechatReadyChange?: (ready: boolean) => void;
|
onWechatReadyChange?: (ready: boolean) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MAX_MB = 10;
|
|
||||||
|
|
||||||
function isCancelError(msg: string): boolean {
|
function isCancelError(msg: string): boolean {
|
||||||
return /cancel|取消/i.test(msg);
|
return /cancel|取消/i.test(msg);
|
||||||
}
|
}
|
||||||
@@ -79,10 +77,6 @@ export default function OssUploadField({
|
|||||||
showUploadError('图片读取失败,请重新选择');
|
showUploadError('图片读取失败,请重新选择');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.size > DEFAULT_MAX_MB * 1024 * 1024) {
|
|
||||||
showUploadError(`文件不能超过 ${DEFAULT_MAX_MB}MB`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const result = await uploadFileToOss(file, { bizType, mediaType });
|
const result = await uploadFileToOss(file, { bizType, mediaType });
|
||||||
onChange?.(result.url);
|
onChange?.(result.url);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase, request } from './api';
|
import { apiBase, request } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
const UPLOAD_TIMEOUT_MS = 120_000;
|
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||||
|
|
||||||
@@ -11,13 +16,23 @@ export type UploadFileResult = {
|
|||||||
mock: boolean;
|
mock: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async function prepareUploadFile(file: File, mediaType: OssMediaType): Promise<File> {
|
||||||
|
if (mediaType !== 'IMAGE') return file;
|
||||||
|
const compressed = await compressImageFileIfNeeded(file);
|
||||||
|
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||||
|
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||||
|
}
|
||||||
|
return compressed;
|
||||||
|
}
|
||||||
|
|
||||||
async function uploadFileToOssInner(
|
async function uploadFileToOssInner(
|
||||||
file: File,
|
file: File,
|
||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||||
|
const prepared = await prepareUploadFile(file, mediaType);
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,19 @@ export async function canPartnerUseWechatLogin(options: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 短信登录/发码前:校验手机号对应合伙人存在且未暂停 */
|
||||||
|
export async function checkPartnerPhoneForLogin(phone: string): Promise<PartnerPhoneCheckResponse> {
|
||||||
|
const normalized = phone.trim();
|
||||||
|
if (!/^1\d{10}$/.test(normalized)) {
|
||||||
|
throw new Error('请输入正确的手机号');
|
||||||
|
}
|
||||||
|
return request<PartnerPhoneCheckResponse>('PARTNER_H5', '/partner/auth/phone/check', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ phone: normalized }),
|
||||||
|
silent: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
||||||
return request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config');
|
return request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ import {
|
|||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||||
import { partnerHomePath } from '../lib/partnerAccess';
|
import { partnerHomePath } from '../lib/partnerAccess';
|
||||||
|
import type { PartnerPhoneCheckResponse } from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
bindPartnerWechatAfterSmsLogin,
|
bindPartnerWechatAfterSmsLogin,
|
||||||
|
checkPartnerPhoneForLogin,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
loginPartnerWithWechat,
|
loginPartnerWithWechat,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
@@ -69,14 +71,17 @@ function formatPartnerError(e: unknown): string {
|
|||||||
if (text.includes('合伙人账号不存在') || text.includes('未找到合伙人账号')) {
|
if (text.includes('合伙人账号不存在') || text.includes('未找到合伙人账号')) {
|
||||||
return '未找到合伙人账号';
|
return '未找到合伙人账号';
|
||||||
}
|
}
|
||||||
if (text.includes('合伙人账号已停用')) {
|
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||||
return '合伙人账号已停用';
|
return '合伙人账号已暂停,无法登录';
|
||||||
}
|
}
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatWechatError(e: unknown): string {
|
function formatWechatError(e: unknown): string {
|
||||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||||
|
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||||
|
return '合伙人账号已暂停,无法登录';
|
||||||
|
}
|
||||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||||
}
|
}
|
||||||
@@ -138,11 +143,21 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function sendCode() {
|
async function sendCode() {
|
||||||
if (!ensureAgreed()) return;
|
if (!ensureAgreed()) return;
|
||||||
|
const trimmedPhone = phone.trim();
|
||||||
|
if (!trimmedPhone) {
|
||||||
|
setMsg('请输入手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^1\d{10}$/.test(trimmedPhone)) {
|
||||||
|
setMsg('请输入正确的手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
await checkPartnerPhoneForLogin(trimmedPhone);
|
||||||
await request('PARTNER_H5', '/partner/auth/sms/send', {
|
await request('PARTNER_H5', '/partner/auth/sms/send', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, scene: 'PARTNER_LOGIN' }),
|
body: JSON.stringify({ phone: trimmedPhone, scene: 'PARTNER_LOGIN' }),
|
||||||
silent: true,
|
silent: true,
|
||||||
});
|
});
|
||||||
setMsg('验证码已发送');
|
setMsg('验证码已发送');
|
||||||
@@ -168,12 +183,27 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function login() {
|
async function login() {
|
||||||
if (!ensureAgreed()) return;
|
if (!ensureAgreed()) return;
|
||||||
|
const trimmedPhone = phone.trim();
|
||||||
|
const trimmedCode = code.trim();
|
||||||
|
if (!trimmedPhone) {
|
||||||
|
setMsg('请输入手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^1\d{10}$/.test(trimmedPhone)) {
|
||||||
|
setMsg('请输入正确的手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!trimmedCode) {
|
||||||
|
setMsg('请输入验证码');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
await checkPartnerPhoneForLogin(trimmedPhone);
|
||||||
const data = await request<PartnerSessionPayload>('PARTNER_H5', '/partner/auth/login/sms', {
|
const data = await request<PartnerSessionPayload>('PARTNER_H5', '/partner/auth/login/sms', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, code }),
|
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||||
silent: true,
|
silent: true,
|
||||||
});
|
});
|
||||||
saveRememberedSession(data);
|
saveRememberedSession(data);
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallback,
|
||||||
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
isShopWechatUnboundError,
|
isShopWechatUnboundError,
|
||||||
SHOP_WX_NEED_PHONE_LOGIN_MSG,
|
SHOP_WX_NEED_PHONE_LOGIN_MSG,
|
||||||
@@ -79,7 +80,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
const config = await fetchClientConfig();
|
const config = await fetchClientConfig();
|
||||||
if (isWxAuthorizeEnabled(config)) {
|
if (isWxAuthorizeEnabled(config)) {
|
||||||
const result = await handleShopWechatCallback();
|
const result = await handleShopWechatCallbackOnce();
|
||||||
if (result && !cancelled) {
|
if (result && !cancelled) {
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
if (session) applySession(session);
|
if (session) applySession(session);
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { isIosDevice } from '@dukang/weixin-sdk';
|
||||||
|
|
||||||
|
/** 扫码前发起 OAuth 时标记,回跳后在首页续扫 */
|
||||||
|
export const SHOP_PENDING_SCAN_KEY = 'shop_pending_scan';
|
||||||
|
|
||||||
|
export function markPendingScanAfterAuth(): void {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(SHOP_PENDING_SCAN_KEY, '1');
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function peekPendingScanAfterAuth(): boolean {
|
||||||
|
try {
|
||||||
|
return sessionStorage.getItem(SHOP_PENDING_SCAN_KEY) === '1';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearPendingScanAfterAuth(): void {
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem(SHOP_PENDING_SCAN_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** OAuth 回跳后延迟再调 scanQRCode(iOS JSSDK 离线校验更慢) */
|
||||||
|
export function getPostAuthScanDelayMs(): number {
|
||||||
|
return isIosDevice() ? 1200 : 600;
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
import { apiBase } from './api';
|
import { apiBase } from './api';
|
||||||
import { getStoreProfile } from './api';
|
import { getStoreProfile } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
const UPLOAD_TIMEOUT_MS = 120_000;
|
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||||
|
|
||||||
@@ -16,8 +21,12 @@ export type RegisteredResource = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export async function uploadFileToOss(file: File, bizType: string): Promise<UploadFileResult> {
|
export async function uploadFileToOss(file: File, bizType: string): Promise<UploadFileResult> {
|
||||||
|
const compressed = await compressImageFileIfNeeded(file);
|
||||||
|
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||||
|
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||||
|
}
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', compressed);
|
||||||
formData.append('bizType', bizType);
|
formData.append('bizType', bizType);
|
||||||
formData.append('mediaType', 'IMAGE');
|
formData.append('mediaType', 'IMAGE');
|
||||||
|
|
||||||
|
|||||||
@@ -138,6 +138,20 @@ export async function handleShopWechatCallback(): Promise<WechatLoginResult | nu
|
|||||||
return weixinSdk.handleOAuthCallback();
|
return weixinSdk.handleOAuthCallback();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let oauthCallbackInflight: Promise<WechatLoginResult | null> | null = null;
|
||||||
|
|
||||||
|
/** 全局单例:避免 Context 与页面 effect 重复消费 OAuth code */
|
||||||
|
export async function handleShopWechatCallbackOnce(): Promise<WechatLoginResult | null> {
|
||||||
|
if (!isWechatEnv()) return null;
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
if (!params.get('code')) return null;
|
||||||
|
if (oauthCallbackInflight) return oauthCallbackInflight;
|
||||||
|
oauthCallbackInflight = handleShopWechatCallback().finally(() => {
|
||||||
|
oauthCallbackInflight = null;
|
||||||
|
});
|
||||||
|
return oauthCallbackInflight;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 微信一键登录(已绑定微信的门店账号免验证码)。
|
* 微信一键登录(已绑定微信的门店账号免验证码)。
|
||||||
* 返回 session = 已登录;void = 已跳转授权页等待回调。
|
* 返回 session = 已登录;void = 已跳转授权页等待回调。
|
||||||
|
|||||||
@@ -1,285 +1,585 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
|
|
||||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||||
|
|
||||||
|
import { isScanPermissionWarmupError } from '@dukang/weixin-sdk';
|
||||||
|
|
||||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||||
|
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
|
|
||||||
import { parseRedeemTokenFromScan } from '../lib/redeem-scan';
|
import { parseRedeemTokenFromScan } from '../lib/redeem-scan';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
|
||||||
authorizeShopWechat,
|
authorizeShopWechat,
|
||||||
|
|
||||||
checkNeedsWechatAuth,
|
checkNeedsWechatAuth,
|
||||||
|
|
||||||
fetchShopAccount,
|
fetchShopAccount,
|
||||||
handleShopWechatCallback,
|
|
||||||
handleShopWechatLoginResult,
|
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
|
|
||||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
|
||||||
|
import {
|
||||||
|
|
||||||
|
clearPendingScanAfterAuth,
|
||||||
|
|
||||||
|
getPostAuthScanDelayMs,
|
||||||
|
|
||||||
|
markPendingScanAfterAuth,
|
||||||
|
|
||||||
|
peekPendingScanAfterAuth,
|
||||||
|
|
||||||
|
} from '../lib/shop-scan-auth';
|
||||||
|
|
||||||
import WechatScanAuthModal from '../components/WechatScanAuthModal';
|
import WechatScanAuthModal from '../components/WechatScanAuthModal';
|
||||||
|
|
||||||
import { useStorePageView } from '../lib/usePageView';
|
import { useStorePageView } from '../lib/usePageView';
|
||||||
|
|
||||||
import { trackStore } from '../lib/analytics';
|
import { trackStore } from '../lib/analytics';
|
||||||
|
|
||||||
const PENDING_SCAN_KEY = 'shop_pending_scan';
|
|
||||||
|
|
||||||
function formatMoney(n: number) {
|
function formatMoney(n: number) {
|
||||||
|
|
||||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatScanError(e: unknown): string {
|
|
||||||
|
|
||||||
|
function formatScanError(e: unknown, opts?: { afterAuth?: boolean }): string {
|
||||||
|
|
||||||
const msg = e instanceof Error ? e.message : '扫码失败,请重试';
|
const msg = e instanceof Error ? e.message : '扫码失败,请重试';
|
||||||
|
|
||||||
if (/invalid signature/i.test(msg)) {
|
if (/invalid signature/i.test(msg)) {
|
||||||
|
|
||||||
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
||||||
|
|
||||||
}
|
}
|
||||||
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
|
||||||
|
if (isScanPermissionWarmupError(msg)) {
|
||||||
|
|
||||||
|
if (opts?.afterAuth) {
|
||||||
|
|
||||||
|
return '微信授权已完成,扫码权限仍在准备中,请再点一次「扫码核销」';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
return '微信权限校验尚未完成,请等待 1~2 秒后再次点击扫码(首次绑定微信时较常见)';
|
return '微信权限校验尚未完成,请等待 1~2 秒后再次点击扫码(首次绑定微信时较常见)';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg;
|
return msg;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
|
|
||||||
useStorePageView('store_home_view');
|
useStorePageView('store_home_view');
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { applySession } = useStoreSession();
|
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const { ready, authenticated } = useStoreSession();
|
||||||
|
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
|
||||||
const [dash, setDash] = useState<Record<string, unknown> | null>(null);
|
const [dash, setDash] = useState<Record<string, unknown> | null>(null);
|
||||||
|
|
||||||
const [scanMsg, setScanMsg] = useState('');
|
const [scanMsg, setScanMsg] = useState('');
|
||||||
|
|
||||||
const [scanning, setScanning] = useState(false);
|
const [scanning, setScanning] = useState(false);
|
||||||
|
|
||||||
const [authModalOpen, setAuthModalOpen] = useState(false);
|
const [authModalOpen, setAuthModalOpen] = useState(false);
|
||||||
|
|
||||||
const [authLoading, setAuthLoading] = useState(false);
|
const [authLoading, setAuthLoading] = useState(false);
|
||||||
|
|
||||||
const [authError, setAuthError] = useState('');
|
const [authError, setAuthError] = useState('');
|
||||||
|
|
||||||
|
const pendingScanStartedRef = useRef(false);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const loadDashboard = useCallback(() => {
|
const loadDashboard = useCallback(() => {
|
||||||
|
|
||||||
return request<Record<string, unknown>>('SHOP_H5', '/shop/dashboard')
|
return request<Record<string, unknown>>('SHOP_H5', '/shop/dashboard')
|
||||||
|
|
||||||
.then((d) => {
|
.then((d) => {
|
||||||
|
|
||||||
setDash(d);
|
setDash(d);
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
||||||
void loadDashboard();
|
void loadDashboard();
|
||||||
|
|
||||||
}, [loadDashboard]);
|
}, [loadDashboard]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
||||||
function onResume() {
|
function onResume() {
|
||||||
|
|
||||||
setScanning(false);
|
setScanning(false);
|
||||||
|
|
||||||
void loadDashboard();
|
void loadDashboard();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onVisibility() {
|
function onVisibility() {
|
||||||
|
|
||||||
if (document.visibilityState === 'visible') onResume();
|
if (document.visibilityState === 'visible') onResume();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener('visibilitychange', onVisibility);
|
document.addEventListener('visibilitychange', onVisibility);
|
||||||
|
|
||||||
window.addEventListener('pageshow', onResume);
|
window.addEventListener('pageshow', onResume);
|
||||||
|
|
||||||
window.addEventListener('focus', onResume);
|
window.addEventListener('focus', onResume);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
document.removeEventListener('visibilitychange', onVisibility);
|
||||||
|
|
||||||
window.removeEventListener('pageshow', onResume);
|
window.removeEventListener('pageshow', onResume);
|
||||||
|
|
||||||
window.removeEventListener('focus', onResume);
|
window.removeEventListener('focus', onResume);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}, [loadDashboard]);
|
}, [loadDashboard]);
|
||||||
|
|
||||||
async function runScan(opts?: { postAuthWarmup?: boolean }) {
|
|
||||||
trackStore('store_redeem_scan_start');
|
|
||||||
if (!isWechatEnv()) {
|
const runScan = useCallback(
|
||||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
|
||||||
return;
|
async (opts?: { postAuthWarmup?: boolean }) => {
|
||||||
}
|
|
||||||
setScanning(true);
|
trackStore('store_redeem_scan_start');
|
||||||
setScanMsg('');
|
|
||||||
try {
|
if (!isWechatEnv()) {
|
||||||
// 授权回跳后强制重签,避免沿用带 code 的旧签名态
|
|
||||||
if (opts?.postAuthWarmup) {
|
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||||
weixinSdk.reset();
|
|
||||||
}
|
|
||||||
await weixinSdk.init();
|
|
||||||
const raw = await weixinSdk.scanQrCode(
|
|
||||||
opts?.postAuthWarmup ? { postAuthWarmup: true } : undefined,
|
|
||||||
);
|
|
||||||
if (!raw) {
|
|
||||||
void loadDashboard();
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
const token = parseRedeemTokenFromScan(raw);
|
|
||||||
if (!token) {
|
setScanning(true);
|
||||||
setScanMsg('无法识别核销码,请扫描用户出示的核销二维码');
|
|
||||||
return;
|
if (!opts?.postAuthWarmup) {
|
||||||
|
|
||||||
|
setScanMsg('');
|
||||||
|
|
||||||
}
|
}
|
||||||
navigate(`/redeem?token=${encodeURIComponent(token)}`);
|
|
||||||
} catch (e) {
|
try {
|
||||||
setScanMsg(formatScanError(e));
|
|
||||||
} finally {
|
if (opts?.postAuthWarmup) {
|
||||||
setScanning(false);
|
|
||||||
}
|
weixinSdk.reset();
|
||||||
}
|
|
||||||
|
}
|
||||||
|
|
||||||
|
await weixinSdk.init();
|
||||||
|
|
||||||
|
const raw = await weixinSdk.scanQrCode(
|
||||||
|
|
||||||
|
opts?.postAuthWarmup ? { postAuthWarmup: true } : undefined,
|
||||||
|
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!raw) {
|
||||||
|
|
||||||
|
void loadDashboard();
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = parseRedeemTokenFromScan(raw);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
|
||||||
|
setScanMsg('无法识别核销码,请扫描用户出示的核销二维码');
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
navigate(`/redeem?token=${encodeURIComponent(token)}`);
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
|
||||||
|
setScanMsg(formatScanError(e, { afterAuth: opts?.postAuthWarmup }));
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
|
||||||
|
setScanning(false);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
},
|
||||||
|
|
||||||
|
[loadDashboard, navigate],
|
||||||
|
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// OAuth 由 StoreSessionContext 单例处理;此处仅在授权完成后续扫
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWechatEnv() || !searchParams.get('code')) return;
|
|
||||||
void handleShopWechatCallback()
|
if (!ready || !authenticated || !isWechatEnv()) return;
|
||||||
.then((result) => {
|
|
||||||
if (!result) return;
|
if (searchParams.get('code')) return;
|
||||||
const session = handleShopWechatLoginResult(result);
|
|
||||||
if (session) {
|
if (!peekPendingScanAfterAuth() || pendingScanStartedRef.current) return;
|
||||||
applySession(session);
|
|
||||||
}
|
|
||||||
setAuthModalOpen(false);
|
|
||||||
setAuthError('');
|
pendingScanStartedRef.current = true;
|
||||||
// 先清 OAuth 参数再扫,保证 JSSDK 签名 URL 与当前页一致
|
|
||||||
stripOAuthParamsFromLocation();
|
clearPendingScanAfterAuth();
|
||||||
setSearchParams({}, { replace: true });
|
|
||||||
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
setAuthModalOpen(false);
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
if (shouldScan) {
|
setAuthLoading(false);
|
||||||
// OAuth 回跳后微信权限离线校验未完成;稍候再扫,失败可再点一次
|
|
||||||
window.setTimeout(() => void runScan({ postAuthWarmup: true }), 400);
|
setAuthError('');
|
||||||
}
|
|
||||||
})
|
setScanMsg('微信授权成功,正在准备扫码…');
|
||||||
.catch((e) => {
|
|
||||||
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
|
||||||
});
|
|
||||||
}, [searchParams, applySession, setSearchParams]);
|
const timer = window.setTimeout(() => {
|
||||||
|
|
||||||
|
void runScan({ postAuthWarmup: true });
|
||||||
|
|
||||||
|
}, getPostAuthScanDelayMs());
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
|
||||||
|
}, [ready, authenticated, searchParams, runScan]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async function handleScan() {
|
async function handleScan() {
|
||||||
|
|
||||||
setScanMsg('');
|
setScanMsg('');
|
||||||
|
|
||||||
if (!isWechatEnv()) {
|
if (!isWechatEnv()) {
|
||||||
|
|
||||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const profile = await fetchShopAccount();
|
const profile = await fetchShopAccount();
|
||||||
|
|
||||||
if (await checkNeedsWechatAuth(profile)) {
|
if (await checkNeedsWechatAuth(profile)) {
|
||||||
|
|
||||||
|
pendingScanStartedRef.current = false;
|
||||||
|
|
||||||
setAuthModalOpen(true);
|
setAuthModalOpen(true);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await runScan();
|
await runScan();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
||||||
setScanMsg(e instanceof Error ? e.message : '无法发起扫码');
|
setScanMsg(e instanceof Error ? e.message : '无法发起扫码');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async function startWechatAuth() {
|
async function startWechatAuth() {
|
||||||
|
|
||||||
setAuthLoading(true);
|
setAuthLoading(true);
|
||||||
|
|
||||||
setAuthError('');
|
setAuthError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
sessionStorage.setItem(PENDING_SCAN_KEY, '1');
|
|
||||||
|
pendingScanStartedRef.current = false;
|
||||||
|
|
||||||
|
markPendingScanAfterAuth();
|
||||||
|
|
||||||
await authorizeShopWechat();
|
await authorizeShopWechat();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
|
clearPendingScanAfterAuth();
|
||||||
|
|
||||||
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
||||||
|
|
||||||
setAuthLoading(false);
|
setAuthLoading(false);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const store = dash?.store as Record<string, unknown> | undefined;
|
const store = dash?.store as Record<string, unknown> | undefined;
|
||||||
|
|
||||||
const recent = (dash?.recentRecords as Array<Record<string, unknown>>) || [];
|
const recent = (dash?.recentRecords as Array<Record<string, unknown>>) || [];
|
||||||
|
|
||||||
const status = String(store?.status || '');
|
const status = String(store?.status || '');
|
||||||
|
|
||||||
const open = status === 'OPEN';
|
const open = status === 'OPEN';
|
||||||
|
|
||||||
const hoursParts: string[] = [];
|
const hoursParts: string[] = [];
|
||||||
|
|
||||||
if (store?.openTime && store?.closeTime) hoursParts.push(`${store.openTime} - ${store.closeTime}`);
|
if (store?.openTime && store?.closeTime) hoursParts.push(`${store.openTime} - ${store.closeTime}`);
|
||||||
|
|
||||||
if (store?.openTime2 && store?.closeTime2) hoursParts.push(`${store.openTime2} - ${store.closeTime2}`);
|
if (store?.openTime2 && store?.closeTime2) hoursParts.push(`${store.openTime2} - ${store.closeTime2}`);
|
||||||
|
|
||||||
const hoursText = hoursParts.length ? hoursParts.join(',') : '10:00 - 22:00';
|
const hoursText = hoursParts.length ? hoursParts.join(',') : '10:00 - 22:00';
|
||||||
|
|
||||||
const statusText =
|
const statusText =
|
||||||
|
|
||||||
status === 'CLOSED' ? '永久关闭' : open ? '当前正在营业中' : '当前临时闭店';
|
status === 'CLOSED' ? '永久关闭' : open ? '当前正在营业中' : '当前临时闭店';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<PullToRefresh onRefresh={loadDashboard} className="shop-home-page">
|
<PullToRefresh onRefresh={loadDashboard} className="shop-home-page">
|
||||||
|
|
||||||
<header className="shop-home-header">
|
<header className="shop-home-header">
|
||||||
|
|
||||||
<h1 className="app-page-title">门店管理中心</h1>
|
<h1 className="app-page-title">门店管理中心</h1>
|
||||||
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div className="shop-home-content">
|
<div className="shop-home-content">
|
||||||
|
|
||||||
<section className="shop-home-hero">
|
<section className="shop-home-hero">
|
||||||
|
|
||||||
<div className="shop-home-hero-store">
|
<div className="shop-home-hero-store">
|
||||||
|
|
||||||
<span className="material-symbols-outlined shop-fill-icon">store</span>
|
<span className="material-symbols-outlined shop-fill-icon">store</span>
|
||||||
|
|
||||||
<h2>{String(store?.name || '门店')}</h2>
|
<h2>{String(store?.name || '门店')}</h2>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shop-home-stats">
|
<div className="shop-home-stats">
|
||||||
|
|
||||||
<div className="shop-home-stat">
|
<div className="shop-home-stat">
|
||||||
|
|
||||||
<p className="shop-home-stat-label">今日核销笔数</p>
|
<p className="shop-home-stat-label">今日核销笔数</p>
|
||||||
|
|
||||||
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
||||||
|
|
||||||
<p className="shop-home-stat-sub">
|
<p className="shop-home-stat-sub">
|
||||||
|
|
||||||
扫码 {Number(dash?.todayScanCount || 0)} · 手机号 {Number(dash?.todayPhoneCount || 0)}
|
扫码 {Number(dash?.todayScanCount || 0)} · 手机号 {Number(dash?.todayPhoneCount || 0)}
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shop-home-stat">
|
<div className="shop-home-stat">
|
||||||
|
|
||||||
<p className="shop-home-stat-label">今日到账金额</p>
|
<p className="shop-home-stat-label">今日到账金额</p>
|
||||||
|
|
||||||
<p className="shop-home-stat-value">
|
<p className="shop-home-stat-value">
|
||||||
|
|
||||||
<span style={{ fontSize: 18 }}>¥</span>
|
<span style={{ fontSize: 18 }}>¥</span>
|
||||||
|
|
||||||
{formatMoney(Number(dash?.todayAmount || 0))}
|
{formatMoney(Number(dash?.todayAmount || 0))}
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<section className="shop-home-scan">
|
<section className="shop-home-scan">
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
||||||
type="button"
|
type="button"
|
||||||
|
|
||||||
className="shop-home-scan-btn"
|
className="shop-home-scan-btn"
|
||||||
|
|
||||||
disabled={scanning}
|
disabled={scanning}
|
||||||
|
|
||||||
onClick={() => void handleScan()}
|
onClick={() => void handleScan()}
|
||||||
|
|
||||||
>
|
>
|
||||||
|
|
||||||
<span className="material-symbols-outlined">qr_code_scanner</span>
|
<span className="material-symbols-outlined">qr_code_scanner</span>
|
||||||
|
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<p className="shop-home-scan-label">{scanning ? '正在打开相机…' : '扫码核销'}</p>
|
<p className="shop-home-scan-label">{scanning ? '正在打开相机…' : '扫码核销'}</p>
|
||||||
|
|
||||||
{scanMsg && <p className="shop-home-scan-msg" role="alert">{scanMsg}</p>}
|
{scanMsg && <p className="shop-home-scan-msg" role="alert">{scanMsg}</p>}
|
||||||
|
|
||||||
<Link to="/redeem/phone" className="shop-home-phone-link">
|
<Link to="/redeem/phone" className="shop-home-phone-link">
|
||||||
|
|
||||||
<span className="material-symbols-outlined">smartphone</span>
|
<span className="material-symbols-outlined">smartphone</span>
|
||||||
|
|
||||||
手机号核销
|
手机号核销
|
||||||
|
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<section className="shop-home-status">
|
<section className="shop-home-status">
|
||||||
|
|
||||||
<div className="shop-home-status-left">
|
<div className="shop-home-status-left">
|
||||||
|
|
||||||
<div className={`shop-home-status-icon${open ? '' : ' closed'}`}>
|
<div className={`shop-home-status-icon${open ? '' : ' closed'}`}>
|
||||||
|
|
||||||
<span className="material-symbols-outlined shop-fill-icon">schedule</span>
|
<span className="material-symbols-outlined shop-fill-icon">schedule</span>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|
||||||
<p className="shop-home-status-title">营业状态</p>
|
<p className="shop-home-status-title">营业状态</p>
|
||||||
|
|
||||||
<p className="shop-home-status-sub">{statusText}</p>
|
<p className="shop-home-status-sub">{statusText}</p>
|
||||||
|
|
||||||
<p className="shop-home-status-sub">营业时间: {hoursText}</p>
|
<p className="shop-home-status-sub">营业时间: {hoursText}</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<label className="shop-home-switch" onClick={() => navigate('/status')}>
|
<label className="shop-home-switch" onClick={() => navigate('/status')}>
|
||||||
|
|
||||||
<input type="checkbox" checked={open && status !== 'CLOSED'} readOnly tabIndex={-1} />
|
<input type="checkbox" checked={open && status !== 'CLOSED'} readOnly tabIndex={-1} />
|
||||||
|
|
||||||
<span className="shop-home-switch-track" />
|
<span className="shop-home-switch-track" />
|
||||||
|
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
|
|
||||||
<div className="shop-home-records-head">
|
<div className="shop-home-records-head">
|
||||||
|
|
||||||
<h3 className="shop-home-records-title">核销记录</h3>
|
<h3 className="shop-home-records-title">核销记录</h3>
|
||||||
|
|
||||||
<Link to="/records" className="shop-home-records-link">
|
<Link to="/records" className="shop-home-records-link">
|
||||||
|
|
||||||
查看全部
|
查看全部
|
||||||
|
|
||||||
<span className="material-symbols-outlined" style={{ fontSize: 16 }}>chevron_right</span>
|
<span className="material-symbols-outlined" style={{ fontSize: 16 }}>chevron_right</span>
|
||||||
|
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shop-home-record-list">
|
<div className="shop-home-record-list">
|
||||||
|
|
||||||
{recent.length === 0 && (
|
{recent.length === 0 && (
|
||||||
|
|
||||||
<p className="shop-home-status-sub" style={{ textAlign: 'center', padding: '16px 0' }}>暂无核销记录</p>
|
<p className="shop-home-status-sub" style={{ textAlign: 'center', padding: '16px 0' }}>暂无核销记录</p>
|
||||||
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{recent.map((r) => (
|
{recent.map((r) => (
|
||||||
|
|
||||||
<div key={String(r.id)} className="shop-home-record-item">
|
<div key={String(r.id)} className="shop-home-record-item">
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|
||||||
<p className="shop-home-record-time">核销时间</p>
|
<p className="shop-home-record-time">核销时间</p>
|
||||||
|
|
||||||
<p className="shop-home-record-value">
|
<p className="shop-home-record-value">
|
||||||
|
|
||||||
{new Date(String(r.createdAt)).toLocaleString('zh-CN')}
|
{new Date(String(r.createdAt)).toLocaleString('zh-CN')}
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="shop-home-record-amount">¥{formatMoney(Number(r.amount))}</p>
|
<p className="shop-home-record-amount">¥{formatMoney(Number(r.amount))}</p>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
))}
|
))}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<WechatScanAuthModal
|
<WechatScanAuthModal
|
||||||
|
|
||||||
open={authModalOpen}
|
open={authModalOpen}
|
||||||
|
|
||||||
loading={authLoading}
|
loading={authLoading}
|
||||||
|
|
||||||
error={authError}
|
error={authError}
|
||||||
|
|
||||||
onAuthorize={() => void startWechatAuth()}
|
onAuthorize={() => void startWechatAuth()}
|
||||||
|
|
||||||
onCancel={() => {
|
onCancel={() => {
|
||||||
|
|
||||||
setAuthModalOpen(false);
|
setAuthModalOpen(false);
|
||||||
|
|
||||||
setAuthError('');
|
setAuthError('');
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
|
clearPendingScanAfterAuth();
|
||||||
|
|
||||||
|
pendingScanStartedRef.current = false;
|
||||||
|
|
||||||
}}
|
}}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</PullToRefresh>
|
</PullToRefresh>
|
||||||
|
|
||||||
);
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
consumeShopWechatLoginHint,
|
consumeShopWechatLoginHint,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
formatShopWechatError,
|
formatShopWechatError,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
loginShopWithWechat,
|
loginShopWithWechat,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
@@ -88,7 +88,7 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||||
void handleShopWechatCallback()
|
void handleShopWechatCallbackOnce()
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
@@ -140,12 +140,22 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function login() {
|
async function login() {
|
||||||
if (!ensureAgreed()) return;
|
if (!ensureAgreed()) return;
|
||||||
|
const trimmedPhone = phone.trim();
|
||||||
|
const trimmedCode = code.trim();
|
||||||
|
if (!trimmedPhone) {
|
||||||
|
setMsg('phone should not be empty');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!trimmedCode) {
|
||||||
|
setMsg('code should not be empty');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
const data = await request<ShopSessionPayload>('SHOP_H5', '/shop/auth/login/sms', {
|
const data = await request<ShopSessionPayload>('SHOP_H5', '/shop/auth/login/sms', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, code }),
|
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||||
});
|
});
|
||||||
saveRememberedSession(data);
|
saveRememberedSession(data);
|
||||||
applySession(data);
|
applySession(data);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
authorizeShopWechat,
|
authorizeShopWechat,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
fetchShopAccount,
|
fetchShopAccount,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
import { isWechatEnv } from '../lib/weixin';
|
import { isWechatEnv } from '../lib/weixin';
|
||||||
@@ -45,7 +45,7 @@ export default function MinePage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWechatEnv() || !wxAuthorize || !searchParams.get('code')) return;
|
if (!isWechatEnv() || !wxAuthorize || !searchParams.get('code')) return;
|
||||||
void handleShopWechatCallback()
|
void handleShopWechatCallbackOnce()
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { CUSTOMER_SERVICE_PHONE } from '@dukang/shared-types';
|
import { useEffect, useState } from 'react';
|
||||||
import { track } from '../lib/analytics';
|
import { track } from '../lib/analytics';
|
||||||
import { openWecomCustomerService } from '../lib/customer-service';
|
import {
|
||||||
|
getCustomerServicePhone,
|
||||||
|
loadCustomerServicePhone,
|
||||||
|
openWecomCustomerService,
|
||||||
|
} from '../lib/customer-service';
|
||||||
|
|
||||||
type ContactCustomerSheetProps = {
|
type ContactCustomerSheetProps = {
|
||||||
orderId?: string;
|
orderId?: string;
|
||||||
@@ -9,7 +13,13 @@ type ContactCustomerSheetProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function ContactCustomerSheet({ orderId, onClose }: ContactCustomerSheetProps) {
|
export default function ContactCustomerSheet({ orderId, onClose }: ContactCustomerSheetProps) {
|
||||||
const tel = CUSTOMER_SERVICE_PHONE.replace(/-/g, '');
|
const [phone, setPhone] = useState(getCustomerServicePhone);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadCustomerServicePhone().then(setPhone);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const tel = phone.replace(/-/g, '');
|
||||||
|
|
||||||
function openPhone() {
|
function openPhone() {
|
||||||
track('cs_contact', { type: 'phone', orderId });
|
track('cs_contact', { type: 'phone', orderId });
|
||||||
@@ -41,7 +51,7 @@ export default function ContactCustomerSheet({ orderId, onClose }: ContactCustom
|
|||||||
</div>
|
</div>
|
||||||
<div className="contact-customer-option-body">
|
<div className="contact-customer-option-body">
|
||||||
<p className="contact-customer-option-title">拨打总部客服电话</p>
|
<p className="contact-customer-option-title">拨打总部客服电话</p>
|
||||||
<p className="contact-customer-option-sub">{CUSTOMER_SERVICE_PHONE}</p>
|
<p className="contact-customer-option-sub">{phone}</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
|
<span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,12 +1,31 @@
|
|||||||
import { CUSTOMER_SERVICE_PHONE, CUSTOMER_SERVICE_WECOM_URL } from '@dukang/shared-types';
|
import { CUSTOMER_SERVICE_PHONE, CUSTOMER_SERVICE_WECOM_URL } from '@dukang/shared-types';
|
||||||
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
import { isWechatEnv } from './weixin';
|
import { isWechatEnv } from './weixin';
|
||||||
|
|
||||||
|
let cachedPhone = CUSTOMER_SERVICE_PHONE;
|
||||||
|
|
||||||
/** 企微客服链接:优先 Vite env,否则 shared-types 默认 */
|
/** 企微客服链接:优先 Vite env,否则 shared-types 默认 */
|
||||||
export function getCustomerServiceWecomUrl(): string {
|
export function getCustomerServiceWecomUrl(): string {
|
||||||
const fromEnv = import.meta.env.VITE_CS_WECOM_URL?.trim();
|
const fromEnv = import.meta.env.VITE_CS_WECOM_URL?.trim();
|
||||||
return fromEnv || CUSTOMER_SERVICE_WECOM_URL;
|
return fromEnv || CUSTOMER_SERVICE_WECOM_URL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getCustomerServicePhone(): string {
|
||||||
|
return cachedPhone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从系统设置拉取客服电话(失败则保持默认常量) */
|
||||||
|
export async function loadCustomerServicePhone(): Promise<string> {
|
||||||
|
try {
|
||||||
|
const cfg = await fetchClientConfig();
|
||||||
|
const phone = cfg.customerServicePhone?.trim();
|
||||||
|
if (phone) cachedPhone = phone;
|
||||||
|
} catch {
|
||||||
|
/* keep fallback */
|
||||||
|
}
|
||||||
|
return cachedPhone;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 打开企业微信客服会话(须在微信内;需用户点击手势)。
|
* 打开企业微信客服会话(须在微信内;需用户点击手势)。
|
||||||
* @returns true 已跳转;false 非微信环境已提示
|
* @returns true 已跳转;false 非微信环境已提示
|
||||||
@@ -20,4 +39,5 @@ export function openWecomCustomerService(): boolean {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @deprecated 请用 getCustomerServicePhone(),保留兼容旧引用 */
|
||||||
export { CUSTOMER_SERVICE_PHONE };
|
export { CUSTOMER_SERVICE_PHONE };
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase } from './api';
|
import { apiBase } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||||
|
|
||||||
@@ -15,8 +20,15 @@ export async function uploadFileToOss(
|
|||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||||
|
let prepared = file;
|
||||||
|
if (mediaType === 'IMAGE') {
|
||||||
|
prepared = await compressImageFileIfNeeded(file);
|
||||||
|
if (prepared.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||||
|
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||||
|
}
|
||||||
|
}
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import SubPageHeader from '../components/SubPageHeader';
|
import SubPageHeader from '../components/SubPageHeader';
|
||||||
import { CUSTOMER_SERVICE_PHONE, openWecomCustomerService } from '../lib/customer-service';
|
import {
|
||||||
|
getCustomerServicePhone,
|
||||||
|
loadCustomerServicePhone,
|
||||||
|
openWecomCustomerService,
|
||||||
|
} from '../lib/customer-service';
|
||||||
import { track } from '../lib/analytics';
|
import { track } from '../lib/analytics';
|
||||||
|
|
||||||
export default function CustomerServicePage() {
|
export default function CustomerServicePage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const tel = CUSTOMER_SERVICE_PHONE.replace(/-/g, '');
|
const [phone, setPhone] = useState(getCustomerServicePhone);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadCustomerServicePhone().then(setPhone);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const tel = phone.replace(/-/g, '');
|
||||||
|
|
||||||
function openOnline() {
|
function openOnline() {
|
||||||
track('cs_contact', { type: 'wecom_kf' });
|
track('cs_contact', { type: 'wecom_kf' });
|
||||||
@@ -27,7 +38,7 @@ export default function CustomerServicePage() {
|
|||||||
|
|
||||||
<a className="customer-service-phone-link" href={`tel:${tel}`}>
|
<a className="customer-service-phone-link" href={`tel:${tel}`}>
|
||||||
<span className="material-symbols-outlined">call</span>
|
<span className="material-symbols-outlined">call</span>
|
||||||
或拨打客服电话 {CUSTOMER_SERVICE_PHONE}
|
或拨打客服电话 {phone}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@dukang/mini-user",
|
"name": "@dukang/mini-user",
|
||||||
"version": "0.1.0",
|
"version": "3.4.14",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ export default defineAppConfig({
|
|||||||
'pages/mine/index',
|
'pages/mine/index',
|
||||||
'pages/product-detail/index',
|
'pages/product-detail/index',
|
||||||
'pages/store-detail/index',
|
'pages/store-detail/index',
|
||||||
|
'pages/store-package-detail/index',
|
||||||
'pages/order-confirm/index',
|
'pages/order-confirm/index',
|
||||||
'pages/order-confirm-pickup/index',
|
'pages/order-confirm-pickup/index',
|
||||||
'pages/pay/index',
|
'pages/pay/index',
|
||||||
'pages/orders/index',
|
'pages/orders/index',
|
||||||
'pages/order-detail/index',
|
'pages/order-detail/index',
|
||||||
|
'pages/order-logistics/index',
|
||||||
'pages/pickup-receive/index',
|
'pages/pickup-receive/index',
|
||||||
'pages/addresses/index',
|
'pages/addresses/index',
|
||||||
'pages/address-edit/index',
|
'pages/address-edit/index',
|
||||||
|
|||||||
@@ -6,11 +6,13 @@ import WechatShareBootstrap from './components/WechatShareBootstrap';
|
|||||||
import { patchTaroH5Hooks } from './lib/patch-taro-h5-hooks';
|
import { patchTaroH5Hooks } from './lib/patch-taro-h5-hooks';
|
||||||
import { handleWechatOrderConfirmShow } from './lib/wechat-order-confirm';
|
import { handleWechatOrderConfirmShow } from './lib/wechat-order-confirm';
|
||||||
import { installClientErrorReporting } from './lib/client-error';
|
import { installClientErrorReporting } from './lib/client-error';
|
||||||
|
import { prefetchShareBrandAssets } from './lib/wechat-share';
|
||||||
import './app.css';
|
import './app.css';
|
||||||
|
|
||||||
// H5:在首屏 page hooks 执行前,把 Taro.useDidShow 等绑到与 createReactApp 同一份 runtime
|
// H5:在首屏 page hooks 执行前,把 Taro.useDidShow 等绑到与 createReactApp 同一份 runtime
|
||||||
patchTaroH5Hooks();
|
patchTaroH5Hooks();
|
||||||
installClientErrorReporting();
|
installClientErrorReporting();
|
||||||
|
prefetchShareBrandAssets();
|
||||||
|
|
||||||
function App({ children }: PropsWithChildren) {
|
function App({ children }: PropsWithChildren) {
|
||||||
const handlingRef = useRef(false);
|
const handlingRef = useRef(false);
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { Text } from '@tarojs/components';
|
||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
import { splitLogisticsText } from '../lib/order-logistics-utils';
|
||||||
|
import { toast } from '../lib/api';
|
||||||
|
|
||||||
|
type LogisticsRichTextProps = {
|
||||||
|
text: string;
|
||||||
|
className?: string;
|
||||||
|
phoneClassName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function LogisticsRichText({
|
||||||
|
text,
|
||||||
|
className = '',
|
||||||
|
phoneClassName = 'order-logistics-phone-link',
|
||||||
|
}: LogisticsRichTextProps) {
|
||||||
|
const segments = splitLogisticsText(text);
|
||||||
|
|
||||||
|
function dial(phone: string) {
|
||||||
|
const normalized = phone.replace(/-/g, '');
|
||||||
|
Taro.makePhoneCall({ phoneNumber: normalized }).catch(() => toast('无法拨打电话'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Text className={className}>
|
||||||
|
{segments.map((segment, index) =>
|
||||||
|
segment.type === 'phone' ? (
|
||||||
|
<Text
|
||||||
|
key={`${segment.value}-${index}`}
|
||||||
|
className={phoneClassName}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
dial(segment.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{segment.value}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text key={`${index}-text`}>{segment.value}</Text>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ type ProductCarouselProps = {
|
|||||||
alt: string;
|
alt: string;
|
||||||
variant?: 'home' | 'detail' | 'store';
|
variant?: 'home' | 'detail' | 'store';
|
||||||
previewable?: boolean;
|
previewable?: boolean;
|
||||||
|
/** cover=aspectFill 裁剪铺满;contain=aspectFit 缩放完整显示(门店门头固定区) */
|
||||||
|
imageFit?: 'cover' | 'contain';
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 商品/门店轮播(对齐 h5 ProductCarousel 三变体) */
|
/** 商品/门店轮播(对齐 h5 ProductCarousel 三变体) */
|
||||||
@@ -15,11 +17,14 @@ export default function ProductCarousel({
|
|||||||
alt,
|
alt,
|
||||||
variant = 'detail',
|
variant = 'detail',
|
||||||
previewable = false,
|
previewable = false,
|
||||||
|
imageFit = 'cover',
|
||||||
}: ProductCarouselProps) {
|
}: ProductCarouselProps) {
|
||||||
const slides = images.length > 0 ? images : [''];
|
const slides = images.length > 0 ? images : [''];
|
||||||
const [activeIndex, setActiveIndex] = useState(0);
|
const [activeIndex, setActiveIndex] = useState(0);
|
||||||
const prefix =
|
const prefix =
|
||||||
variant === 'store' ? 'store-detail-carousel' : variant === 'home' ? 'home-carousel' : 'detail-carousel';
|
variant === 'store' ? 'store-detail-carousel' : variant === 'home' ? 'home-carousel' : 'detail-carousel';
|
||||||
|
const isContain = imageFit === 'contain';
|
||||||
|
const wrapClass = `${prefix}-wrap${isContain ? ` ${prefix}-wrap--contain` : ''}`;
|
||||||
|
|
||||||
function previewAt(index: number) {
|
function previewAt(index: number) {
|
||||||
const urls = slides.filter(Boolean);
|
const urls = slides.filter(Boolean);
|
||||||
@@ -29,7 +34,7 @@ export default function ProductCarousel({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View className={`${prefix}-wrap`}>
|
<View className={wrapClass}>
|
||||||
<Swiper
|
<Swiper
|
||||||
className={prefix}
|
className={prefix}
|
||||||
circular={slides.length > 1}
|
circular={slides.length > 1}
|
||||||
@@ -41,7 +46,7 @@ export default function ProductCarousel({
|
|||||||
<Image
|
<Image
|
||||||
className={`${prefix}-image`}
|
className={`${prefix}-image`}
|
||||||
src={src}
|
src={src}
|
||||||
mode="aspectFill"
|
mode={isContain ? 'aspectFit' : 'aspectFill'}
|
||||||
alt={alt}
|
alt={alt}
|
||||||
onClick={previewable ? () => previewAt(index) : undefined}
|
onClick={previewable ? () => previewAt(index) : undefined}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useEffect, useRef } from 'react';
|
|||||||
import { finishLoginNavigate, forceReloadAfterAccountMerge, goLogin } from '../lib/auth-nav';
|
import { finishLoginNavigate, forceReloadAfterAccountMerge, goLogin } from '../lib/auth-nav';
|
||||||
import { toast } from '../lib/api';
|
import { toast } from '../lib/api';
|
||||||
import { capturePromoSceneAndTouchScan } from '../lib/promo';
|
import { capturePromoSceneAndTouchScan } from '../lib/promo';
|
||||||
|
import { initClientVersionChecks } from '../lib/client-version';
|
||||||
import { saveWechatLoginResult } from '../lib/pay-wechat';
|
import { saveWechatLoginResult } from '../lib/pay-wechat';
|
||||||
import { applyWechatShare } from '../lib/wechat-share';
|
import { applyWechatShare } from '../lib/wechat-share';
|
||||||
import { handleWechatAuthCallback } from '../lib/wechat-auth';
|
import { handleWechatAuthCallback } from '../lib/wechat-auth';
|
||||||
@@ -38,6 +39,7 @@ export default function WechatShareBootstrap() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void capturePromoSceneAndTouchScan();
|
void capturePromoSceneAndTouchScan();
|
||||||
|
initClientVersionChecks();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import {
|
||||||
|
BRAND_LOGO_MARK_URL,
|
||||||
|
BRAND_LOGO_URL,
|
||||||
|
BRAND_LOGO_WIDE_URL,
|
||||||
|
CUSTOMER_SERVICE_PHONE,
|
||||||
|
QUALIFICATION_DISCLOSURE_URL,
|
||||||
|
type ClientRuntimeConfig,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
|
|
||||||
|
export type BrandAssets = {
|
||||||
|
brandLogoUrl: string;
|
||||||
|
brandLogoWideUrl: string;
|
||||||
|
brandLogoMarkUrl: string;
|
||||||
|
qualificationDisclosureUrl: string;
|
||||||
|
customerServicePhone: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FALLBACK: BrandAssets = {
|
||||||
|
brandLogoUrl: BRAND_LOGO_URL,
|
||||||
|
brandLogoWideUrl: BRAND_LOGO_WIDE_URL,
|
||||||
|
brandLogoMarkUrl: BRAND_LOGO_MARK_URL,
|
||||||
|
qualificationDisclosureUrl: QUALIFICATION_DISCLOSURE_URL,
|
||||||
|
customerServicePhone: CUSTOMER_SERVICE_PHONE,
|
||||||
|
};
|
||||||
|
|
||||||
|
let cached: BrandAssets | null = null;
|
||||||
|
let inflight: Promise<BrandAssets> | null = null;
|
||||||
|
|
||||||
|
function fromConfig(config: ClientRuntimeConfig | null | undefined): BrandAssets {
|
||||||
|
return {
|
||||||
|
brandLogoUrl: config?.brandLogoUrl?.trim() || FALLBACK.brandLogoUrl,
|
||||||
|
brandLogoWideUrl: config?.brandLogoWideUrl?.trim() || FALLBACK.brandLogoWideUrl,
|
||||||
|
brandLogoMarkUrl: config?.brandLogoMarkUrl?.trim() || FALLBACK.brandLogoMarkUrl,
|
||||||
|
qualificationDisclosureUrl:
|
||||||
|
config?.qualificationDisclosureUrl?.trim() || FALLBACK.qualificationDisclosureUrl,
|
||||||
|
customerServicePhone: config?.customerServicePhone?.trim() || FALLBACK.customerServicePhone,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 同步读取最近一次缓存(未拉取前返回代码默认常量) */
|
||||||
|
export function getBrandAssetsSync(): BrandAssets {
|
||||||
|
return cached ?? FALLBACK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取 /common/client-config 中的品牌与客服配置并缓存 */
|
||||||
|
export async function loadBrandAssets(force = false): Promise<BrandAssets> {
|
||||||
|
if (!force && cached) return cached;
|
||||||
|
if (!force && inflight) return inflight;
|
||||||
|
inflight = fetchClientConfig()
|
||||||
|
.then((cfg) => {
|
||||||
|
cached = fromConfig(cfg);
|
||||||
|
return cached;
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
cached = FALLBACK;
|
||||||
|
return cached;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
inflight = null;
|
||||||
|
});
|
||||||
|
return inflight;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyBrandFromClientConfig(config: ClientRuntimeConfig | null | undefined) {
|
||||||
|
cached = fromConfig(config);
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
|
|
||||||
|
/** 与 package.json version 同步,供服务端 minClientVersion 比对 */
|
||||||
|
export const APP_VERSION = '3.4.14';
|
||||||
|
|
||||||
|
export const APP_VERSION_LABEL = `v${APP_VERSION}`;
|
||||||
|
|
||||||
|
function parseSemver(v: string): number[] {
|
||||||
|
return v.split('.').map((n) => parseInt(n, 10) || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compareSemver(a: string, b: string): number {
|
||||||
|
const pa = parseSemver(a);
|
||||||
|
const pb = parseSemver(b);
|
||||||
|
const len = Math.max(pa.length, pb.length);
|
||||||
|
for (let i = 0; i < len; i += 1) {
|
||||||
|
const da = pa[i] ?? 0;
|
||||||
|
const db = pb[i] ?? 0;
|
||||||
|
if (da !== db) return da - db;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function exitMiniProgramIfSupported() {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp') return;
|
||||||
|
if (typeof Taro.exitMiniProgram !== 'function') return;
|
||||||
|
void Taro.exitMiniProgram({});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 微信 CDN 有新包时引导 applyUpdate;返回是否已触发更新流程 */
|
||||||
|
function tryWeappForceUpdate(min: string): Promise<boolean> {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp' || typeof Taro.getUpdateManager !== 'function') {
|
||||||
|
return Promise.resolve(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const manager = Taro.getUpdateManager();
|
||||||
|
let settled = false;
|
||||||
|
const finish = (updated: boolean) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
resolve(updated);
|
||||||
|
};
|
||||||
|
|
||||||
|
manager.onCheckForUpdate((res) => {
|
||||||
|
if (!res.hasUpdate) {
|
||||||
|
finish(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
manager.onUpdateReady(() => {
|
||||||
|
void Taro.showModal({
|
||||||
|
title: '版本过低',
|
||||||
|
content: `当前 ${APP_VERSION_LABEL} 低于要求版本 v${min},已检测到新版本,请立即更新后继续使用。`,
|
||||||
|
showCancel: false,
|
||||||
|
confirmText: '立即更新',
|
||||||
|
success: (r) => {
|
||||||
|
if (r.confirm) {
|
||||||
|
manager.applyUpdate();
|
||||||
|
finish(true);
|
||||||
|
} else {
|
||||||
|
finish(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
fail: () => finish(false),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
manager.onUpdateFailed(() => finish(false));
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => finish(false), 4000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enforceMinClientVersion(min: string) {
|
||||||
|
const updated = await tryWeappForceUpdate(min);
|
||||||
|
if (updated) return;
|
||||||
|
|
||||||
|
await Taro.showModal({
|
||||||
|
title: '版本过低',
|
||||||
|
content: `当前 ${APP_VERSION_LABEL} 低于要求版本 v${min},请更新至最新版本后继续使用。`,
|
||||||
|
showCancel: false,
|
||||||
|
confirmText: '我知道了',
|
||||||
|
});
|
||||||
|
|
||||||
|
exitMiniProgramIfSupported();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkClientVersionGate() {
|
||||||
|
try {
|
||||||
|
const config = await fetchClientConfig();
|
||||||
|
const min = config.minClientVersion?.trim();
|
||||||
|
if (min && compareSemver(APP_VERSION, min) < 0) {
|
||||||
|
await enforceMinClientVersion(min);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* 配置拉取失败不阻塞启动 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setupWeappUpdateManager() {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp') return;
|
||||||
|
if (typeof Taro.getUpdateManager !== 'function') return;
|
||||||
|
|
||||||
|
const manager = Taro.getUpdateManager();
|
||||||
|
manager.onCheckForUpdate((res) => {
|
||||||
|
if (!res.hasUpdate) return;
|
||||||
|
manager.onUpdateReady(() => {
|
||||||
|
void Taro.showModal({
|
||||||
|
title: '更新提示',
|
||||||
|
content: '新版本已准备好,是否重启应用?',
|
||||||
|
confirmText: '立即更新',
|
||||||
|
success: (r) => {
|
||||||
|
if (r.confirm) manager.applyUpdate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
manager.onUpdateFailed(() => {
|
||||||
|
void Taro.showModal({
|
||||||
|
title: '更新失败',
|
||||||
|
content: '新版本下载失败,请删除小程序后重新搜索打开。',
|
||||||
|
showCancel: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initClientVersionChecks() {
|
||||||
|
setupWeappUpdateManager();
|
||||||
|
void checkClientVersionGate();
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
|
||||||
|
const MAX_BYTES = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** 小程序临时文件超过 10MB 时用 compressImage 压缩后再上传 */
|
||||||
|
export async function compressWeappImageIfNeeded(tempFilePath: string): Promise<string> {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp') return tempFilePath;
|
||||||
|
|
||||||
|
let path = tempFilePath;
|
||||||
|
let size = await getFileSize(path);
|
||||||
|
if (size <= MAX_BYTES) return path;
|
||||||
|
|
||||||
|
const qualities = [80, 65, 50, 40];
|
||||||
|
for (const quality of qualities) {
|
||||||
|
const res = await Taro.compressImage({ src: path, quality });
|
||||||
|
path = res.tempFilePath;
|
||||||
|
size = await getFileSize(path);
|
||||||
|
if (size <= MAX_BYTES) return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size > MAX_BYTES) {
|
||||||
|
throw new Error('图片压缩后仍超过 10MB,请换一张较小的图片');
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getFileSize(filePath: string): Promise<number> {
|
||||||
|
try {
|
||||||
|
const info = await Taro.getFileInfo({ filePath });
|
||||||
|
return typeof info.size === 'number' ? info.size : 0;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,12 +69,15 @@ export function mergeWxDisplayProfile(profile: UserProfile): UserProfile {
|
|||||||
/** 上传 chooseAvatar 临时文件到 OSS,并返回已登记到当前用户的真实资源。 */
|
/** 上传 chooseAvatar 临时文件到 OSS,并返回已登记到当前用户的真实资源。 */
|
||||||
export async function uploadAvatarTempFile(tempFilePath: string): Promise<UploadedAvatarResource> {
|
export async function uploadAvatarTempFile(tempFilePath: string): Promise<UploadedAvatarResource> {
|
||||||
const { API_BASE, CLIENT_APP, getToken } = await import('./api');
|
const { API_BASE, CLIENT_APP, getToken } = await import('./api');
|
||||||
|
const { compressWeappImageIfNeeded } = await import('./compress-image');
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (!token) throw new Error('请先登录');
|
if (!token) throw new Error('请先登录');
|
||||||
|
|
||||||
|
const filePath = await compressWeappImageIfNeeded(tempFilePath);
|
||||||
|
|
||||||
const res = await Taro.uploadFile({
|
const res = await Taro.uploadFile({
|
||||||
url: `${API_BASE}/common/resources/upload`,
|
url: `${API_BASE}/common/resources/upload`,
|
||||||
filePath: tempFilePath,
|
filePath,
|
||||||
name: 'file',
|
name: 'file',
|
||||||
formData: {
|
formData: {
|
||||||
bizType: 'AVATAR',
|
bizType: 'AVATAR',
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import type { OrderTrackDto } from '@dukang/shared-types';
|
||||||
|
import { isXfxProviderCode } from '@dukang/shared-types';
|
||||||
|
import { formatShanghaiDateTime } from './datetime';
|
||||||
|
|
||||||
|
export type OrderDelivery = {
|
||||||
|
provider?: string;
|
||||||
|
trackingNo?: string;
|
||||||
|
logisticsCompany?: string;
|
||||||
|
manualQueryUrl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OrderTrackNode = {
|
||||||
|
trackInfo?: string;
|
||||||
|
createTime?: string;
|
||||||
|
createdAt?: string;
|
||||||
|
statusName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OrderTrackEstimatedArrival = {
|
||||||
|
arriveTime: string;
|
||||||
|
siteName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type OrderTrackResponse = OrderTrackDto;
|
||||||
|
|
||||||
|
/** 订单详情页展示物流摘要的状态(配送中) */
|
||||||
|
export const ORDER_LOGISTICS_PREVIEW_STATUSES = ['SHIPPING', 'SHIPPED'] as const;
|
||||||
|
|
||||||
|
const PHONE_PATTERN = /(1[3-9]\d{9}|\d{3,4}-\d{7,8})/g;
|
||||||
|
|
||||||
|
function compareTrackNodeTime(a: OrderTrackNode, b: OrderTrackNode) {
|
||||||
|
const ta = new Date(a.createTime || a.createdAt || 0).getTime();
|
||||||
|
const tb = new Date(b.createTime || b.createdAt || 0).getTime();
|
||||||
|
if (Number.isNaN(ta) && Number.isNaN(tb)) return 0;
|
||||||
|
if (Number.isNaN(ta)) return 1;
|
||||||
|
if (Number.isNaN(tb)) return -1;
|
||||||
|
return ta - tb;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deliveryProviderLabel(provider?: string, company?: string) {
|
||||||
|
if (company) return company;
|
||||||
|
if (!provider || provider === 'MOCK' || isXfxProviderCode(provider)) {
|
||||||
|
return '小飞侠配送';
|
||||||
|
}
|
||||||
|
if (provider === 'LOGISTICS') return '快递配送';
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldLoadOrderTrack(delivery?: OrderDelivery | null) {
|
||||||
|
if (!delivery) return false;
|
||||||
|
if (delivery.trackingNo) return true;
|
||||||
|
return isXfxProviderCode(delivery.provider || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatTrackNodeTime(node: OrderTrackNode) {
|
||||||
|
return formatShanghaiDateTime(node.createTime || node.createdAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortTrackNodesNewestFirst(nodes: OrderTrackNode[]): OrderTrackNode[] {
|
||||||
|
return [...nodes].sort((a, b) => -compareTrackNodeTime(a, b));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortTrackNodesOldestFirst(nodes: OrderTrackNode[]): OrderTrackNode[] {
|
||||||
|
return [...nodes].sort(compareTrackNodeTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function latestTrackNode(nodes: OrderTrackNode[]) {
|
||||||
|
if (!nodes.length) return null;
|
||||||
|
let latest = nodes[0];
|
||||||
|
for (let i = 1; i < nodes.length; i += 1) {
|
||||||
|
if (compareTrackNodeTime(nodes[i], latest) > 0) {
|
||||||
|
latest = nodes[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLogisticsNotArrived(nodes: OrderTrackNode[], orderStatus?: string) {
|
||||||
|
if (['PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(orderStatus || '')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (nodes.length === 0) return true;
|
||||||
|
return !nodes.some(
|
||||||
|
(node) => node.statusName?.includes('签收') || node.trackInfo?.includes('签收'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatEstimatedArrival(eta?: OrderTrackEstimatedArrival | null) {
|
||||||
|
if (!eta?.arriveTime) return '';
|
||||||
|
const time = formatShanghaiDateTime(eta.arriveTime);
|
||||||
|
if (eta.siteName) return `预计送达:${time}(${eta.siteName})`;
|
||||||
|
return `预计送达:${time}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LogisticsTextSegment = { type: 'text' | 'phone'; value: string };
|
||||||
|
|
||||||
|
export function splitLogisticsText(text: string): LogisticsTextSegment[] {
|
||||||
|
if (!text) return [];
|
||||||
|
const segments: LogisticsTextSegment[] = [];
|
||||||
|
let lastIndex = 0;
|
||||||
|
const regex = new RegExp(PHONE_PATTERN.source, 'g');
|
||||||
|
let match: RegExpExecArray | null;
|
||||||
|
while ((match = regex.exec(text)) !== null) {
|
||||||
|
if (match.index > lastIndex) {
|
||||||
|
segments.push({ type: 'text', value: text.slice(lastIndex, match.index) });
|
||||||
|
}
|
||||||
|
segments.push({ type: 'phone', value: match[0] });
|
||||||
|
lastIndex = match.index + match[0].length;
|
||||||
|
}
|
||||||
|
if (lastIndex < text.length) {
|
||||||
|
segments.push({ type: 'text', value: text.slice(lastIndex) });
|
||||||
|
}
|
||||||
|
return segments.length ? segments : [{ type: 'text', value: text }];
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export * from './order-logistics-utils';
|
||||||
|
import type { OrderTrackResponse } from './order-logistics-utils';
|
||||||
|
import { request } from './api';
|
||||||
|
|
||||||
|
export async function fetchOrderTrack(orderId: string) {
|
||||||
|
return request<OrderTrackResponse>(`/trade/orders/${orderId}/track`);
|
||||||
|
}
|
||||||
@@ -1,16 +1,126 @@
|
|||||||
import Taro from '@tarojs/taro';
|
import Taro from '@tarojs/taro';
|
||||||
import { BRAND_LOGO_URL } from '@dukang/shared-types';
|
|
||||||
import type { WechatShareData } from '@dukang/weixin-sdk';
|
import type { WechatShareData } from '@dukang/weixin-sdk';
|
||||||
import { getWechatShareLink, isWechatBrowser, isMiniProgram } from '@dukang/weixin-sdk';
|
import { getWechatShareLink, isWechatBrowser, isMiniProgram } from '@dukang/weixin-sdk';
|
||||||
|
import {
|
||||||
|
applyShareTitleTemplate,
|
||||||
|
DEFAULT_SHARE_DESC,
|
||||||
|
DEFAULT_SHARE_HINT,
|
||||||
|
DEFAULT_SHARE_TITLE,
|
||||||
|
resolveMiniShareRuntime,
|
||||||
|
type ClientRuntimeConfig,
|
||||||
|
type MiniShareRuntime,
|
||||||
|
type MiniShareSceneConfig,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import { toast } from './api';
|
import { toast } from './api';
|
||||||
|
import { getBrandAssetsSync, loadBrandAssets } from './brand-assets';
|
||||||
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
import { isWechatEnv, weixinSdk } from './weixin';
|
import { isWechatEnv, weixinSdk } from './weixin';
|
||||||
|
|
||||||
export const DEFAULT_SHARE_TITLE = '你吃饭,杜康买单';
|
export type ShareScene =
|
||||||
export const DEFAULT_SHARE_DESC = '杜康好客 · 买美酒,享好礼,全城门店可用';
|
| 'home'
|
||||||
export const WECHAT_SHARE_HINT = '请点击右上角 ··· 分享给好友';
|
| 'stores'
|
||||||
|
| 'storeDetail'
|
||||||
|
| 'benefit'
|
||||||
|
| 'mine'
|
||||||
|
| 'productDetail'
|
||||||
|
| 'orderDetail';
|
||||||
|
|
||||||
|
export { DEFAULT_SHARE_TITLE, DEFAULT_SHARE_DESC };
|
||||||
|
|
||||||
|
export const WECHAT_SHARE_HINT = DEFAULT_SHARE_HINT;
|
||||||
|
|
||||||
|
const FALLBACK_SHARE: MiniShareRuntime = resolveMiniShareRuntime({});
|
||||||
|
|
||||||
|
let shareCached: MiniShareRuntime | null = null;
|
||||||
|
|
||||||
|
export function getShareRuntimeSync(): MiniShareRuntime {
|
||||||
|
return shareCached ?? FALLBACK_SHARE;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyShareFromClientConfig(config?: ClientRuntimeConfig | null) {
|
||||||
|
if (config?.share) {
|
||||||
|
shareCached = config.share;
|
||||||
|
return shareCached;
|
||||||
|
}
|
||||||
|
return getShareRuntimeSync();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadShareConfig(force = false): Promise<MiniShareRuntime> {
|
||||||
|
if (!force && shareCached) return shareCached;
|
||||||
|
try {
|
||||||
|
const cfg = await fetchClientConfig();
|
||||||
|
if (cfg?.share) {
|
||||||
|
shareCached = cfg.share;
|
||||||
|
return shareCached;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
shareCached = FALLBACK_SHARE;
|
||||||
|
return shareCached;
|
||||||
|
}
|
||||||
|
|
||||||
export function getDefaultShareImageUrl(): string {
|
export function getDefaultShareImageUrl(): string {
|
||||||
return BRAND_LOGO_URL;
|
const share = getShareRuntimeSync();
|
||||||
|
return share.default.imageUrl || getBrandAssetsSync().brandLogoUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getShareHint(): string {
|
||||||
|
return getShareRuntimeSync().hint || DEFAULT_SHARE_HINT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 预热分享配置与品牌图 */
|
||||||
|
export function prefetchShareBrandAssets() {
|
||||||
|
void loadBrandAssets();
|
||||||
|
void loadShareConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sceneConfig(scene?: ShareScene): MiniShareSceneConfig {
|
||||||
|
const runtime = getShareRuntimeSync();
|
||||||
|
if (!scene) return runtime.default;
|
||||||
|
return runtime[scene] ?? runtime.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组装页面分享:场景配置优先;空字段用 dynamic → 默认分享。
|
||||||
|
* orderDetail 标题支持 {productName}。
|
||||||
|
*/
|
||||||
|
export function buildSceneSharePayload(
|
||||||
|
scene: ShareScene,
|
||||||
|
options?: {
|
||||||
|
path?: string;
|
||||||
|
/** 业务动态标题(场景配置为空时使用) */
|
||||||
|
dynamicTitle?: string | null;
|
||||||
|
dynamicDesc?: string | null;
|
||||||
|
dynamicImageUrl?: string | null;
|
||||||
|
titleVars?: Record<string, string | undefined | null>;
|
||||||
|
},
|
||||||
|
): PageSharePayload {
|
||||||
|
const def = getShareRuntimeSync().default;
|
||||||
|
const sc = sceneConfig(scene);
|
||||||
|
let title = (sc.title || '').trim();
|
||||||
|
if (title && options?.titleVars) {
|
||||||
|
const vars = options.titleVars;
|
||||||
|
const missingRequired = Object.entries(vars).some(
|
||||||
|
([key, value]) => title.includes(`{${key}}`) && !(value != null && String(value).trim()),
|
||||||
|
);
|
||||||
|
title = missingRequired ? '' : applyShareTitleTemplate(title, vars);
|
||||||
|
}
|
||||||
|
if (!title) {
|
||||||
|
title = (options?.dynamicTitle || '').trim() || def.title;
|
||||||
|
}
|
||||||
|
const desc = (sc.desc || '').trim() || (options?.dynamicDesc || '').trim() || def.desc;
|
||||||
|
const imgUrl =
|
||||||
|
(sc.imageUrl || '').trim() ||
|
||||||
|
(options?.dynamicImageUrl || '').trim() ||
|
||||||
|
def.imageUrl ||
|
||||||
|
getDefaultShareImageUrl();
|
||||||
|
return {
|
||||||
|
title,
|
||||||
|
desc,
|
||||||
|
path: options?.path,
|
||||||
|
imgUrl,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildDefaultShareData(
|
export function buildDefaultShareData(
|
||||||
@@ -24,9 +134,10 @@ export function buildDefaultShareData(
|
|||||||
link = '';
|
link = '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const def = getShareRuntimeSync().default;
|
||||||
return {
|
return {
|
||||||
title: overrides?.title ?? DEFAULT_SHARE_TITLE,
|
title: overrides?.title ?? def.title,
|
||||||
desc: overrides?.desc ?? DEFAULT_SHARE_DESC,
|
desc: overrides?.desc ?? def.desc,
|
||||||
link,
|
link,
|
||||||
imgUrl: overrides?.imgUrl ?? getDefaultShareImageUrl(),
|
imgUrl: overrides?.imgUrl ?? getDefaultShareImageUrl(),
|
||||||
};
|
};
|
||||||
@@ -68,7 +179,7 @@ export async function handleShareButtonClick(
|
|||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
toast(WECHAT_SHARE_HINT);
|
toast(getShareHint());
|
||||||
return { showGuide: false };
|
return { showGuide: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +200,7 @@ export async function handleShareButtonClick(
|
|||||||
if (result.invoked) {
|
if (result.invoked) {
|
||||||
return { showGuide: false };
|
return { showGuide: false };
|
||||||
}
|
}
|
||||||
toast(WECHAT_SHARE_HINT);
|
toast(getShareHint());
|
||||||
return { showGuide: true };
|
return { showGuide: true };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast(e instanceof Error ? e.message : '分享配置失败,请刷新后重试');
|
toast(e instanceof Error ? e.message : '分享配置失败,请刷新后重试');
|
||||||
@@ -99,9 +210,20 @@ export async function handleShareButtonClick(
|
|||||||
|
|
||||||
/** 供 useShareAppMessage 使用的标题/路径/图 */
|
/** 供 useShareAppMessage 使用的标题/路径/图 */
|
||||||
export function toWeappShareMessage(payload?: PageSharePayload) {
|
export function toWeappShareMessage(payload?: PageSharePayload) {
|
||||||
|
const def = getShareRuntimeSync().default;
|
||||||
return {
|
return {
|
||||||
title: payload?.title || DEFAULT_SHARE_TITLE,
|
title: payload?.title || def.title,
|
||||||
path: payload?.path || '/pages/home/index',
|
path: payload?.path || '/pages/home/index',
|
||||||
imageUrl: payload?.imgUrl || getDefaultShareImageUrl(),
|
imageUrl: payload?.imgUrl || getDefaultShareImageUrl(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 供 useShareTimeline */
|
||||||
|
export function toWeappShareTimeline(payload?: PageSharePayload, query = '') {
|
||||||
|
const def = getShareRuntimeSync().default;
|
||||||
|
return {
|
||||||
|
title: payload?.title || def.title,
|
||||||
|
query,
|
||||||
|
imageUrl: payload?.imgUrl || getDefaultShareImageUrl(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import { goLogin } from '../../lib/auth-nav';
|
|||||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||||
import { navBarStyle, tabNavContentStyle, useNavBarMetrics } from '../../lib/nav-bar';
|
import { navBarStyle, tabNavContentStyle, useNavBarMetrics } from '../../lib/nav-bar';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
buildSceneSharePayload,
|
||||||
DEFAULT_SHARE_TITLE,
|
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import { formatMoney } from '../../lib/money';
|
import { formatMoney } from '../../lib/money';
|
||||||
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
||||||
@@ -104,20 +104,15 @@ export default function BenefitPage() {
|
|||||||
const available = coupons.filter((c) => c.status === 'ACTIVE' && c.balance > 0);
|
const available = coupons.filter((c) => c.status === 'ACTIVE' && c.balance > 0);
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: '好客权益 · 杜康好客',
|
buildSceneSharePayload('benefit', {
|
||||||
desc: DEFAULT_SHARE_DESC,
|
path: '/pages/benefit/index',
|
||||||
path: '/pages/benefit/index',
|
}),
|
||||||
}),
|
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() => toWeappShareTimeline(sharePayload));
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
|
||||||
query: '',
|
|
||||||
imageUrl: sharePayload.imgUrl,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="tab" className="benefit-page">
|
<PageShell variant="tab" className="benefit-page">
|
||||||
|
|||||||
@@ -1,19 +1,26 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
import { View, Text } from '@tarojs/components';
|
import { View, Text } from '@tarojs/components';
|
||||||
import Taro from '@tarojs/taro';
|
import Taro from '@tarojs/taro';
|
||||||
import { CUSTOMER_SERVICE_PHONE } from '@dukang/shared-types';
|
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import SubPageHeader from '../../components/SubPageHeader';
|
import SubPageHeader from '../../components/SubPageHeader';
|
||||||
import ContactCsButton from '../../components/ContactCsButton';
|
import ContactCsButton from '../../components/ContactCsButton';
|
||||||
import { toast } from '../../lib/api';
|
import { toast } from '../../lib/api';
|
||||||
|
import { getBrandAssetsSync, loadBrandAssets } from '../../lib/brand-assets';
|
||||||
|
|
||||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||||
const DIAL_PHONE = CUSTOMER_SERVICE_PHONE.replace(/-/g, '');
|
|
||||||
|
|
||||||
function dialPhone() {
|
function dialPhone(phone: string) {
|
||||||
Taro.makePhoneCall({ phoneNumber: DIAL_PHONE }).catch(() => toast('无法拨打电话'));
|
const tel = phone.replace(/-/g, '');
|
||||||
|
Taro.makePhoneCall({ phoneNumber: tel }).catch(() => toast('无法拨打电话'));
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CustomerServicePage() {
|
export default function CustomerServicePage() {
|
||||||
|
const [phone, setPhone] = useState(() => getBrandAssetsSync().customerServicePhone);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadBrandAssets().then((b) => setPhone(b.customerServicePhone));
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="sub" className="cs-page">
|
<PageShell variant="sub" className="cs-page">
|
||||||
<SubPageHeader title="联系客服" />
|
<SubPageHeader title="联系客服" />
|
||||||
@@ -30,14 +37,14 @@ export default function CustomerServicePage() {
|
|||||||
<ContactCsButton className="cs-online-btn" session={{ from: 'customer-service' }} />
|
<ContactCsButton className="cs-online-btn" session={{ from: 'customer-service' }} />
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<View className={isWeapp ? 'cs-phone-link' : 'cs-call-btn'} onClick={dialPhone}>
|
<View className={isWeapp ? 'cs-phone-link' : 'cs-call-btn'} onClick={() => dialPhone(phone)}>
|
||||||
<Text>
|
<Text>
|
||||||
{isWeapp ? `或拨打客服电话 ${CUSTOMER_SERVICE_PHONE}` : '拨打客服电话'}
|
{isWeapp ? `或拨打客服电话 ${phone}` : '拨打客服电话'}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{!isWeapp ? (
|
{!isWeapp ? (
|
||||||
<Text className="cs-phone-display">{CUSTOMER_SERVICE_PHONE}</Text>
|
<Text className="cs-phone-display">{phone}</Text>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
</PageShell>
|
</PageShell>
|
||||||
|
|||||||
@@ -28,10 +28,12 @@ import {
|
|||||||
normalizeFulfillmentFlags,
|
normalizeFulfillmentFlags,
|
||||||
} from '../../lib/product-fulfillment';
|
} from '../../lib/product-fulfillment';
|
||||||
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
||||||
|
import type { ClientRuntimeConfig } from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
applyShareFromClientConfig,
|
||||||
DEFAULT_SHARE_TITLE,
|
buildSceneSharePayload,
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import { trackPageView } from '../../lib/analytics';
|
import { trackPageView } from '../../lib/analytics';
|
||||||
type Product = {
|
type Product = {
|
||||||
@@ -85,8 +87,9 @@ export default function HomePage() {
|
|||||||
}, [cityCode]);
|
}, [cityCode]);
|
||||||
|
|
||||||
const loadMiniHome = useCallback(() => {
|
const loadMiniHome = useCallback(() => {
|
||||||
return request<{ miniHome?: MiniHomeConfig }>('/common/client-config')
|
return request<ClientRuntimeConfig>('/common/client-config')
|
||||||
.then((cfg) => {
|
.then((cfg) => {
|
||||||
|
applyShareFromClientConfig(cfg);
|
||||||
const banners = Array.isArray(cfg.miniHome?.banners)
|
const banners = Array.isArray(cfg.miniHome?.banners)
|
||||||
? cfg.miniHome!.banners.filter((u) => typeof u === 'string' && !!u.trim())
|
? cfg.miniHome!.banners.filter((u) => typeof u === 'string' && !!u.trim())
|
||||||
: [];
|
: [];
|
||||||
@@ -221,21 +224,16 @@ export default function HomePage() {
|
|||||||
const footerUrl = miniHome.footerUrl;
|
const footerUrl = miniHome.footerUrl;
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: DEFAULT_SHARE_TITLE,
|
buildSceneSharePayload('home', {
|
||||||
desc: DEFAULT_SHARE_DESC,
|
path: '/pages/home/index',
|
||||||
path: '/pages/home/index',
|
dynamicImageUrl: banners[0] || undefined,
|
||||||
imgUrl: banners[0] || undefined,
|
}),
|
||||||
}),
|
|
||||||
[banners],
|
[banners],
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() => toWeappShareTimeline(sharePayload));
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
|
||||||
query: '',
|
|
||||||
imageUrl: sharePayload.imgUrl,
|
|
||||||
}));
|
|
||||||
|
|
||||||
function scrollToAroma(key: AromaKey) {
|
function scrollToAroma(key: AromaKey) {
|
||||||
setActiveAroma(key);
|
setActiveAroma(key);
|
||||||
|
|||||||
@@ -10,7 +10,11 @@ import {
|
|||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import WechatLoginButton from '../../components/WechatLoginButton';
|
import WechatLoginButton from '../../components/WechatLoginButton';
|
||||||
import PhoneQuickLoginButton from '../../components/PhoneQuickLoginButton';
|
import PhoneQuickLoginButton from '../../components/PhoneQuickLoginButton';
|
||||||
import { BRAND_LOGO_WIDE_URL } from '@dukang/shared-types';
|
import {
|
||||||
|
applyBrandFromClientConfig,
|
||||||
|
getBrandAssetsSync,
|
||||||
|
loadBrandAssets,
|
||||||
|
} from '../../lib/brand-assets';
|
||||||
import { finishLoginNavigate, forceReloadAfterAccountMerge } from '../../lib/auth-nav';
|
import { finishLoginNavigate, forceReloadAfterAccountMerge } from '../../lib/auth-nav';
|
||||||
import {
|
import {
|
||||||
bindWechatForUser,
|
bindWechatForUser,
|
||||||
@@ -98,11 +102,18 @@ export default function LoginPage() {
|
|||||||
const [wxAuthorize, setWxAuthorize] = useState(true);
|
const [wxAuthorize, setWxAuthorize] = useState(true);
|
||||||
const [completeMode, setCompleteMode] = useState<'phone' | 'wechat' | null>(null);
|
const [completeMode, setCompleteMode] = useState<'phone' | 'wechat' | null>(null);
|
||||||
const [showSmsForm, setShowSmsForm] = useState(!IS_WEAPP);
|
const [showSmsForm, setShowSmsForm] = useState(!IS_WEAPP);
|
||||||
|
const [logoWideUrl, setLogoWideUrl] = useState(() => getBrandAssetsSync().brandLogoWideUrl);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
request<ClientRuntimeConfig>('/common/client-config')
|
request<ClientRuntimeConfig>('/common/client-config')
|
||||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
.then((config) => {
|
||||||
.catch(() => setWxAuthorize(true));
|
setWxAuthorize(isWxAuthorizeEnabled(config));
|
||||||
|
setLogoWideUrl(applyBrandFromClientConfig(config).brandLogoWideUrl);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setWxAuthorize(true);
|
||||||
|
void loadBrandAssets().then((b) => setLogoWideUrl(b.brandLogoWideUrl));
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -394,7 +405,7 @@ export default function LoginPage() {
|
|||||||
<View className="login-header">
|
<View className="login-header">
|
||||||
<View className="login-logo-wrap">
|
<View className="login-logo-wrap">
|
||||||
<View className="login-logo">
|
<View className="login-logo">
|
||||||
<Image className="login-logo-img" src={BRAND_LOGO_WIDE_URL} mode="aspectFit" />
|
<Image className="login-logo-img" src={logoWideUrl} mode="aspectFit" />
|
||||||
</View>
|
</View>
|
||||||
<Text className="login-logo-badge">官方</Text>
|
<Text className="login-logo-badge">官方</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import { useEffect, useMemo, useState } from 'react';
|
|||||||
import { View, Text, Image, Button, Input, ScrollView } from '@tarojs/components';
|
import { View, Text, Image, Button, Input, ScrollView } from '@tarojs/components';
|
||||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||||
import {
|
import {
|
||||||
BRAND_LOGO_MARK_URL,
|
|
||||||
QUALIFICATION_DISCLOSURE_URL,
|
|
||||||
isWxAuthorizeEnabled,
|
isWxAuthorizeEnabled,
|
||||||
type ClientRuntimeConfig,
|
type ClientRuntimeConfig,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -13,6 +11,11 @@ import WechatShareReady from '../../components/WechatShareReady';
|
|||||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
import { bindWechatForUser } from '../../lib/wechat-auth';
|
import { bindWechatForUser } from '../../lib/wechat-auth';
|
||||||
|
import {
|
||||||
|
applyBrandFromClientConfig,
|
||||||
|
getBrandAssetsSync,
|
||||||
|
loadBrandAssets,
|
||||||
|
} from '../../lib/brand-assets';
|
||||||
import {
|
import {
|
||||||
fetchMiniWechatUserInfo,
|
fetchMiniWechatUserInfo,
|
||||||
isDefaultMiniNickname,
|
isDefaultMiniNickname,
|
||||||
@@ -23,11 +26,13 @@ import {
|
|||||||
} from '../../lib/mini-wechat-profile';
|
} from '../../lib/mini-wechat-profile';
|
||||||
import { isLoggedIn, logout, request, toast, type UserProfile } from '../../lib/api';
|
import { isLoggedIn, logout, request, toast, type UserProfile } from '../../lib/api';
|
||||||
import { isWechatEnv } from '../../lib/weixin';
|
import { isWechatEnv } from '../../lib/weixin';
|
||||||
|
import { APP_VERSION_LABEL } from '../../lib/client-version';
|
||||||
import { maskPhone } from '../../lib/phone';
|
import { maskPhone } from '../../lib/phone';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
applyShareFromClientConfig,
|
||||||
DEFAULT_SHARE_TITLE,
|
buildSceneSharePayload,
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import iconPendingPay from '../../assets/icons/待付款.png';
|
import iconPendingPay from '../../assets/icons/待付款.png';
|
||||||
import iconPaid from '../../assets/icons/已付款.png';
|
import iconPaid from '../../assets/icons/已付款.png';
|
||||||
@@ -69,7 +74,11 @@ export default function MinePage() {
|
|||||||
const [savingProfile, setSavingProfile] = useState(false);
|
const [savingProfile, setSavingProfile] = useState(false);
|
||||||
const [profileLoadError, setProfileLoadError] = useState('');
|
const [profileLoadError, setProfileLoadError] = useState('');
|
||||||
const [qualificationOpen, setQualificationOpen] = useState(false);
|
const [qualificationOpen, setQualificationOpen] = useState(false);
|
||||||
|
const [brandMarkUrl, setBrandMarkUrl] = useState(() => getBrandAssetsSync().brandLogoMarkUrl);
|
||||||
|
const [qualificationUrl, setQualificationUrl] = useState(
|
||||||
|
() => getBrandAssetsSync().qualificationDisclosureUrl,
|
||||||
|
);
|
||||||
|
const [shareTick, setShareTick] = useState(0);
|
||||||
function resetGuestState() {
|
function resetGuestState() {
|
||||||
setProfile(null);
|
setProfile(null);
|
||||||
setBenefitBalance(0);
|
setBenefitBalance(0);
|
||||||
@@ -140,24 +149,30 @@ export default function MinePage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
request<ClientRuntimeConfig>('/common/client-config')
|
request<ClientRuntimeConfig>('/common/client-config')
|
||||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
.then((config) => {
|
||||||
.catch(() => setWxAuthorize(true));
|
setWxAuthorize(isWxAuthorizeEnabled(config));
|
||||||
|
const brand = applyBrandFromClientConfig(config);
|
||||||
|
applyShareFromClientConfig(config);
|
||||||
|
setBrandMarkUrl(brand.brandLogoMarkUrl);
|
||||||
|
setQualificationUrl(brand.qualificationDisclosureUrl);
|
||||||
|
setShareTick((n) => n + 1);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setWxAuthorize(true);
|
||||||
|
void loadBrandAssets();
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: '杜康好客 · 我的',
|
buildSceneSharePayload('mine', {
|
||||||
desc: DEFAULT_SHARE_DESC,
|
path: '/pages/mine/index',
|
||||||
path: '/pages/mine/index',
|
}),
|
||||||
}),
|
[shareTick],
|
||||||
[],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() => toWeappShareTimeline(sharePayload));
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
|
||||||
query: '',
|
|
||||||
}));
|
|
||||||
|
|
||||||
async function ensureWechatBound(): Promise<boolean> {
|
async function ensureWechatBound(): Promise<boolean> {
|
||||||
if (profile?.hasWechat) return true;
|
if (profile?.hasWechat) return true;
|
||||||
@@ -303,7 +318,7 @@ export default function MinePage() {
|
|||||||
if (displayAvatarUrl) {
|
if (displayAvatarUrl) {
|
||||||
return <Image className="mine-avatar-img" src={displayAvatarUrl} mode="aspectFill" />;
|
return <Image className="mine-avatar-img" src={displayAvatarUrl} mode="aspectFill" />;
|
||||||
}
|
}
|
||||||
return <Image className="mine-avatar-img" src={BRAND_LOGO_MARK_URL} mode="aspectFit" />;
|
return <Image className="mine-avatar-img" src={brandMarkUrl} mode="aspectFit" />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!authed) {
|
if (!authed) {
|
||||||
@@ -316,7 +331,7 @@ export default function MinePage() {
|
|||||||
<View className="mine-profile">
|
<View className="mine-profile">
|
||||||
<View className="mine-avatar-wrap mine-avatar-wrap--action" onClick={() => goLogin('/pages/mine/index')}>
|
<View className="mine-avatar-wrap mine-avatar-wrap--action" onClick={() => goLogin('/pages/mine/index')}>
|
||||||
<View className="mine-avatar mine-avatar--wx-pending">
|
<View className="mine-avatar mine-avatar--wx-pending">
|
||||||
<Image className="mine-avatar-img" src={BRAND_LOGO_MARK_URL} mode="aspectFit" />
|
<Image className="mine-avatar-img" src={brandMarkUrl} mode="aspectFit" />
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
<View>
|
<View>
|
||||||
@@ -499,7 +514,7 @@ export default function MinePage() {
|
|||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="mine-footer">
|
<View className="mine-footer">
|
||||||
<Text className="mine-version">杜康好客</Text>
|
<Text className="mine-version">杜康好客 {APP_VERSION_LABEL}</Text>
|
||||||
<Text className="mine-logout" onClick={() => logout()}>
|
<Text className="mine-logout" onClick={() => logout()}>
|
||||||
退出登录
|
退出登录
|
||||||
</Text>
|
</Text>
|
||||||
@@ -525,7 +540,7 @@ export default function MinePage() {
|
|||||||
{previewAvatar ? (
|
{previewAvatar ? (
|
||||||
<Image className="mine-avatar-img" src={previewAvatar} mode="aspectFill" />
|
<Image className="mine-avatar-img" src={previewAvatar} mode="aspectFill" />
|
||||||
) : (
|
) : (
|
||||||
<Image className="mine-avatar-img" src={BRAND_LOGO_MARK_URL} mode="aspectFit" />
|
<Image className="mine-avatar-img" src={brandMarkUrl} mode="aspectFit" />
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
<Text className="mine-profile-avatar-tip">点击选择头像</Text>
|
<Text className="mine-profile-avatar-tip">点击选择头像</Text>
|
||||||
@@ -578,7 +593,7 @@ export default function MinePage() {
|
|||||||
<View className="mine-qualification-body">
|
<View className="mine-qualification-body">
|
||||||
<Image
|
<Image
|
||||||
className="mine-qualification-img"
|
className="mine-qualification-img"
|
||||||
src={QUALIFICATION_DISCLOSURE_URL}
|
src={qualificationUrl}
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -141,6 +141,14 @@ export default function OrderConfirmPickupPage() {
|
|||||||
const ready = await ensurePayReady(returnPath);
|
const ready = await ensurePayReady(returnPath);
|
||||||
if (!ready) return;
|
if (!ready) return;
|
||||||
|
|
||||||
|
const { confirm } = await Taro.showModal({
|
||||||
|
title: '确认提交订单',
|
||||||
|
content: `确认提交现场提货订单?共 ${quantity} 瓶,应付 ¥${Number(preview?.payAmount ?? 0).toFixed(2)}。`,
|
||||||
|
confirmText: '确认提交',
|
||||||
|
cancelText: '再想想',
|
||||||
|
});
|
||||||
|
if (!confirm) return;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -6,14 +6,25 @@ import SubPageHeader from '../../components/SubPageHeader';
|
|||||||
import ShareNavButton from '../../components/ShareNavButton';
|
import ShareNavButton from '../../components/ShareNavButton';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import ContactCsButton from '../../components/ContactCsButton';
|
import ContactCsButton from '../../components/ContactCsButton';
|
||||||
|
import LogisticsRichText from '../../components/LogisticsRichText';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||||
|
import {
|
||||||
|
formatEstimatedArrival,
|
||||||
|
isLogisticsNotArrived,
|
||||||
|
latestTrackNode,
|
||||||
|
ORDER_LOGISTICS_PREVIEW_STATUSES,
|
||||||
|
shouldLoadOrderTrack,
|
||||||
|
type OrderTrackEstimatedArrival,
|
||||||
|
type OrderTrackNode,
|
||||||
|
} from '../../lib/order-logistics-utils';
|
||||||
|
import { fetchOrderTrack } from '../../lib/order-logistics';
|
||||||
import { maskPhone } from '../../lib/phone';
|
import { maskPhone } from '../../lib/phone';
|
||||||
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
buildSceneSharePayload,
|
||||||
DEFAULT_SHARE_TITLE,
|
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import { usePageView } from '../../lib/usePageView';
|
import { usePageView } from '../../lib/usePageView';
|
||||||
|
|
||||||
@@ -44,8 +55,15 @@ type OrderDetail = {
|
|||||||
orderType?: string;
|
orderType?: string;
|
||||||
isProxyOrder?: boolean;
|
isProxyOrder?: boolean;
|
||||||
proxyPartnerName?: string | null;
|
proxyPartnerName?: string | null;
|
||||||
|
deliveryType?: string;
|
||||||
items?: OrderItem[];
|
items?: OrderItem[];
|
||||||
wechatConfirm?: WechatConfirmPayload | null;
|
wechatConfirm?: WechatConfirmPayload | null;
|
||||||
|
delivery?: {
|
||||||
|
provider?: string;
|
||||||
|
trackingNo?: string;
|
||||||
|
logisticsCompany?: string;
|
||||||
|
manualQueryUrl?: string;
|
||||||
|
} | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STATUS_LABELS: Record<string, string> = {
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
@@ -78,11 +96,41 @@ export default function OrderDetailPage() {
|
|||||||
usePageView('order_detail_view', orderId ? { orderId } : undefined);
|
usePageView('order_detail_view', orderId ? { orderId } : undefined);
|
||||||
const [order, setOrder] = useState<OrderDetail | null>(null);
|
const [order, setOrder] = useState<OrderDetail | null>(null);
|
||||||
const [confirming, setConfirming] = useState(false);
|
const [confirming, setConfirming] = useState(false);
|
||||||
|
const [latestTrack, setLatestTrack] = useState<OrderTrackNode | null>(null);
|
||||||
|
const [estimatedArrival, setEstimatedArrival] = useState<OrderTrackEstimatedArrival | null>(null);
|
||||||
|
const [trackLoading, setTrackLoading] = useState(false);
|
||||||
|
|
||||||
|
async function loadOrderTrack(delivery: OrderDetail['delivery'], orderStatus?: string) {
|
||||||
|
if (!orderId || !shouldLoadOrderTrack(delivery)) {
|
||||||
|
setLatestTrack(null);
|
||||||
|
setEstimatedArrival(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTrackLoading(true);
|
||||||
|
try {
|
||||||
|
const track = await fetchOrderTrack(orderId);
|
||||||
|
const nodes = track.nodes ?? [];
|
||||||
|
setLatestTrack(latestTrackNode(nodes));
|
||||||
|
setEstimatedArrival(
|
||||||
|
isLogisticsNotArrived(nodes, orderStatus) && track.estimatedArrival
|
||||||
|
? track.estimatedArrival
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
setLatestTrack(null);
|
||||||
|
setEstimatedArrival(null);
|
||||||
|
} finally {
|
||||||
|
setTrackLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!orderId) return;
|
if (!orderId) return;
|
||||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||||
.then(setOrder)
|
.then((data) => {
|
||||||
|
setOrder(data);
|
||||||
|
void loadOrderTrack(data.delivery, data.status);
|
||||||
|
})
|
||||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||||
}, [orderId]);
|
}, [orderId]);
|
||||||
|
|
||||||
@@ -90,7 +138,10 @@ export default function OrderDetailPage() {
|
|||||||
if (!orderId) return;
|
if (!orderId) return;
|
||||||
// 从微信确认收货组件返回后刷新
|
// 从微信确认收货组件返回后刷新
|
||||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||||
.then(setOrder)
|
.then((data) => {
|
||||||
|
setOrder(data);
|
||||||
|
void loadOrderTrack(data.delivery, data.status);
|
||||||
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,6 +150,18 @@ export default function OrderDetailPage() {
|
|||||||
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
||||||
const canConfirmReceive =
|
const canConfirmReceive =
|
||||||
!!order && !isReship && !isProxy && ['PENDING_RECEIVE', 'DELIVERED'].includes(order.status || '');
|
!!order && !isReship && !isProxy && ['PENDING_RECEIVE', 'DELIVERED'].includes(order.status || '');
|
||||||
|
const canViewLogistics =
|
||||||
|
!!order &&
|
||||||
|
order.deliveryType !== 'ON_SITE_PICKUP' &&
|
||||||
|
!isReship &&
|
||||||
|
['PENDING_SHIP', 'OUT_WAREHOUSE', 'SHIPPING', 'SHIPPED', 'PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(
|
||||||
|
order.status || '',
|
||||||
|
);
|
||||||
|
const showLogisticsPreview =
|
||||||
|
canViewLogistics &&
|
||||||
|
ORDER_LOGISTICS_PREVIEW_STATUSES.includes(
|
||||||
|
(order?.status || '') as (typeof ORDER_LOGISTICS_PREVIEW_STATUSES)[number],
|
||||||
|
);
|
||||||
|
|
||||||
const item = order?.items?.[0];
|
const item = order?.items?.[0];
|
||||||
const productName = item?.productName || order?.productName || '杜康商品';
|
const productName = item?.productName || order?.productName || '杜康商品';
|
||||||
@@ -111,19 +174,20 @@ export default function OrderDetailPage() {
|
|||||||
: '';
|
: '';
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: productName !== '杜康商品' ? `我买了${productName} · 杜康好客` : DEFAULT_SHARE_TITLE,
|
buildSceneSharePayload('orderDetail', {
|
||||||
desc: DEFAULT_SHARE_DESC,
|
path: orderId ? `/pages/order-detail/index?id=${orderId}` : '/pages/home/index',
|
||||||
path: orderId ? `/pages/order-detail/index?id=${orderId}` : '/pages/home/index',
|
titleVars: {
|
||||||
}),
|
productName: productName && productName !== '杜康商品' ? productName : '',
|
||||||
|
},
|
||||||
|
}),
|
||||||
[productName, orderId],
|
[productName, orderId],
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() =>
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
toWeappShareTimeline(sharePayload, orderId ? `id=${orderId}` : ''),
|
||||||
query: orderId ? `id=${orderId}` : '',
|
);
|
||||||
}));
|
|
||||||
|
|
||||||
function goPay() {
|
function goPay() {
|
||||||
if (!order) return;
|
if (!order) return;
|
||||||
@@ -134,6 +198,11 @@ export default function OrderDetailPage() {
|
|||||||
Taro.navigateTo({ url: '/pages/customer-service/index' });
|
Taro.navigateTo({ url: '/pages/customer-service/index' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function goLogistics() {
|
||||||
|
if (!order) return;
|
||||||
|
Taro.navigateTo({ url: `/pages/order-logistics/index?id=${order.id}` });
|
||||||
|
}
|
||||||
|
|
||||||
async function confirmReceive() {
|
async function confirmReceive() {
|
||||||
if (!order || !canConfirmReceive || confirming) return;
|
if (!order || !canConfirmReceive || confirming) return;
|
||||||
|
|
||||||
@@ -211,6 +280,34 @@ export default function OrderDetailPage() {
|
|||||||
{isProxy && order.proxyPartnerName ? (
|
{isProxy && order.proxyPartnerName ? (
|
||||||
<Text className="order-proxy-hint">由合伙人 {order.proxyPartnerName} 代下</Text>
|
<Text className="order-proxy-hint">由合伙人 {order.proxyPartnerName} 代下</Text>
|
||||||
) : null}
|
) : null}
|
||||||
|
{showLogisticsPreview ? (
|
||||||
|
<View className="order-logistics-preview-block">
|
||||||
|
<View className="order-logistics-preview" onClick={goLogistics}>
|
||||||
|
<View className="order-logistics-preview-main">
|
||||||
|
{trackLoading ? (
|
||||||
|
<Text className="order-logistics-preview-info u-muted">物流信息加载中…</Text>
|
||||||
|
) : latestTrack?.trackInfo ? (
|
||||||
|
<LogisticsRichText
|
||||||
|
text={latestTrack.trackInfo}
|
||||||
|
className="order-logistics-preview-info"
|
||||||
|
/>
|
||||||
|
) : order.delivery?.manualQueryUrl ? (
|
||||||
|
<Text className="order-logistics-preview-info u-muted">物流已更新,点击查看详情</Text>
|
||||||
|
) : (
|
||||||
|
<Text className="order-logistics-preview-info u-muted">物流信息待更新,请稍后查看</Text>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
<Text className="order-logistics-preview-link">物流详情</Text>
|
||||||
|
</View>
|
||||||
|
{estimatedArrival ? (
|
||||||
|
<Text className="order-logistics-eta">{formatEstimatedArrival(estimatedArrival)}</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
) : canViewLogistics ? (
|
||||||
|
<Text className="order-logistics-link" onClick={goLogistics}>
|
||||||
|
查看物流追踪
|
||||||
|
</Text>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
<View className="order-card">
|
<View className="order-card">
|
||||||
<Text className="order-card-title">商品信息</Text>
|
<Text className="order-card-title">商品信息</Text>
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export default definePageConfig({
|
||||||
|
navigationStyle: 'custom',
|
||||||
|
navigationBarTitleText: '物流详情',
|
||||||
|
});
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { View, Text, Image } from '@tarojs/components';
|
||||||
|
import Taro, { useRouter } from '@tarojs/taro';
|
||||||
|
import PageShell from '../../components/PageShell';
|
||||||
|
import SubPageHeader from '../../components/SubPageHeader';
|
||||||
|
import LogisticsRichText from '../../components/LogisticsRichText';
|
||||||
|
import { request, toast } from '../../lib/api';
|
||||||
|
import {
|
||||||
|
deliveryProviderLabel,
|
||||||
|
formatTrackNodeTime,
|
||||||
|
shouldLoadOrderTrack,
|
||||||
|
sortTrackNodesOldestFirst,
|
||||||
|
type OrderDelivery,
|
||||||
|
type OrderTrackNode,
|
||||||
|
} from '../../lib/order-logistics-utils';
|
||||||
|
import { fetchOrderTrack } from '../../lib/order-logistics';
|
||||||
|
import { usePageView } from '../../lib/usePageView';
|
||||||
|
|
||||||
|
type OrderDetail = {
|
||||||
|
id: string;
|
||||||
|
orderNo?: string;
|
||||||
|
status?: string;
|
||||||
|
delivery?: OrderDelivery | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function OrderLogisticsPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const orderId = router.params.id ?? '';
|
||||||
|
usePageView('order_logistics_view', orderId ? { orderId } : undefined);
|
||||||
|
const [order, setOrder] = useState<OrderDetail | null>(null);
|
||||||
|
const [trackNodes, setTrackNodes] = useState<OrderTrackNode[]>([]);
|
||||||
|
const [signPhotoUrls, setSignPhotoUrls] = useState<string[]>([]);
|
||||||
|
const [trackLoading, setTrackLoading] = useState(false);
|
||||||
|
|
||||||
|
const sortedTrackNodes = useMemo(
|
||||||
|
() => (Array.isArray(trackNodes) ? sortTrackNodesOldestFirst(trackNodes) : []),
|
||||||
|
[trackNodes],
|
||||||
|
);
|
||||||
|
const timelineComplete = ['PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(
|
||||||
|
order?.status || '',
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!orderId) return;
|
||||||
|
let cancelled = false;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const data = await request<OrderDetail>(`/trade/orders/${orderId}`);
|
||||||
|
if (cancelled) return;
|
||||||
|
setOrder(data);
|
||||||
|
if (!shouldLoadOrderTrack(data.delivery)) {
|
||||||
|
setTrackNodes([]);
|
||||||
|
setSignPhotoUrls([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTrackLoading(true);
|
||||||
|
try {
|
||||||
|
const track = await fetchOrderTrack(orderId);
|
||||||
|
if (!cancelled) {
|
||||||
|
setTrackNodes(track.nodes ?? []);
|
||||||
|
setSignPhotoUrls(track.signPhotoUrls ?? []);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) {
|
||||||
|
setTrackNodes([]);
|
||||||
|
setSignPhotoUrls([]);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) setTrackLoading(false);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!cancelled) toast(e instanceof Error ? e.message : '加载失败');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [orderId]);
|
||||||
|
|
||||||
|
function openManualQuery() {
|
||||||
|
const url = order?.delivery?.manualQueryUrl?.trim();
|
||||||
|
if (!url) {
|
||||||
|
toast('暂无物流查询链接');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (process.env.TARO_ENV === 'h5' && typeof window !== 'undefined') {
|
||||||
|
window.open(url, '_blank');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Taro.setClipboardData({ data: url })
|
||||||
|
.then(() => toast('查询链接已复制,请在浏览器中打开'))
|
||||||
|
.catch(() => toast('无法打开物流查询'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewSignPhotos(index: number) {
|
||||||
|
if (signPhotoUrls.length === 0) return;
|
||||||
|
Taro.previewImage({ current: signPhotoUrls[index], urls: signPhotoUrls }).catch(() =>
|
||||||
|
toast('无法预览图片'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const delivery = order?.delivery;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageShell variant="sub" className="order-logistics-page">
|
||||||
|
<SubPageHeader title="物流详情" />
|
||||||
|
<View className="sub-page-body order-logistics-body">
|
||||||
|
{!order ? (
|
||||||
|
<View className="u-empty">加载中…</View>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<View className="order-card order-logistics-info-card">
|
||||||
|
<Text className="order-card-title">物流信息</Text>
|
||||||
|
<View className="order-row">
|
||||||
|
<Text className="order-row-label">配送方式</Text>
|
||||||
|
<Text className="order-row-value">
|
||||||
|
{deliveryProviderLabel(delivery?.provider, delivery?.logisticsCompany)}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
{delivery?.trackingNo ? (
|
||||||
|
<View className="order-row">
|
||||||
|
<Text className="order-row-label">运单号</Text>
|
||||||
|
<Text className="order-row-value">{delivery.trackingNo}</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
{delivery?.manualQueryUrl ? (
|
||||||
|
<View className="order-row">
|
||||||
|
<Text className="order-row-label">物流查询</Text>
|
||||||
|
<Text className="order-row-value order-row-value--link" onClick={openManualQuery}>
|
||||||
|
查看物流
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
{!delivery?.trackingNo && !delivery?.manualQueryUrl ? (
|
||||||
|
<Text className="u-muted">物流信息待更新,请稍后查看</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{signPhotoUrls.length > 0 ? (
|
||||||
|
<View className="order-card">
|
||||||
|
<Text className="order-card-title">签收照片</Text>
|
||||||
|
<View className="order-logistics-sign-photos">
|
||||||
|
{signPhotoUrls.map((url, index) => (
|
||||||
|
<Image
|
||||||
|
key={url}
|
||||||
|
className="order-logistics-sign-photo"
|
||||||
|
src={url}
|
||||||
|
mode="aspectFill"
|
||||||
|
onClick={() => previewSignPhotos(index)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{trackLoading ? (
|
||||||
|
<View className="order-card">
|
||||||
|
<Text className="order-card-title">物流动态</Text>
|
||||||
|
<Text className="u-muted">加载中…</Text>
|
||||||
|
</View>
|
||||||
|
) : sortedTrackNodes.length > 0 ? (
|
||||||
|
<View className="order-card">
|
||||||
|
<Text className="order-card-title">物流动态</Text>
|
||||||
|
<View
|
||||||
|
className={`order-logistics-timeline${
|
||||||
|
timelineComplete ? ' order-logistics-timeline--complete' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{sortedTrackNodes.map((node, index) => {
|
||||||
|
const isLatest = index === sortedTrackNodes.length - 1;
|
||||||
|
return (
|
||||||
|
<View
|
||||||
|
key={`${node.trackInfo}-${node.createTime}-${index}`}
|
||||||
|
className={[
|
||||||
|
'order-logistics-timeline-item',
|
||||||
|
'order-logistics-timeline-item--done',
|
||||||
|
isLatest ? 'order-logistics-timeline-item--latest' : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')}
|
||||||
|
>
|
||||||
|
<View className="order-logistics-timeline-dot" />
|
||||||
|
<View className="order-logistics-timeline-body">
|
||||||
|
{node.statusName ? (
|
||||||
|
<Text className="order-logistics-timeline-status">{node.statusName}</Text>
|
||||||
|
) : null}
|
||||||
|
<LogisticsRichText
|
||||||
|
text={node.trackInfo || '—'}
|
||||||
|
className="order-logistics-node-info"
|
||||||
|
/>
|
||||||
|
<Text className="order-logistics-node-time">{formatTrackNodeTime(node)}</Text>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
) : shouldLoadOrderTrack(delivery) ? (
|
||||||
|
<View className="order-card">
|
||||||
|
<Text className="order-card-title">物流动态</Text>
|
||||||
|
<Text className="u-muted">暂无路由信息,请稍后刷新</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
|
</PageShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,6 @@ import type { ProductDetailContentDto } from '@dukang/shared-types';
|
|||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import PageNavBar from '../../components/PageNavBar';
|
import PageNavBar from '../../components/PageNavBar';
|
||||||
import ProductCarousel from '../../components/ProductCarousel';
|
import ProductCarousel from '../../components/ProductCarousel';
|
||||||
import ShareNavButton from '../../components/ShareNavButton';
|
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
import { ensurePayReady } from '../../lib/pay-ready';
|
import { ensurePayReady } from '../../lib/pay-ready';
|
||||||
@@ -28,9 +27,9 @@ import {
|
|||||||
normalizeFulfillmentFlags,
|
normalizeFulfillmentFlags,
|
||||||
} from '../../lib/product-fulfillment';
|
} from '../../lib/product-fulfillment';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
buildSceneSharePayload,
|
||||||
DEFAULT_SHARE_TITLE,
|
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
import iconHome from '../../assets/tabbar/home.png';
|
import iconHome from '../../assets/tabbar/home.png';
|
||||||
import { usePageView } from '../../lib/usePageView';
|
import { usePageView } from '../../lib/usePageView';
|
||||||
@@ -89,21 +88,20 @@ export default function ProductDetailPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: product?.name || DEFAULT_SHARE_TITLE,
|
buildSceneSharePayload('productDetail', {
|
||||||
desc: product?.subtitle || DEFAULT_SHARE_DESC,
|
path: `/pages/product-detail/index?id=${productId}`,
|
||||||
path: `/pages/product-detail/index?id=${productId}`,
|
dynamicTitle: product?.name,
|
||||||
imgUrl: (product ? getProductMainImage(product) : '') || undefined,
|
dynamicDesc: product?.subtitle,
|
||||||
}),
|
dynamicImageUrl: product ? getProductMainImage(product) : undefined,
|
||||||
|
}),
|
||||||
[product, productId],
|
[product, productId],
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() =>
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
toWeappShareTimeline(sharePayload, productId ? `id=${productId}` : ''),
|
||||||
query: productId ? `id=${productId}` : '',
|
);
|
||||||
imageUrl: sharePayload.imgUrl,
|
|
||||||
}));
|
|
||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
const pages = Taro.getCurrentPages();
|
const pages = Taro.getCurrentPages();
|
||||||
@@ -167,12 +165,11 @@ export default function ProductDetailPage() {
|
|||||||
solid={headerSolid}
|
solid={headerSolid}
|
||||||
titleVisible={headerSolid}
|
titleVisible={headerSolid}
|
||||||
onBack={goBack}
|
onBack={goBack}
|
||||||
right={<ShareNavButton payload={sharePayload} />}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<View className="product-detail-main">
|
<View className="product-detail-main">
|
||||||
<View className="product-detail-hero full-bleed">
|
<View className="product-detail-hero full-bleed">
|
||||||
<ProductCarousel images={carouselImages} alt={product.name} variant="detail" />
|
<ProductCarousel images={carouselImages} alt={product.name} variant="detail" previewable />
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="product-detail-info">
|
<View className="product-detail-info">
|
||||||
|
|||||||
@@ -15,11 +15,13 @@ import ShareNavButton from '../../components/ShareNavButton';
|
|||||||
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import { maskPhone } from '../../lib/phone';
|
||||||
|
import { track } from '../../lib/analytics';
|
||||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
buildSceneSharePayload,
|
||||||
DEFAULT_SHARE_TITLE,
|
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
|
|
||||||
type StoreMedia = {
|
type StoreMedia = {
|
||||||
@@ -235,18 +237,15 @@ export default function StoreDetailPage() {
|
|||||||
void loadRecentRedeems(id);
|
void loadRecentRedeems(id);
|
||||||
});
|
});
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(() => {
|
||||||
() => {
|
const envFirst = store ? envPhotoUrls(store)[0] : undefined;
|
||||||
const envFirst = store ? envPhotoUrls(store)[0] : undefined;
|
return buildSceneSharePayload('storeDetail', {
|
||||||
return {
|
path: `/pages/store-detail/index?id=${storeId}`,
|
||||||
title: store?.name || DEFAULT_SHARE_TITLE,
|
dynamicTitle: store?.name,
|
||||||
desc: store?.intro?.trim() || store?.address || DEFAULT_SHARE_DESC,
|
dynamicDesc: store?.intro?.trim() || store?.address,
|
||||||
path: `/pages/store-detail/index?id=${storeId}`,
|
dynamicImageUrl: store?.coverUrl || envFirst || store?.carouselUrls?.[0],
|
||||||
imgUrl: store?.coverUrl || envFirst || store?.carouselUrls?.[0] || undefined,
|
});
|
||||||
};
|
}, [store, storeId]);
|
||||||
},
|
|
||||||
[store, storeId],
|
|
||||||
);
|
|
||||||
|
|
||||||
const marqueeLines = useMemo(
|
const marqueeLines = useMemo(
|
||||||
() => recentRedeems.map(formatRecentRedeemLine).filter(Boolean),
|
() => recentRedeems.map(formatRecentRedeemLine).filter(Boolean),
|
||||||
@@ -254,11 +253,9 @@ export default function StoreDetailPage() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() =>
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
toWeappShareTimeline(sharePayload, storeId ? `id=${storeId}` : ''),
|
||||||
query: storeId ? `id=${storeId}` : '',
|
);
|
||||||
imageUrl: sharePayload.imgUrl,
|
|
||||||
}));
|
|
||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
const pages = Taro.getCurrentPages();
|
const pages = Taro.getCurrentPages();
|
||||||
@@ -271,6 +268,7 @@ export default function StoreDetailPage() {
|
|||||||
toast('暂无门店电话');
|
toast('暂无门店电话');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
track('store_phone_call', { storeId: store.id });
|
||||||
Taro.makePhoneCall({ phoneNumber: store.phone }).catch(() => toast('无法拨打电话'));
|
Taro.makePhoneCall({ phoneNumber: store.phone }).catch(() => toast('无法拨打电话'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,12 +315,19 @@ export default function StoreDetailPage() {
|
|||||||
|
|
||||||
const envPhotos = envPhotoUrls(store);
|
const envPhotos = envPhotoUrls(store);
|
||||||
const heroImages = uniqueUrls([store.coverUrl, ...(store.carouselUrls || [])]);
|
const heroImages = uniqueUrls([store.coverUrl, ...(store.carouselUrls || [])]);
|
||||||
|
const packages = store.packages ?? [];
|
||||||
|
|
||||||
const intro = store.intro?.trim() || '';
|
const intro = store.intro?.trim() || '';
|
||||||
const benefitRuleRaw = store.benefitUsageRule?.trim() || '';
|
const benefitRuleRaw = store.benefitUsageRule?.trim() || '';
|
||||||
const benefitRule =
|
const benefitRule =
|
||||||
benefitRuleRaw && !/^null$/i.test(benefitRuleRaw) ? benefitRuleRaw : '';
|
benefitRuleRaw && !/^null$/i.test(benefitRuleRaw) ? benefitRuleRaw : '';
|
||||||
|
|
||||||
|
function openPackageDetail(index: number) {
|
||||||
|
Taro.navigateTo({
|
||||||
|
url: `/pages/store-package-detail/index?storeId=${storeId}&index=${index}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function previewEnv(index: number) {
|
function previewEnv(index: number) {
|
||||||
if (!envPhotos.length) return;
|
if (!envPhotos.length) return;
|
||||||
Taro.previewImage({
|
Taro.previewImage({
|
||||||
@@ -343,7 +348,13 @@ export default function StoreDetailPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<View className="store-detail-hero full-bleed">
|
<View className="store-detail-hero full-bleed">
|
||||||
<ProductCarousel images={heroImages} alt={store.name} variant="store" previewable />
|
<ProductCarousel
|
||||||
|
images={heroImages}
|
||||||
|
alt={store.name}
|
||||||
|
variant="store"
|
||||||
|
previewable
|
||||||
|
imageFit="contain"
|
||||||
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="store-detail-info-card">
|
<View className="store-detail-info-card">
|
||||||
@@ -374,7 +385,9 @@ export default function StoreDetailPage() {
|
|||||||
|
|
||||||
{store.phone ? (
|
{store.phone ? (
|
||||||
<View className="store-detail-row">
|
<View className="store-detail-row">
|
||||||
<Text className="store-detail-meta store-detail-meta--flex">电话: {store.phone}</Text>
|
<Text className="store-detail-meta store-detail-meta--flex">
|
||||||
|
电话: {maskPhone(store.phone)}
|
||||||
|
</Text>
|
||||||
<Text className="store-detail-action" onClick={callStore}>
|
<Text className="store-detail-action" onClick={callStore}>
|
||||||
拨打
|
拨打
|
||||||
</Text>
|
</Text>
|
||||||
@@ -396,26 +409,20 @@ export default function StoreDetailPage() {
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{store.packages && store.packages.length > 0 ? (
|
{packages.length > 0 ? (
|
||||||
<View className="store-detail-section">
|
<View className="store-detail-section store-detail-section--packages">
|
||||||
<Text className="store-detail-section-title">门店套餐</Text>
|
<Text className="store-detail-section-title">门店套餐</Text>
|
||||||
{store.packages.map((pkg, index) => (
|
<View className="store-detail-package-list">
|
||||||
<View key={`${pkg.name}-${index}`} className="store-detail-package-card">
|
{packages.map((pkg, index) => (
|
||||||
{pkg.imageUrl ? (
|
<View
|
||||||
<Image className="store-detail-package-img" src={pkg.imageUrl} mode="aspectFill" />
|
key={`${pkg.name}-${index}`}
|
||||||
) : null}
|
className="store-detail-package-list-item"
|
||||||
<Text className="store-detail-package-name">{pkg.name}</Text>
|
onClick={() => openPackageDetail(index)}
|
||||||
<Text className="store-detail-package-body">
|
>
|
||||||
{formatRedeemAmountYuan(pkg.price)} 元 · {pkg.dishes}
|
<Text className="store-detail-package-list-title">{pkg.name}</Text>
|
||||||
</Text>
|
</View>
|
||||||
{pkg.usableTime ? (
|
))}
|
||||||
<Text className="store-detail-package-meta">使用时间:{pkg.usableTime}</Text>
|
</View>
|
||||||
) : null}
|
|
||||||
{pkg.otherNotes ? (
|
|
||||||
<Text className="store-detail-package-meta">说明:{pkg.otherNotes}</Text>
|
|
||||||
) : null}
|
|
||||||
</View>
|
|
||||||
))}
|
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export default definePageConfig({
|
||||||
|
navigationStyle: 'custom',
|
||||||
|
navigationBarTitleText: '套餐详情',
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import { useCallback, useState } from 'react';
|
||||||
|
import { View, Text, Image } from '@tarojs/components';
|
||||||
|
import Taro, { useLoad, useRouter } from '@tarojs/taro';
|
||||||
|
import PageShell from '../../components/PageShell';
|
||||||
|
import PageNavBar from '../../components/PageNavBar';
|
||||||
|
import { request, toast } from '../../lib/api';
|
||||||
|
|
||||||
|
type StorePackage = {
|
||||||
|
name: string;
|
||||||
|
price: string | number;
|
||||||
|
dishes: string;
|
||||||
|
usableTime?: string | null;
|
||||||
|
otherNotes?: string | null;
|
||||||
|
imageUrl?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Store = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
packages?: StorePackage[] | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function pickStoreId(raw?: string | null) {
|
||||||
|
return String(raw || '')
|
||||||
|
.trim()
|
||||||
|
.replace(/[^\d]/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePackageIndex(raw?: string | null) {
|
||||||
|
const n = Number.parseInt(String(raw ?? ''), 10);
|
||||||
|
return Number.isFinite(n) && n >= 0 ? n : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPriceYuan(price: string | number) {
|
||||||
|
const n = typeof price === 'number' ? price : Number(price);
|
||||||
|
if (!Number.isFinite(n)) return '0';
|
||||||
|
if (Math.abs(n - Math.round(n)) < 1e-9) return String(Math.round(n));
|
||||||
|
return n.toFixed(2).replace(/\.?0+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function StorePackageDetailPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [storeId, setStoreId] = useState(() => pickStoreId(router.params.storeId));
|
||||||
|
const [storeName, setStoreName] = useState('');
|
||||||
|
const [pkg, setPkg] = useState<StorePackage | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [loadError, setLoadError] = useState('');
|
||||||
|
|
||||||
|
const loadPackage = useCallback(async (sid: string, index: number) => {
|
||||||
|
if (!sid) {
|
||||||
|
setLoading(false);
|
||||||
|
setLoadError('缺少门店参数');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (index < 0) {
|
||||||
|
setLoading(false);
|
||||||
|
setLoadError('套餐不存在');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoadError('');
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await request<Store>(`/stores/${sid}`);
|
||||||
|
const packages = data?.packages ?? [];
|
||||||
|
const item = packages[index];
|
||||||
|
if (!data?.id || !item) {
|
||||||
|
setPkg(null);
|
||||||
|
setLoadError('套餐不存在或已下架');
|
||||||
|
toast('套餐不存在或已下架');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setStoreName(data.name);
|
||||||
|
setPkg(item);
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : '加载失败';
|
||||||
|
setLoadError(msg);
|
||||||
|
toast(msg);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useLoad((options) => {
|
||||||
|
const sid = pickStoreId(options?.storeId || router.params.storeId);
|
||||||
|
const index = parsePackageIndex(options?.index ?? router.params.index);
|
||||||
|
setStoreId(sid);
|
||||||
|
void loadPackage(sid, index);
|
||||||
|
});
|
||||||
|
|
||||||
|
function goBack() {
|
||||||
|
const pages = Taro.getCurrentPages();
|
||||||
|
if (pages.length > 1) Taro.navigateBack();
|
||||||
|
else if (storeId) {
|
||||||
|
Taro.redirectTo({ url: `/pages/store-detail/index?id=${storeId}` });
|
||||||
|
} else {
|
||||||
|
Taro.switchTab({ url: '/pages/stores/index' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewImage(url: string) {
|
||||||
|
Taro.previewImage({ urls: [url], current: url }).catch(() => toast('无法预览图片'));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<PageShell variant="scroll" className="store-package-detail-page">
|
||||||
|
<PageNavBar title="套餐详情" solid onBack={goBack} />
|
||||||
|
<View className="page-with-nav-bar u-empty">加载中…</View>
|
||||||
|
</PageShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pkg) {
|
||||||
|
return (
|
||||||
|
<PageShell variant="scroll" className="store-package-detail-page">
|
||||||
|
<PageNavBar title="套餐详情" solid onBack={goBack} />
|
||||||
|
<View className="page-with-nav-bar u-empty">{loadError || '套餐不存在'}</View>
|
||||||
|
</PageShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageUrl = (pkg.imageUrl || '').trim();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PageShell variant="scroll" className="store-package-detail-page">
|
||||||
|
<PageNavBar title={pkg.name} solid titleVisible onBack={goBack} />
|
||||||
|
|
||||||
|
<View className="store-package-detail-body">
|
||||||
|
<View className="store-package-detail-inner">
|
||||||
|
<View className="store-package-detail-header">
|
||||||
|
<View className="store-package-detail-title-row">
|
||||||
|
<Text className="store-package-detail-title">{pkg.name}</Text>
|
||||||
|
<Text className="store-package-detail-price">¥{formatPriceYuan(pkg.price)}</Text>
|
||||||
|
</View>
|
||||||
|
{storeName ? (
|
||||||
|
<Text className="store-package-detail-store">{storeName}</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
|
||||||
|
{imageUrl ? (
|
||||||
|
<View
|
||||||
|
className="store-package-detail-photo"
|
||||||
|
onClick={() => previewImage(imageUrl)}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
className="store-package-detail-photo-image"
|
||||||
|
src={imageUrl}
|
||||||
|
mode="widthFix"
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<View className="store-package-detail-content">
|
||||||
|
<View className="store-detail-package-field">
|
||||||
|
<Text className="store-detail-package-field-label">菜品</Text>
|
||||||
|
<Text className="store-detail-package-field-value">{pkg.dishes || '—'}</Text>
|
||||||
|
</View>
|
||||||
|
{pkg.usableTime ? (
|
||||||
|
<View className="store-detail-package-field">
|
||||||
|
<Text className="store-detail-package-field-label">使用时间</Text>
|
||||||
|
<Text className="store-detail-package-field-value">{pkg.usableTime}</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
{pkg.otherNotes ? (
|
||||||
|
<View className="store-detail-package-field">
|
||||||
|
<Text className="store-detail-package-field-label">其他说明</Text>
|
||||||
|
<Text className="store-detail-package-field-value">{pkg.otherNotes}</Text>
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</PageShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { View, Text, Image, Input } from '@tarojs/components';
|
import { View, Text, Image, Input } from '@tarojs/components';
|
||||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||||
import { StoreStatus, STORE_STATUS_LABELS } from '@dukang/shared-types';
|
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import TabMainHeader from '../../components/TabMainHeader';
|
import TabMainHeader from '../../components/TabMainHeader';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
@@ -37,9 +36,9 @@ import {
|
|||||||
setStoresListCache,
|
setStoresListCache,
|
||||||
} from '../../lib/stores-session';
|
} from '../../lib/stores-session';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
buildSceneSharePayload,
|
||||||
DEFAULT_SHARE_TITLE,
|
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
|
toWeappShareTimeline,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
|
|
||||||
type Store = {
|
type Store = {
|
||||||
@@ -342,33 +341,24 @@ export default function StoresPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatHours(store: Store) {
|
function hoursLines(store: Store): string[] {
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
if (store.openTime && store.closeTime) parts.push(`${store.openTime}-${store.closeTime}`);
|
if (store.openTime && store.closeTime) parts.push(`${store.openTime}-${store.closeTime}`);
|
||||||
if (store.openTime2 && store.closeTime2) parts.push(`${store.openTime2}-${store.closeTime2}`);
|
if (store.openTime2 && store.closeTime2) parts.push(`${store.openTime2}-${store.closeTime2}`);
|
||||||
return parts.length ? `营业时间: ${parts.join(',')}` : '营业时间: 10:00-22:00';
|
if (!parts.length) parts.push('10:00-22:00');
|
||||||
}
|
return parts.map((p, i) => (i === 0 ? `营业时间: ${p}` : p));
|
||||||
|
|
||||||
function formatStatus(store: Store) {
|
|
||||||
const status = store.status as StoreStatus | undefined;
|
|
||||||
if (status && STORE_STATUS_LABELS[status]) return STORE_STATUS_LABELS[status];
|
|
||||||
return STORE_STATUS_LABELS[StoreStatus.OPEN];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() =>
|
||||||
title: '杜康好客门店',
|
buildSceneSharePayload('stores', {
|
||||||
desc: DEFAULT_SHARE_DESC,
|
path: '/pages/stores/index',
|
||||||
path: '/pages/stores/index',
|
}),
|
||||||
}),
|
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() => toWeappShareTimeline(sharePayload));
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
|
||||||
query: '',
|
|
||||||
}));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="tab" className="store-page no-tab-header">
|
<PageShell variant="tab" className="store-page no-tab-header">
|
||||||
@@ -437,30 +427,37 @@ export default function StoresPage() {
|
|||||||
<View className="store-card-cover store-card-cover--empty" />
|
<View className="store-card-cover store-card-cover--empty" />
|
||||||
)}
|
)}
|
||||||
<View className="store-card-body">
|
<View className="store-card-body">
|
||||||
<View className="store-card-head">
|
{/* 第1行:标题 + 距离 */}
|
||||||
<Text className="store-card-name">{s.name}</Text>
|
<View className="store-card-row store-card-row--head">
|
||||||
|
<Text className="store-card-name" numberOfLines={1}>
|
||||||
|
{s.name}
|
||||||
|
</Text>
|
||||||
<Text className="store-card-distance">
|
<Text className="store-card-distance">
|
||||||
{formatDistanceMeters(s.distanceMeters)}
|
{formatDistanceMeters(s.distanceMeters)}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
<View className="store-card-status-row">
|
{/* 第2行:营业时间(多段各占一行,居左) */}
|
||||||
<Text className="store-card-status">{formatStatus(s)}</Text>
|
<View className="store-card-hours">
|
||||||
<Text className="store-card-hours">{formatHours(s)}</Text>
|
{hoursLines(s).map((line) => (
|
||||||
|
<Text key={line} className="store-card-hours-line">
|
||||||
|
{line}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
</View>
|
</View>
|
||||||
<Text className="store-card-address">
|
{/* 第3行:地址(最多两行)+ 去核销 */}
|
||||||
{s.address || (s.district ? `${s.district}` : '地址待完善')}
|
<View className="store-card-row store-card-row--foot">
|
||||||
</Text>
|
<Text className="store-card-address" numberOfLines={2}>
|
||||||
<View className="store-card-footer">
|
{s.address || (s.district ? `${s.district}` : '地址待完善')}
|
||||||
<View className="store-card-footer-spacer" />
|
</Text>
|
||||||
<Text
|
<View
|
||||||
className="store-card-cta"
|
className="store-card-cta"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
Taro.navigateTo({ url: '/pages/redeem/index' });
|
Taro.navigateTo({ url: '/pages/redeem/index' });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
去核销
|
<Text className="store-card-cta-text">去核销</Text>
|
||||||
</Text>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -488,3 +488,188 @@
|
|||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.order-logistics-page {
|
||||||
|
background: var(--color-background);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-body {
|
||||||
|
padding-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-info-card {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-link {
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-preview {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: rgba(166, 29, 36, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-preview-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-preview-info {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
line-height: 1.5;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-preview-link {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-preview-block {
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-eta {
|
||||||
|
display: block;
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-on-surface-variant);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-phone-link {
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-sign-photos {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-sign-photo {
|
||||||
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--color-surface-container);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-row-value--link {
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline {
|
||||||
|
padding-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline--complete .order-logistics-timeline-item:not(:last-child)::before {
|
||||||
|
background: rgba(166, 29, 36, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
position: relative;
|
||||||
|
padding-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item:last-child {
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item:not(:last-child)::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
left: 5px;
|
||||||
|
top: 14px;
|
||||||
|
bottom: 0;
|
||||||
|
width: 1px;
|
||||||
|
background: rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item--done .order-logistics-timeline-dot {
|
||||||
|
background: var(--color-heritage-red);
|
||||||
|
box-shadow: 0 0 0 1px var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item--done:not(:last-child)::before {
|
||||||
|
background: rgba(166, 29, 36, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-dot {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 11px;
|
||||||
|
height: 11px;
|
||||||
|
margin-top: 4px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--color-surface-container-high, #e8e4df);
|
||||||
|
border: 2px solid #fff;
|
||||||
|
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item--latest .order-logistics-timeline-dot {
|
||||||
|
background: var(--color-heritage-red);
|
||||||
|
box-shadow: 0 0 0 2px rgba(166, 29, 36, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-status {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item--done .order-logistics-timeline-status {
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-timeline-item--latest .order-logistics-timeline-status {
|
||||||
|
color: var(--color-heritage-red);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-node {
|
||||||
|
padding: 10px 0;
|
||||||
|
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-node:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-node-time {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--color-on-surface-variant);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-logistics-node-info {
|
||||||
|
display: block;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,8 +10,24 @@
|
|||||||
.store-detail-carousel-wrap {
|
.store-detail-carousel-wrap {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 280px;
|
aspect-ratio: 4 / 3;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
/* background: var(--color-surface-container); */
|
||||||
|
background-color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 门店门头:固定 4:3 区域,图片 aspectFit 缩放完整显示(不裁剪) */
|
||||||
|
.store-detail-carousel-wrap--contain .store-detail-carousel-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-carousel-wrap--contain .store-detail-carousel-image {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: contain;
|
||||||
|
object-position: center center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-carousel {
|
.store-detail-carousel {
|
||||||
@@ -26,6 +42,12 @@
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.store-detail-carousel-image {
|
||||||
|
object-fit: cover;
|
||||||
|
object-position: center center;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
.store-detail-carousel-placeholder {
|
.store-detail-carousel-placeholder {
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
}
|
}
|
||||||
@@ -53,7 +75,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-info-card {
|
.store-detail-info-card {
|
||||||
margin: -40px var(--space-page) 16px;
|
margin: 0 var(--space-page) 16px;
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 2;
|
z-index: 2;
|
||||||
background: var(--color-card);
|
background: var(--color-card);
|
||||||
@@ -236,43 +258,146 @@
|
|||||||
margin-right: 0;
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-card {
|
.store-detail-section--packages {
|
||||||
padding: 12px 0;
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-list-item {
|
||||||
|
padding: 14px 0;
|
||||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-img {
|
.store-detail-package-list-item:first-child {
|
||||||
width: 100%;
|
padding-top: 4px;
|
||||||
height: 160px;
|
|
||||||
border-radius: var(--radius-md, 8px);
|
|
||||||
margin-bottom: 8px;
|
|
||||||
display: block;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-card:last-of-type {
|
.store-detail-package-list-item:last-child {
|
||||||
border-bottom: none;
|
border-bottom: none;
|
||||||
|
padding-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-name {
|
.store-detail-package-list-title {
|
||||||
display: block;
|
display: block;
|
||||||
font-size: 16px;
|
font-size: 15px;
|
||||||
|
line-height: 1.5;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--color-on-surface);
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-list-item:active {
|
||||||
|
opacity: 0.72;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── 套餐详情页(独立于门店详情) ── */
|
||||||
|
.store-package-detail-page {
|
||||||
|
background: var(--color-background);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-body {
|
||||||
|
/* 避开状态栏+胶囊导航,并额外 12px 顶白 */
|
||||||
|
padding: calc(var(--nav-bar-height, 56px) + 12px) 0 24px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-inner {
|
||||||
|
/* 左右留白,内容不贴边 */
|
||||||
|
padding: 8px 16px 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-header {
|
||||||
|
padding: 8px 16px 4px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-title-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-title {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
font-family: var(--font-headline);
|
||||||
|
font-size: 20px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--color-text-primary, #1a1a1a);
|
line-height: 1.4;
|
||||||
|
color: var(--color-ink-black);
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-price {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.35;
|
||||||
|
color: #a61d24;
|
||||||
|
color: var(--color-heritage-red, #a61d24);
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-store {
|
||||||
|
display: block;
|
||||||
|
margin-top: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--color-on-surface-variant);
|
||||||
|
padding-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-photo {
|
||||||
|
margin: 14px 0 0;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--color-card);
|
||||||
|
box-shadow: var(--shadow-card);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-photo-image {
|
||||||
|
width: 100%;
|
||||||
|
display: block;
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-package-detail-content {
|
||||||
|
margin-top: 16px;
|
||||||
|
background: var(--color-card);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 16px;
|
||||||
|
box-shadow: var(--shadow-card);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-field-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-on-surface-variant);
|
||||||
margin-bottom: 6px;
|
margin-bottom: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-body {
|
.store-detail-package-field-value {
|
||||||
display: block;
|
display: block;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: var(--color-text-secondary, #666);
|
color: var(--color-on-surface);
|
||||||
line-height: 1.5;
|
line-height: 1.7;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-meta {
|
.store-detail-package-field {
|
||||||
display: block;
|
margin-bottom: 16px;
|
||||||
font-size: 13px;
|
}
|
||||||
color: var(--color-text-tertiary, #999);
|
|
||||||
margin-top: 4px;
|
.store-detail-package-field:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-dispute {
|
.store-detail-package-dispute {
|
||||||
|
|||||||
@@ -144,24 +144,25 @@
|
|||||||
padding: 4px var(--space-page) 16px;
|
padding: 4px var(--space-page) 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 左图右文 */
|
||||||
.store-card {
|
.store-card {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
align-items: stretch;
|
align-items: flex-start;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
|
box-sizing: border-box;
|
||||||
background: var(--color-card);
|
background: var(--color-card);
|
||||||
border-radius: var(--radius-lg);
|
border-radius: var(--radius-lg);
|
||||||
box-shadow: var(--shadow-card);
|
box-shadow: var(--shadow-card);
|
||||||
margin-bottom: 12px;
|
margin-bottom: 12px;
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-cover {
|
.store-card-cover {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
width: 96px;
|
width: 96px;
|
||||||
height: 96px;
|
height: 96px;
|
||||||
border-radius: var(--radius-md);
|
border-radius: 8px;
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
@@ -173,16 +174,25 @@
|
|||||||
.store-card-body {
|
.store-card-body {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
min-height: 96px;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 4px;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-head {
|
.store-card-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: flex-start;
|
align-items: center;
|
||||||
justify-content: space-between;
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 第1行:加粗标题(单行截断)+ 右对齐距离 */
|
||||||
|
.store-card-row--head {
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
margin-bottom: 6px;
|
height: 22px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-name {
|
.store-card-name {
|
||||||
@@ -191,78 +201,84 @@
|
|||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
line-height: 1.35;
|
line-height: 22px;
|
||||||
color: var(--color-on-surface);
|
color: #1a1a1a;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
display: -webkit-box;
|
white-space: nowrap;
|
||||||
-webkit-line-clamp: 2;
|
|
||||||
-webkit-box-orient: vertical;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-distance {
|
.store-card-distance {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
max-width: 40%;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
line-height: 1.35;
|
font-weight: 400;
|
||||||
color: var(--color-subtle-gray);
|
line-height: 22px;
|
||||||
}
|
color: #999;
|
||||||
|
text-align: right;
|
||||||
.store-card-status-row {
|
white-space: nowrap;
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 6px;
|
|
||||||
margin-bottom: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-card-status {
|
|
||||||
flex-shrink: 0;
|
|
||||||
padding: 2px 8px;
|
|
||||||
border-radius: var(--radius-sm);
|
|
||||||
background: rgba(45, 106, 79, 0.12);
|
|
||||||
color: var(--color-success-green);
|
|
||||||
font-size: 11px;
|
|
||||||
font-weight: 600;
|
|
||||||
line-height: 1.4;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 第2行:营业时间独自居左;多段各占一行 */
|
||||||
.store-card-hours {
|
.store-card-hours {
|
||||||
flex: 1;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 2px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-card-hours-line {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
line-height: 1.4;
|
font-weight: 400;
|
||||||
color: var(--color-subtle-gray);
|
line-height: 16px;
|
||||||
|
color: #999;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 第3行:地址最多两行截断 + 右对齐去核销;与按钮垂直居中 */
|
||||||
|
.store-card-row--foot {
|
||||||
|
gap: 8px;
|
||||||
|
min-height: 28px;
|
||||||
|
align-items: center;
|
||||||
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-address {
|
.store-card-address {
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.45;
|
|
||||||
color: var(--color-subtle-gray);
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
display: -webkit-box;
|
|
||||||
-webkit-line-clamp: 2;
|
|
||||||
-webkit-box-orient: vertical;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-card-footer {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
margin-top: auto;
|
|
||||||
padding-top: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.store-card-footer-spacer {
|
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 14px;
|
||||||
|
max-height: 28px;
|
||||||
|
color: #999;
|
||||||
|
text-align: left;
|
||||||
|
white-space: normal;
|
||||||
|
word-break: break-word;
|
||||||
|
overflow: hidden;
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
line-clamp: 2;
|
||||||
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-cta {
|
.store-card-cta {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
padding: 6px 16px;
|
display: flex;
|
||||||
border-radius: var(--radius-full);
|
align-items: center;
|
||||||
background: var(--color-heritage-red);
|
justify-content: center;
|
||||||
color: #fff;
|
padding: 0 14px;
|
||||||
|
height: 26px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--color-heritage-red, #a61d24);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-card-cta-text {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
line-height: 1.4;
|
line-height: 26px;
|
||||||
|
color: #fff;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,15 @@ describe('validateSupportTicketStatusTransition', () => {
|
|||||||
).toBe(false);
|
).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('allows PASSED -> PUBLISHED', () => {
|
||||||
|
expect(
|
||||||
|
validateSupportTicketStatusTransition('PASSED', 'PUBLISHED', {
|
||||||
|
linkedTaskCount: 1,
|
||||||
|
isSuperAdmin: true,
|
||||||
|
}).ok,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it('requires super admin and reason for REJECTED', () => {
|
it('requires super admin and reason for REJECTED', () => {
|
||||||
expect(
|
expect(
|
||||||
validateSupportTicketStatusTransition('DEVELOPING', 'REJECTED', {
|
validateSupportTicketStatusTransition('DEVELOPING', 'REJECTED', {
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ export type SupportTicketStatus =
|
|||||||
| 'REJECTED'
|
| 'REJECTED'
|
||||||
| 'DEVELOPING'
|
| 'DEVELOPING'
|
||||||
| 'TESTING'
|
| 'TESTING'
|
||||||
| 'PASSED';
|
| 'PASSED'
|
||||||
|
| 'PUBLISHED';
|
||||||
|
|
||||||
export type SupportTicketStatusTransitionContext = {
|
export type SupportTicketStatusTransitionContext = {
|
||||||
linkedTaskCount: number;
|
linkedTaskCount: number;
|
||||||
@@ -16,7 +17,8 @@ const FORWARD_TRANSITIONS: Record<SupportTicketStatus, SupportTicketStatus[]> =
|
|||||||
DEVELOPING: ['TESTING', 'REJECTED'],
|
DEVELOPING: ['TESTING', 'REJECTED'],
|
||||||
TESTING: ['PASSED', 'REJECTED'],
|
TESTING: ['PASSED', 'REJECTED'],
|
||||||
REJECTED: [],
|
REJECTED: [],
|
||||||
PASSED: [],
|
PASSED: ['PUBLISHED'],
|
||||||
|
PUBLISHED: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 技术支持工单批量/人工改状态校验(禁止回退) */
|
/** 技术支持工单批量/人工改状态校验(禁止回退) */
|
||||||
|
|||||||
@@ -32,29 +32,29 @@ export interface AppConfig {
|
|||||||
userH5Url: string;
|
userH5Url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 推广码 / C 端 H5 默认落地页(未配置 USER_H5_URL 时使用) */
|
/** 推广码 / C 端 H5 默认落地页(系统设置 USER_H5_URL 未配时回退;HQ 可改) */
|
||||||
export const DEFAULT_USER_H5_URL = 'https://user.runxian.top/user';
|
export const DEFAULT_USER_H5_URL = 'https://user.runxian.top/user';
|
||||||
|
|
||||||
/** 品牌 Logo OSS 根路径(改环境时只改此处) */
|
/** 品牌 Logo OSS 根路径(默认;系统设置 BRAND_LOGO_OSS_BASE 可覆盖) */
|
||||||
export const BRAND_LOGO_OSS_BASE = 'https://dukang-dev.oss-cn-beijing.aliyuncs.com/logo/';
|
export const BRAND_LOGO_OSS_BASE = 'https://dukang-dev.oss-cn-beijing.aliyuncs.com/logo/';
|
||||||
|
|
||||||
/** 方形 Logo(首页等品牌展示;商品列表顶栏仍用文字标题) */
|
/** 方形 Logo(默认;系统设置 BRAND_LOGO_URL 可覆盖) */
|
||||||
export const BRAND_LOGO_URL = `${BRAND_LOGO_OSS_BASE}logo.png`;
|
export const BRAND_LOGO_URL = `${BRAND_LOGO_OSS_BASE}logo.png`;
|
||||||
|
|
||||||
/** 长方形 Logo(含文字,登录等场景) */
|
/** 长方形 Logo(默认;系统设置 BRAND_LOGO_WIDE_URL 可覆盖) */
|
||||||
export const BRAND_LOGO_WIDE_URL = `${BRAND_LOGO_OSS_BASE}logo1.png`;
|
export const BRAND_LOGO_WIDE_URL = `${BRAND_LOGO_OSS_BASE}logo1.png`;
|
||||||
|
|
||||||
/** 仅图标 Logo(默认头像:未微信授权时) */
|
/** 仅图标 Logo(默认;系统设置 BRAND_LOGO_MARK_URL 可覆盖) */
|
||||||
export const BRAND_LOGO_MARK_URL = `${BRAND_LOGO_OSS_BASE}logo2.png`;
|
export const BRAND_LOGO_MARK_URL = `${BRAND_LOGO_OSS_BASE}logo2.png`;
|
||||||
|
|
||||||
/** 小程序静态资源(资质公示等) */
|
/** 小程序静态资源根路径(默认;系统设置 MINI_USER_STATIC_OSS_BASE 可覆盖) */
|
||||||
export const MINI_USER_STATIC_OSS_BASE =
|
export const MINI_USER_STATIC_OSS_BASE =
|
||||||
'https://dukang-dev.oss-cn-beijing.aliyuncs.com/static/mini-user/';
|
'https://dukang-dev.oss-cn-beijing.aliyuncs.com/static/mini-user/';
|
||||||
|
|
||||||
/** 「我的」页资质公示长图 */
|
/** 「我的」页资质公示长图(默认;系统设置 QUALIFICATION_DISCLOSURE_URL 可覆盖) */
|
||||||
export const QUALIFICATION_DISCLOSURE_URL = `${MINI_USER_STATIC_OSS_BASE}qualification-disclosure.png`;
|
export const QUALIFICATION_DISCLOSURE_URL = `${MINI_USER_STATIC_OSS_BASE}qualification-disclosure.png`;
|
||||||
|
|
||||||
/** 总部客服电话(C 端联系客服) */
|
/** 总部客服电话(默认;系统设置 CUSTOMER_SERVICE_PHONE 可覆盖) */
|
||||||
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -64,6 +64,137 @@ export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
|||||||
export const CUSTOMER_SERVICE_WECOM_URL =
|
export const CUSTOMER_SERVICE_WECOM_URL =
|
||||||
'https://work.weixin.qq.com/kfid/kfc8b88659a1dffa8cd';
|
'https://work.weixin.qq.com/kfid/kfc8b88659a1dffa8cd';
|
||||||
|
|
||||||
|
/** 从 env / 系统设置解析的 C 端品牌与客服展示配置(缺省回退常量) */
|
||||||
|
export type ClientBrandRuntime = {
|
||||||
|
userH5Url: string;
|
||||||
|
brandLogoOssBase: string;
|
||||||
|
brandLogoUrl: string;
|
||||||
|
brandLogoWideUrl: string;
|
||||||
|
brandLogoMarkUrl: string;
|
||||||
|
miniUserStaticOssBase: string;
|
||||||
|
qualificationDisclosureUrl: string;
|
||||||
|
customerServicePhone: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resolveClientBrandRuntime(
|
||||||
|
env?: Record<string, string | undefined>,
|
||||||
|
): ClientBrandRuntime {
|
||||||
|
const e = readEnv(env);
|
||||||
|
const brandBase = (e.BRAND_LOGO_OSS_BASE || BRAND_LOGO_OSS_BASE).trim().replace(/\/*$/, '/');
|
||||||
|
const staticBase = (e.MINI_USER_STATIC_OSS_BASE || MINI_USER_STATIC_OSS_BASE)
|
||||||
|
.trim()
|
||||||
|
.replace(/\/*$/, '/');
|
||||||
|
return {
|
||||||
|
userH5Url: (e.USER_H5_URL || DEFAULT_USER_H5_URL).replace(/\/$/, ''),
|
||||||
|
brandLogoOssBase: brandBase,
|
||||||
|
brandLogoUrl: (e.BRAND_LOGO_URL || '').trim() || `${brandBase}logo.png`,
|
||||||
|
brandLogoWideUrl: (e.BRAND_LOGO_WIDE_URL || '').trim() || `${brandBase}logo1.png`,
|
||||||
|
brandLogoMarkUrl: (e.BRAND_LOGO_MARK_URL || '').trim() || `${brandBase}logo2.png`,
|
||||||
|
miniUserStaticOssBase: staticBase,
|
||||||
|
qualificationDisclosureUrl:
|
||||||
|
(e.QUALIFICATION_DISCLOSURE_URL || '').trim() ||
|
||||||
|
`${staticBase}qualification-disclosure.png`,
|
||||||
|
customerServicePhone: (e.CUSTOMER_SERVICE_PHONE || CUSTOMER_SERVICE_PHONE).trim(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mock 短信固定验证码(系统设置 MOCK_SMS_FIXED_CODE 可覆盖) */
|
||||||
|
export function resolveMockSmsFixedCode(env?: Record<string, string | undefined>): string {
|
||||||
|
const code = (readEnv(env).MOCK_SMS_FIXED_CODE || '').trim();
|
||||||
|
return code || MOCK_SMS_FIXED_CODE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 小程序 / H5 默认分享文案与引导(系统设置「小程序分享配置」可覆盖) */
|
||||||
|
export const DEFAULT_SHARE_TITLE = '你吃饭,我买单';
|
||||||
|
export const DEFAULT_SHARE_DESC = '杜康好客 · 买美酒,享好礼,全城门店可用';
|
||||||
|
export const DEFAULT_SHARE_HINT = '请点击右上角 ··· 分享给好友';
|
||||||
|
export const DEFAULT_SHARE_STORES_TITLE = '杜康好客门店';
|
||||||
|
export const DEFAULT_SHARE_BENEFIT_TITLE = '好客权益 · 杜康好客';
|
||||||
|
export const DEFAULT_SHARE_MINE_TITLE = '杜康好客 · 我的';
|
||||||
|
/** 订单详情分享标题模板,可用 {productName} */
|
||||||
|
export const DEFAULT_SHARE_ORDER_TITLE = '我买了{productName} · 杜康好客';
|
||||||
|
|
||||||
|
export type MiniShareSceneConfig = {
|
||||||
|
title: string;
|
||||||
|
desc: string;
|
||||||
|
imageUrl: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 各场景分享文案/图(空字符串表示该字段走动态内容或默认分享) */
|
||||||
|
export type MiniShareRuntime = {
|
||||||
|
hint: string;
|
||||||
|
default: MiniShareSceneConfig;
|
||||||
|
home: MiniShareSceneConfig;
|
||||||
|
stores: MiniShareSceneConfig;
|
||||||
|
storeDetail: MiniShareSceneConfig;
|
||||||
|
benefit: MiniShareSceneConfig;
|
||||||
|
mine: MiniShareSceneConfig;
|
||||||
|
productDetail: MiniShareSceneConfig;
|
||||||
|
orderDetail: MiniShareSceneConfig;
|
||||||
|
};
|
||||||
|
|
||||||
|
function pickShareScene(
|
||||||
|
e: Record<string, string | undefined>,
|
||||||
|
prefix: string,
|
||||||
|
fallback: Partial<MiniShareSceneConfig> = {},
|
||||||
|
): MiniShareSceneConfig {
|
||||||
|
return {
|
||||||
|
title: (e[`${prefix}_TITLE`] || '').trim() || fallback.title || '',
|
||||||
|
desc: (e[`${prefix}_DESC`] || '').trim() || fallback.desc || '',
|
||||||
|
imageUrl: (e[`${prefix}_IMAGE_URL`] || '').trim() || fallback.imageUrl || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从 env / 系统设置解析小程序分享配置 */
|
||||||
|
export function resolveMiniShareRuntime(
|
||||||
|
env?: Record<string, string | undefined>,
|
||||||
|
): MiniShareRuntime {
|
||||||
|
const e = readEnv(env);
|
||||||
|
const brand = resolveClientBrandRuntime(e);
|
||||||
|
const defaults: MiniShareSceneConfig = {
|
||||||
|
title: (e.SHARE_DEFAULT_TITLE || '').trim() || DEFAULT_SHARE_TITLE,
|
||||||
|
desc: (e.SHARE_DEFAULT_DESC || '').trim() || DEFAULT_SHARE_DESC,
|
||||||
|
imageUrl: (e.SHARE_DEFAULT_IMAGE_URL || '').trim() || brand.brandLogoUrl,
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
hint: (e.SHARE_HINT || '').trim() || DEFAULT_SHARE_HINT,
|
||||||
|
default: defaults,
|
||||||
|
home: pickShareScene(e, 'SHARE_HOME', {
|
||||||
|
title: defaults.title,
|
||||||
|
desc: defaults.desc,
|
||||||
|
}),
|
||||||
|
stores: pickShareScene(e, 'SHARE_STORES', {
|
||||||
|
title: DEFAULT_SHARE_STORES_TITLE,
|
||||||
|
desc: defaults.desc,
|
||||||
|
}),
|
||||||
|
storeDetail: pickShareScene(e, 'SHARE_STORE_DETAIL'),
|
||||||
|
benefit: pickShareScene(e, 'SHARE_BENEFIT', {
|
||||||
|
title: DEFAULT_SHARE_BENEFIT_TITLE,
|
||||||
|
desc: defaults.desc,
|
||||||
|
}),
|
||||||
|
mine: pickShareScene(e, 'SHARE_MINE', {
|
||||||
|
title: DEFAULT_SHARE_MINE_TITLE,
|
||||||
|
desc: defaults.desc,
|
||||||
|
}),
|
||||||
|
productDetail: pickShareScene(e, 'SHARE_PRODUCT_DETAIL'),
|
||||||
|
orderDetail: pickShareScene(e, 'SHARE_ORDER_DETAIL', {
|
||||||
|
title: DEFAULT_SHARE_ORDER_TITLE,
|
||||||
|
desc: defaults.desc,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 订单等标题模板:替换 {productName} 等占位符 */
|
||||||
|
export function applyShareTitleTemplate(
|
||||||
|
template: string,
|
||||||
|
vars: Record<string, string | undefined | null>,
|
||||||
|
): string {
|
||||||
|
return template.replace(/\{(\w+)\}/g, (_, key: string) => {
|
||||||
|
const v = vars[key];
|
||||||
|
return v != null && String(v).trim() ? String(v).trim() : '';
|
||||||
|
}).replace(/\s{2,}/g, ' ').trim();
|
||||||
|
}
|
||||||
|
|
||||||
function readEnv(env?: Record<string, string | undefined>) {
|
function readEnv(env?: Record<string, string | undefined>) {
|
||||||
return (
|
return (
|
||||||
env ??
|
env ??
|
||||||
@@ -142,5 +273,5 @@ export function loadAppConfig(env?: Record<string, string | undefined>): AppConf
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mock 短信环境固定验证码 */
|
/** Mock 短信环境固定验证码(默认;系统设置 MOCK_SMS_FIXED_CODE 可覆盖) */
|
||||||
export const MOCK_SMS_FIXED_CODE = '999888';
|
export const MOCK_SMS_FIXED_CODE = '999888';
|
||||||
|
|||||||
@@ -85,6 +85,50 @@ export function promoConversion(scan: number, orders: number): string {
|
|||||||
return `${Math.round((orders / scan) * 1000) / 10}%`;
|
return `${Math.round((orders / scan) * 1000) / 10}%`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type PromoMetricEventType = 'SCAN' | 'ATTRIBUTION' | 'REGISTER' | 'ORDER';
|
||||||
|
|
||||||
|
export const PROMO_METRIC_EVENT_LABELS: Record<PromoMetricEventType, string> = {
|
||||||
|
SCAN: '扫码进入',
|
||||||
|
ATTRIBUTION: '归因用户',
|
||||||
|
REGISTER: '扫码注册',
|
||||||
|
ORDER: '订单',
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricEventItem = {
|
||||||
|
id: string;
|
||||||
|
eventType: PromoMetricEventType;
|
||||||
|
userId: string | null;
|
||||||
|
orderId: string | null;
|
||||||
|
sessionId: string | null;
|
||||||
|
clientIp: string | null;
|
||||||
|
ipProvince: string | null;
|
||||||
|
ipCity: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelineBucket = {
|
||||||
|
key: string;
|
||||||
|
scan: number;
|
||||||
|
attribution: number;
|
||||||
|
register: number;
|
||||||
|
order: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelinePeak = {
|
||||||
|
scan: { key: string; count: number } | null;
|
||||||
|
attribution: { key: string; count: number } | null;
|
||||||
|
register: { key: string; count: number } | null;
|
||||||
|
order: { key: string; count: number } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelineDto = {
|
||||||
|
granularity: 'day' | 'hour';
|
||||||
|
dateFrom: string;
|
||||||
|
dateTo: string;
|
||||||
|
buckets: PromoMetricTimelineBucket[];
|
||||||
|
peak: PromoMetricTimelinePeak;
|
||||||
|
};
|
||||||
|
|
||||||
export function buildPromoLandingUrl(baseUrl: string, code: string, qrcodeId: string): string {
|
export function buildPromoLandingUrl(baseUrl: string, code: string, qrcodeId: string): string {
|
||||||
const base = baseUrl.replace(/\/$/, '');
|
const base = baseUrl.replace(/\/$/, '');
|
||||||
return `${base}/?promo=${encodeURIComponent(code)}&pid=${encodeURIComponent(qrcodeId)}`;
|
return `${base}/?promo=${encodeURIComponent(code)}&pid=${encodeURIComponent(qrcodeId)}`;
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ export const STORE_SETTLEMENT_DEFAULT_RATE = 0.6;
|
|||||||
/** 酒厂账单结算比例(酒单实付 × 比例),暂定 30% */
|
/** 酒厂账单结算比例(酒单实付 × 比例),暂定 30% */
|
||||||
export const WINERY_SETTLEMENT_RATE = 0.3;
|
export const WINERY_SETTLEMENT_RATE = 0.3;
|
||||||
|
|
||||||
/** 酒厂账单出账滞后自然日(T+3:支付日 + 3 天后纳入账单) */
|
/** 酒厂账单出账滞后自然日(T+3:订单完成日 + 3 天后纳入账单) */
|
||||||
export const WINERY_SETTLEMENT_LAG_DAYS = 3;
|
export const WINERY_SETTLEMENT_LAG_DAYS = 3;
|
||||||
|
|
||||||
export type { LogisticsSettlementMethod } from './enums';
|
export type { LogisticsSettlementMethod } from './enums';
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ export type SupportTicketStatusDto =
|
|||||||
| 'REJECTED'
|
| 'REJECTED'
|
||||||
| 'DEVELOPING'
|
| 'DEVELOPING'
|
||||||
| 'TESTING'
|
| 'TESTING'
|
||||||
| 'PASSED';
|
| 'PASSED'
|
||||||
|
| 'PUBLISHED';
|
||||||
|
|
||||||
export const SUPPORT_TICKET_STATUSES = [
|
export const SUPPORT_TICKET_STATUSES = [
|
||||||
'PENDING_REVIEW',
|
'PENDING_REVIEW',
|
||||||
@@ -23,6 +24,7 @@ export const SUPPORT_TICKET_STATUSES = [
|
|||||||
'DEVELOPING',
|
'DEVELOPING',
|
||||||
'TESTING',
|
'TESTING',
|
||||||
'PASSED',
|
'PASSED',
|
||||||
|
'PUBLISHED',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string> = {
|
export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string> = {
|
||||||
@@ -31,6 +33,19 @@ export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string
|
|||||||
DEVELOPING: '开发',
|
DEVELOPING: '开发',
|
||||||
TESTING: '测试',
|
TESTING: '测试',
|
||||||
PASSED: '通过',
|
PASSED: '通过',
|
||||||
|
PUBLISHED: '已发布',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 技术支持工单优先级 */
|
||||||
|
export type SupportTicketPriorityDto = 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';
|
||||||
|
|
||||||
|
export const SUPPORT_TICKET_PRIORITIES = ['LOW', 'NORMAL', 'HIGH', 'URGENT'] as const;
|
||||||
|
|
||||||
|
export const SUPPORT_TICKET_PRIORITY_LABELS: Record<SupportTicketPriorityDto, string> = {
|
||||||
|
LOW: '低',
|
||||||
|
NORMAL: '普通',
|
||||||
|
HIGH: '高',
|
||||||
|
URGENT: '紧急',
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface SupportTicketDto {
|
export interface SupportTicketDto {
|
||||||
@@ -38,6 +53,7 @@ export interface SupportTicketDto {
|
|||||||
ticketNo: string;
|
ticketNo: string;
|
||||||
ticketType: SupportTicketTypeDto;
|
ticketType: SupportTicketTypeDto;
|
||||||
status: SupportTicketStatusDto;
|
status: SupportTicketStatusDto;
|
||||||
|
priority: SupportTicketPriorityDto;
|
||||||
title: string;
|
title: string;
|
||||||
content?: string | null;
|
content?: string | null;
|
||||||
rejectReason?: string | null;
|
rejectReason?: string | null;
|
||||||
@@ -51,6 +67,8 @@ export interface SupportTicketDto {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
completedAt?: string | null;
|
completedAt?: string | null;
|
||||||
|
releasedVersionNo?: string | null;
|
||||||
|
publishedAt?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateSupportTicketRequest {
|
export interface CreateSupportTicketRequest {
|
||||||
@@ -59,6 +77,7 @@ export interface CreateSupportTicketRequest {
|
|||||||
content?: string;
|
content?: string;
|
||||||
remark?: string;
|
remark?: string;
|
||||||
attachmentUrls?: string[];
|
attachmentUrls?: string[];
|
||||||
|
priority?: SupportTicketPriorityDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateSupportTicketRequest {
|
export interface UpdateSupportTicketRequest {
|
||||||
@@ -67,6 +86,7 @@ export interface UpdateSupportTicketRequest {
|
|||||||
content?: string;
|
content?: string;
|
||||||
remark?: string;
|
remark?: string;
|
||||||
attachmentUrls?: string[];
|
attachmentUrls?: string[];
|
||||||
|
priority?: SupportTicketPriorityDto;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RejectSupportTicketRequest {
|
export interface RejectSupportTicketRequest {
|
||||||
|
|||||||
@@ -27,6 +27,30 @@ export const TICKET_TYPE_LABELS: Record<TicketTypeDto, string> = {
|
|||||||
PACKAGE_DISPUTE: '套餐异议',
|
PACKAGE_DISPUTE: '套餐异议',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 售后工单状态(common_ticket.status) */
|
||||||
|
export type TicketStatusDto =
|
||||||
|
| 'PENDING'
|
||||||
|
| 'OPEN'
|
||||||
|
| 'COLLABORATING'
|
||||||
|
| 'RESOLVED'
|
||||||
|
| 'REJECTED'
|
||||||
|
| 'COMPLETED'
|
||||||
|
| 'CLOSED';
|
||||||
|
|
||||||
|
export const TICKET_STATUS_LABELS: Record<TicketStatusDto, string> = {
|
||||||
|
PENDING: '待处理',
|
||||||
|
OPEN: '处理中',
|
||||||
|
COLLABORATING: '协同中',
|
||||||
|
RESOLVED: '已解决',
|
||||||
|
REJECTED: '已驳回',
|
||||||
|
COMPLETED: '已完成',
|
||||||
|
CLOSED: '已关闭',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ticketStatusLabel(status: string): string {
|
||||||
|
return TICKET_STATUS_LABELS[status as TicketStatusDto] ?? status;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TicketDto {
|
export interface TicketDto {
|
||||||
id: string;
|
id: string;
|
||||||
ticketNo: string;
|
ticketNo: string;
|
||||||
|
|||||||
@@ -70,6 +70,30 @@ export interface DeliveryDto {
|
|||||||
deliveredAt?: string;
|
deliveredAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 物流路由节点(C 端 track API) */
|
||||||
|
export interface OrderTrackNodeDto {
|
||||||
|
trackInfo: string;
|
||||||
|
createTime: string;
|
||||||
|
statusName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 小飞侠 cmd=100301 预估送达 */
|
||||||
|
export interface OrderTrackEstimatedArrivalDto {
|
||||||
|
arriveTime: string;
|
||||||
|
siteName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /trade/orders/:id/track 响应 */
|
||||||
|
export interface OrderTrackDto {
|
||||||
|
nodes: OrderTrackNodeDto[];
|
||||||
|
signPhotoUrls: string[];
|
||||||
|
estimatedArrival?: OrderTrackEstimatedArrivalDto | null;
|
||||||
|
manualQueryUrl?: string | null;
|
||||||
|
provider?: string;
|
||||||
|
trackingNo?: string | null;
|
||||||
|
logisticsCompany?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
||||||
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
||||||
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { MiniShareRuntime } from './config';
|
||||||
|
|
||||||
/** 微信 JSSDK 初始化参数(后端签名下发) */
|
/** 微信 JSSDK 初始化参数(后端签名下发) */
|
||||||
export interface WechatJssdkConfig {
|
export interface WechatJssdkConfig {
|
||||||
appId: string;
|
appId: string;
|
||||||
@@ -48,6 +50,22 @@ export type ClientRuntimeConfig = {
|
|||||||
banners: string[];
|
banners: string[];
|
||||||
footerUrl: string | null;
|
footerUrl: string | null;
|
||||||
};
|
};
|
||||||
|
/** 小程序最低兼容版本(semver,如 3.4.13);客户端低于此值时提示更新 */
|
||||||
|
minClientVersion?: string | null;
|
||||||
|
/** C 端 H5 落地页(推广码等) */
|
||||||
|
userH5Url?: string;
|
||||||
|
/** 方形品牌 Logo */
|
||||||
|
brandLogoUrl?: string;
|
||||||
|
/** 长方形品牌 Logo(登录) */
|
||||||
|
brandLogoWideUrl?: string;
|
||||||
|
/** 图标 Logo(默认头像) */
|
||||||
|
brandLogoMarkUrl?: string;
|
||||||
|
/** 「我的」资质公示长图 */
|
||||||
|
qualificationDisclosureUrl?: string;
|
||||||
|
/** 总部客服电话 */
|
||||||
|
customerServicePhone?: string;
|
||||||
|
/** 小程序各场景分享文案/图 */
|
||||||
|
share?: MiniShareRuntime;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 是否展示微信授权入口 */
|
/** 是否展示微信授权入口 */
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
"./CouponBadge": "./src/CouponBadge.tsx",
|
"./CouponBadge": "./src/CouponBadge.tsx",
|
||||||
"./OrderStatusTabs": "./src/OrderStatusTabs.tsx",
|
"./OrderStatusTabs": "./src/OrderStatusTabs.tsx",
|
||||||
"./AppImage": "./src/AppImage.tsx",
|
"./AppImage": "./src/AppImage.tsx",
|
||||||
"./PullToRefresh": "./src/PullToRefresh.tsx"
|
"./PullToRefresh": "./src/PullToRefresh.tsx",
|
||||||
|
"./compressImage": "./src/compressImage.ts"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^18.3.1"
|
"react": "^18.3.1"
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
/** OSS 单文件上限(与后端 OSS_MAX_UPLOAD_BYTES 默认一致) */
|
||||||
|
export const DEFAULT_OSS_MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
function isCompressibleImage(file: File): boolean {
|
||||||
|
if (!file.type.startsWith('image/')) return false;
|
||||||
|
if (file.type === 'image/svg+xml' || file.type === 'image/gif') return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadImage(file: File): Promise<HTMLImageElement> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const url = URL.createObjectURL(file);
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
resolve(img);
|
||||||
|
};
|
||||||
|
img.onerror = () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
reject(new Error('图片读取失败'));
|
||||||
|
};
|
||||||
|
img.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function canvasToBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise<Blob> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
canvas.toBlob(
|
||||||
|
(blob) => (blob ? resolve(blob) : reject(new Error('图片压缩失败'))),
|
||||||
|
type,
|
||||||
|
quality,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderScaled(
|
||||||
|
img: HTMLImageElement,
|
||||||
|
maxEdge: number,
|
||||||
|
quality: number,
|
||||||
|
mime: string,
|
||||||
|
): Promise<Blob> {
|
||||||
|
const w = img.naturalWidth;
|
||||||
|
const h = img.naturalHeight;
|
||||||
|
const scale = Math.min(1, maxEdge / Math.max(w, h));
|
||||||
|
const cw = Math.max(1, Math.round(w * scale));
|
||||||
|
const ch = Math.max(1, Math.round(h * scale));
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = cw;
|
||||||
|
canvas.height = ch;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) throw new Error('图片压缩失败');
|
||||||
|
ctx.drawImage(img, 0, 0, cw, ch);
|
||||||
|
return canvasToBlob(canvas, mime, quality);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 超过 maxBytes 的图片用 canvas 压缩后再上传;不可压缩或非图片原样返回。
|
||||||
|
*/
|
||||||
|
export async function compressImageFileIfNeeded(
|
||||||
|
file: File,
|
||||||
|
maxBytes = DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
): Promise<File> {
|
||||||
|
if (!isCompressibleImage(file) || file.size <= maxBytes) return file;
|
||||||
|
|
||||||
|
const img = await loadImage(file);
|
||||||
|
const mime = file.type === 'image/png' || file.type === 'image/webp' ? 'image/jpeg' : file.type || 'image/jpeg';
|
||||||
|
const edges = [4096, 3072, 2048, 1536, 1280, 1024, 800];
|
||||||
|
let best: Blob | null = null;
|
||||||
|
|
||||||
|
outer: for (const edge of edges) {
|
||||||
|
for (let quality = 0.92; quality >= 0.5; quality -= 0.08) {
|
||||||
|
const blob = await renderScaled(img, edge, quality, mime);
|
||||||
|
if (!best || blob.size < best.size) best = blob;
|
||||||
|
if (blob.size <= maxBytes) {
|
||||||
|
best = blob;
|
||||||
|
break outer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!best || best.size >= file.size) return file;
|
||||||
|
|
||||||
|
const ext = mime === 'image/png' ? '.png' : '.jpg';
|
||||||
|
const baseName = file.name.replace(/\.[^.]+$/, '') || 'image';
|
||||||
|
return new File([best], `${baseName}${ext}`, { type: mime, lastModified: Date.now() });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatOssMaxSizeMb(maxBytes = DEFAULT_OSS_MAX_UPLOAD_BYTES): number {
|
||||||
|
return Math.floor(maxBytes / 1024 / 1024);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export { isWechatBrowser, isMiniProgram, getRuntimePlatform } from './env';
|
export { isWechatBrowser, isMiniProgram, getRuntimePlatform, isIosDevice, isWechatDevTools } from './env';
|
||||||
export { getRouterBasename, toAppPath, isOnAppPath } from './app-path';
|
export { getRouterBasename, toAppPath, isOnAppPath } from './app-path';
|
||||||
export {
|
export {
|
||||||
initWechatJssdk,
|
initWechatJssdk,
|
||||||
@@ -10,7 +10,7 @@ export {
|
|||||||
resetJssdkConfig,
|
resetJssdkConfig,
|
||||||
stripOAuthParamsFromLocation,
|
stripOAuthParamsFromLocation,
|
||||||
} from './jssdk';
|
} from './jssdk';
|
||||||
export { formatScanFailMessage } from './scan';
|
export { formatScanFailMessage, isScanPermissionWarmupError } from './scan';
|
||||||
export {
|
export {
|
||||||
getWechatLocation,
|
getWechatLocation,
|
||||||
getWechatLocationDetailed,
|
getWechatLocationDetailed,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export function formatScanFailMessage(errMsg: string): string {
|
|||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isScanPermissionWarmupError(msg: string): boolean {
|
export function isScanPermissionWarmupError(msg: string): boolean {
|
||||||
return /offline verifying|permission value is offline|权限验证中|接口未就绪|invalid signature|config:fail|signature/i.test(
|
return /offline verifying|permission value is offline|权限验证中|接口未就绪|invalid signature|config:fail|signature/i.test(
|
||||||
msg,
|
msg,
|
||||||
);
|
);
|
||||||
@@ -134,15 +134,13 @@ export async function scanQrCode(
|
|||||||
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
||||||
}
|
}
|
||||||
|
|
||||||
// wx.ready ≠ 权限离线校验完成;授权回跳后更明显
|
const ios = isIosDevice() && !isWechatDevTools();
|
||||||
const warmupMs = options.postAuthWarmup
|
|
||||||
? 1200
|
// wx.ready ≠ 权限离线校验完成;OAuth 回跳后 iOS 更明显
|
||||||
: isIosDevice() && !isWechatDevTools()
|
const warmupMs = options.postAuthWarmup ? (ios ? 1600 : 1000) : ios ? 800 : 300;
|
||||||
? 800
|
|
||||||
: 300;
|
|
||||||
await delay(warmupMs);
|
await delay(warmupMs);
|
||||||
|
|
||||||
const maxAttempts = options.postAuthWarmup ? 3 : 2;
|
const maxAttempts = options.postAuthWarmup ? (ios ? 4 : 3) : 2;
|
||||||
let lastError: Error | null = null;
|
let lastError: Error | null = null;
|
||||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||||
if (attempt > 0) {
|
if (attempt > 0) {
|
||||||
@@ -151,7 +149,8 @@ export async function scanQrCode(
|
|||||||
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
||||||
await checkJsApi('scanQRCode');
|
await checkJsApi('scanQRCode');
|
||||||
}
|
}
|
||||||
await delay(700 + attempt * 500);
|
const retryDelay = options.postAuthWarmup && ios ? 900 + attempt * 700 : 700 + attempt * 500;
|
||||||
|
await delay(retryDelay);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await invokeScanQrCode();
|
return await invokeScanQrCode();
|
||||||
|
|||||||
Generated
+3
@@ -29,6 +29,9 @@ importers:
|
|||||||
'@dukang/shared-types':
|
'@dukang/shared-types':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/shared-types
|
version: link:../../packages/shared-types
|
||||||
|
'@dukang/shared-ui':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../../packages/shared-ui
|
||||||
antd:
|
antd:
|
||||||
specifier: ^5.22.0
|
specifier: ^5.22.0
|
||||||
version: 5.29.3(luxon@3.7.2)(moment@2.30.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
version: 5.29.3(luxon@3.7.2)(moment@2.30.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||||
|
|||||||
@@ -107,6 +107,14 @@ enum SupportTicketStatus {
|
|||||||
DEVELOPING
|
DEVELOPING
|
||||||
TESTING
|
TESTING
|
||||||
PASSED
|
PASSED
|
||||||
|
PUBLISHED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SupportTicketPriority {
|
||||||
|
LOW
|
||||||
|
NORMAL
|
||||||
|
HIGH
|
||||||
|
URGENT
|
||||||
}
|
}
|
||||||
|
|
||||||
enum DevPlanTaskType {
|
enum DevPlanTaskType {
|
||||||
@@ -174,6 +182,13 @@ enum PromoCodeScene {
|
|||||||
OTHER
|
OTHER
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PromoMetricEventType {
|
||||||
|
SCAN
|
||||||
|
ATTRIBUTION
|
||||||
|
REGISTER
|
||||||
|
ORDER
|
||||||
|
}
|
||||||
|
|
||||||
enum CityStatus {
|
enum CityStatus {
|
||||||
PENDING
|
PENDING
|
||||||
ACTIVE
|
ACTIVE
|
||||||
@@ -646,6 +661,7 @@ model CommonSupportTicket {
|
|||||||
ticketNo String @unique @map("ticket_no") @db.VarChar(32)
|
ticketNo String @unique @map("ticket_no") @db.VarChar(32)
|
||||||
ticketType SupportTicketType @map("ticket_type")
|
ticketType SupportTicketType @map("ticket_type")
|
||||||
status SupportTicketStatus @default(PENDING_REVIEW)
|
status SupportTicketStatus @default(PENDING_REVIEW)
|
||||||
|
priority SupportTicketPriority @default(NORMAL) @map("priority")
|
||||||
title String @db.VarChar(128)
|
title String @db.VarChar(128)
|
||||||
content String? @db.Text
|
content String? @db.Text
|
||||||
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
||||||
@@ -656,6 +672,8 @@ model CommonSupportTicket {
|
|||||||
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
||||||
remark String? @db.VarChar(512)
|
remark String? @db.VarChar(512)
|
||||||
attachmentUrls Json? @map("attachment_urls")
|
attachmentUrls Json? @map("attachment_urls")
|
||||||
|
releasedVersionNo String? @map("released_version_no") @db.VarChar(32)
|
||||||
|
publishedAt DateTime? @map("published_at") @db.DateTime(3)
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
||||||
@@ -663,6 +681,7 @@ model CommonSupportTicket {
|
|||||||
@@index([status, createdAt])
|
@@index([status, createdAt])
|
||||||
@@index([ticketType, status])
|
@@index([ticketType, status])
|
||||||
@@index([creatorId])
|
@@index([creatorId])
|
||||||
|
@@index([releasedVersionNo])
|
||||||
@@map("common_support_ticket")
|
@@map("common_support_ticket")
|
||||||
|
|
||||||
devPlanTasks DevPlanTask[]
|
devPlanTasks DevPlanTask[]
|
||||||
@@ -848,6 +867,7 @@ model CommonPromoCode {
|
|||||||
qrcodeResource CommonResource? @relation("PromoQrcode", fields: [qrcodeResourceId], references: [id], onDelete: SetNull)
|
qrcodeResource CommonResource? @relation("PromoQrcode", fields: [qrcodeResourceId], references: [id], onDelete: SetNull)
|
||||||
attributions UserPromoAttribution[]
|
attributions UserPromoAttribution[]
|
||||||
orders Order[]
|
orders Order[]
|
||||||
|
metricEvents LogPromoEvent[]
|
||||||
|
|
||||||
@@index([ownerUserId])
|
@@index([ownerUserId])
|
||||||
@@index([scene, status])
|
@@index([scene, status])
|
||||||
@@ -1751,6 +1771,25 @@ model LogThirdParty {
|
|||||||
@@map("log_third_party")
|
@@map("log_third_party")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model LogPromoEvent {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
promoCodeId BigInt @map("promo_code_id") @db.UnsignedBigInt
|
||||||
|
eventType PromoMetricEventType @map("event_type")
|
||||||
|
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
||||||
|
orderId BigInt? @map("order_id") @db.UnsignedBigInt
|
||||||
|
sessionId String? @map("session_id") @db.VarChar(64)
|
||||||
|
clientIp String? @map("client_ip") @db.VarChar(45)
|
||||||
|
ipProvince String? @map("ip_province") @db.VarChar(32)
|
||||||
|
ipCity String? @map("ip_city") @db.VarChar(32)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
promoCode CommonPromoCode @relation(fields: [promoCodeId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([promoCodeId, eventType, createdAt])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("log_promo_event")
|
||||||
|
}
|
||||||
|
|
||||||
model LogUserAnalytics {
|
model LogUserAnalytics {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import { WechatPayCallbackController } from './wechat-pay.controller';
|
|||||||
import { WechatRefundCallbackController } from './wechat-refund.controller';
|
import { WechatRefundCallbackController } from './wechat-refund.controller';
|
||||||
import { WechatMessageCallbackController } from './wechat-message.controller';
|
import { WechatMessageCallbackController } from './wechat-message.controller';
|
||||||
import { DeliveryCallbackController } from './delivery-track.controller';
|
import { DeliveryCallbackController } from './delivery-track.controller';
|
||||||
|
import { DeliveryCallbackService } from './delivery-callback.service';
|
||||||
|
import { CourierModule } from '../integrations/courier/courier.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [IntegrationsModule, TradeModule, PrismaModule],
|
imports: [IntegrationsModule, TradeModule, PrismaModule, CourierModule],
|
||||||
|
providers: [DeliveryCallbackService],
|
||||||
controllers: [
|
controllers: [
|
||||||
WechatPayCallbackController,
|
WechatPayCallbackController,
|
||||||
WechatRefundCallbackController,
|
WechatRefundCallbackController,
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../common/prisma/prisma.module';
|
||||||
|
import { CourierService } from '../integrations/courier/courier.service';
|
||||||
|
import { XiaofeixiaProvider } from '../integrations/courier/xiaofeixia/xiaofeixia.provider';
|
||||||
|
import { logCourierCall } from '../integrations/courier/courier-log.util';
|
||||||
|
import { TradeService } from '../modules/trade/trade.service';
|
||||||
|
|
||||||
|
const XFX_PROVIDER_ALIASES = new Set(['xfx', 'xiaofeixia']);
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DeliveryCallbackService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly courier: CourierService,
|
||||||
|
private readonly xiaofeixiaProvider: XiaofeixiaProvider,
|
||||||
|
private readonly tradeService: TradeService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async handleTrackCallback(providerKey: string, body: unknown, requestUrl: string) {
|
||||||
|
const normalized = providerKey.trim().toLowerCase();
|
||||||
|
const baseLog = {
|
||||||
|
scene: 'TRACK_CALLBACK',
|
||||||
|
requestUrl,
|
||||||
|
requestBody: (body && typeof body === 'object' ? body : { value: body }) as Record<
|
||||||
|
string,
|
||||||
|
unknown
|
||||||
|
>,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!XFX_PROVIDER_ALIASES.has(normalized) && normalized !== 'logistics') {
|
||||||
|
await logCourierCall(this.prisma, {
|
||||||
|
...baseLog,
|
||||||
|
status: 'FAILED',
|
||||||
|
errorMessage: `不支持的承运商: ${providerKey}`,
|
||||||
|
});
|
||||||
|
return this.courier.buildTrackCallbackResponse(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalized === 'logistics') {
|
||||||
|
await logCourierCall(this.prisma, {
|
||||||
|
...baseLog,
|
||||||
|
status: 'SUCCESS',
|
||||||
|
errorMessage: '跨城物流回调暂未接入,已记录',
|
||||||
|
});
|
||||||
|
return this.courier.buildTrackCallbackResponse(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = this.xiaofeixiaProvider.parseTrackCallback(body);
|
||||||
|
if (!payload) {
|
||||||
|
const response = this.courier.buildTrackCallbackResponse(false);
|
||||||
|
await logCourierCall(this.prisma, {
|
||||||
|
...baseLog,
|
||||||
|
responseBody: response,
|
||||||
|
status: 'FAILED',
|
||||||
|
errorMessage: '回调体解析失败',
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const order = payload.outNumber
|
||||||
|
? await this.prisma.order.findUnique({ where: { orderNo: payload.outNumber } })
|
||||||
|
: payload.trackingNumber
|
||||||
|
? await this.prisma.order.findFirst({
|
||||||
|
where: { delivery: { trackingNo: payload.trackingNumber } },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (!order) {
|
||||||
|
const response = this.courier.buildTrackCallbackResponse(false);
|
||||||
|
await logCourierCall(this.prisma, {
|
||||||
|
...baseLog,
|
||||||
|
responseBody: response,
|
||||||
|
status: 'FAILED',
|
||||||
|
errorMessage: '订单不存在',
|
||||||
|
externalNo: payload.outNumber || payload.trackingNumber,
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetStatus = this.xiaofeixiaProvider.mapTrackStatus(
|
||||||
|
payload.status,
|
||||||
|
payload.statusName,
|
||||||
|
);
|
||||||
|
let applied = false;
|
||||||
|
if (targetStatus && targetStatus !== order.status) {
|
||||||
|
await this.tradeService.applyStatusTransition(
|
||||||
|
order.id,
|
||||||
|
order.status,
|
||||||
|
targetStatus,
|
||||||
|
'COURIER_TRACK_CALLBACK',
|
||||||
|
payload.trackInfo || payload.statusName,
|
||||||
|
);
|
||||||
|
applied = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = this.courier.buildTrackCallbackResponse(true);
|
||||||
|
await logCourierCall(this.prisma, {
|
||||||
|
...baseLog,
|
||||||
|
responseBody: response,
|
||||||
|
status: 'SUCCESS',
|
||||||
|
externalNo: order.orderNo,
|
||||||
|
ref: { refType: 'ORDER', refId: order.id },
|
||||||
|
errorMessage: applied ? undefined : '状态未变更',
|
||||||
|
});
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,71 +1,35 @@
|
|||||||
import { Body, Controller, Post } from '@nestjs/common';
|
import { Body, Controller, Param, Post, Res } from '@nestjs/common';
|
||||||
import { TradeService } from '../modules/trade/trade.service';
|
import type { Response } from 'express';
|
||||||
import { CourierService } from '../integrations/courier/courier.service';
|
import { DeliveryCallbackService } from './delivery-callback.service';
|
||||||
import { PrismaService } from '../common/prisma/prisma.module';
|
|
||||||
import { logCourierCall } from '../integrations/courier/courier-log.util';
|
|
||||||
|
|
||||||
@Controller('callbacks/delivery')
|
@Controller('callbacks')
|
||||||
export class DeliveryCallbackController {
|
export class DeliveryCallbackController {
|
||||||
constructor(
|
constructor(private readonly deliveryCallbackService: DeliveryCallbackService) {}
|
||||||
private readonly tradeService: TradeService,
|
|
||||||
private readonly courier: CourierService,
|
|
||||||
private readonly prisma: PrismaService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Post('track')
|
/** 小飞侠/物流路由变化回调(适配器入口) */
|
||||||
async track(@Body() body: { orderNo?: string; orderId?: string; status?: string }) {
|
@Post('courier/:provider/track')
|
||||||
const baseLog = {
|
async trackByProvider(
|
||||||
scene: 'TRACK_CALLBACK',
|
@Param('provider') provider: string,
|
||||||
requestUrl: '/api/v1/callbacks/delivery/track',
|
@Body() body: unknown,
|
||||||
requestBody: body as Record<string, unknown>,
|
@Res() res: Response,
|
||||||
};
|
) {
|
||||||
|
const result = await this.deliveryCallbackService.handleTrackCallback(
|
||||||
|
provider,
|
||||||
|
body,
|
||||||
|
`/api/v1/callbacks/courier/${provider}/track`,
|
||||||
|
);
|
||||||
|
// 直出承运商约定结构,避免被全局 { code:0, data } 包装
|
||||||
|
return res.status(200).json(result);
|
||||||
|
}
|
||||||
|
|
||||||
if (!body.orderId && !body.orderNo) {
|
/** 兼容旧路径,默认按小飞侠解析 */
|
||||||
await logCourierCall(this.prisma, {
|
@Post('delivery/track')
|
||||||
...baseLog,
|
async trackLegacy(@Body() body: unknown, @Res() res: Response) {
|
||||||
status: 'FAILED',
|
const result = await this.deliveryCallbackService.handleTrackCallback(
|
||||||
errorMessage: '缺少 orderId / orderNo',
|
'xfx',
|
||||||
});
|
body,
|
||||||
return this.courier.buildTrackCallbackResponse(false);
|
'/api/v1/callbacks/delivery/track',
|
||||||
}
|
);
|
||||||
|
return res.status(200).json(result);
|
||||||
const order = body.orderId
|
|
||||||
? await this.prisma.order.findUnique({ where: { id: BigInt(body.orderId) } })
|
|
||||||
: await this.prisma.order.findUnique({ where: { orderNo: body.orderNo! } });
|
|
||||||
|
|
||||||
if (!order) {
|
|
||||||
await logCourierCall(this.prisma, {
|
|
||||||
...baseLog,
|
|
||||||
status: 'FAILED',
|
|
||||||
errorMessage: '订单不存在',
|
|
||||||
externalNo: body.orderNo,
|
|
||||||
});
|
|
||||||
return this.courier.buildTrackCallbackResponse(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
const statusMap: Record<string, string> = {
|
|
||||||
SHIPPED: 'SHIPPING',
|
|
||||||
OUT_WAREHOUSE: 'OUT_WAREHOUSE',
|
|
||||||
DELIVERED: 'COMPLETED',
|
|
||||||
COMPLETED: 'COMPLETED',
|
|
||||||
};
|
|
||||||
const target = statusMap[body.status ?? ''] ?? body.status;
|
|
||||||
let applied = false;
|
|
||||||
if (target && target !== order.status) {
|
|
||||||
await this.tradeService.applyStatusTransition(order.id, order.status, target, 'DELIVERY_CALLBACK');
|
|
||||||
applied = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = this.courier.buildTrackCallbackResponse(true);
|
|
||||||
await logCourierCall(this.prisma, {
|
|
||||||
...baseLog,
|
|
||||||
responseBody: response,
|
|
||||||
status: 'SUCCESS',
|
|
||||||
externalNo: order.orderNo,
|
|
||||||
ref: { refType: 'ORDER', refId: order.id },
|
|
||||||
errorMessage: applied ? undefined : '状态未变更',
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,22 @@
|
|||||||
import type { SystemConfigFieldMeta, SystemConfigGroupMeta } from '@dukang/shared-types';
|
import type { SystemConfigFieldMeta, SystemConfigGroupMeta } from '@dukang/shared-types';
|
||||||
|
import {
|
||||||
|
BRAND_LOGO_MARK_URL,
|
||||||
|
BRAND_LOGO_OSS_BASE,
|
||||||
|
BRAND_LOGO_URL,
|
||||||
|
BRAND_LOGO_WIDE_URL,
|
||||||
|
CUSTOMER_SERVICE_PHONE,
|
||||||
|
DEFAULT_SHARE_BENEFIT_TITLE,
|
||||||
|
DEFAULT_SHARE_DESC,
|
||||||
|
DEFAULT_SHARE_HINT,
|
||||||
|
DEFAULT_SHARE_MINE_TITLE,
|
||||||
|
DEFAULT_SHARE_ORDER_TITLE,
|
||||||
|
DEFAULT_SHARE_STORES_TITLE,
|
||||||
|
DEFAULT_SHARE_TITLE,
|
||||||
|
DEFAULT_USER_H5_URL,
|
||||||
|
MINI_USER_STATIC_OSS_BASE,
|
||||||
|
MOCK_SMS_FIXED_CODE,
|
||||||
|
QUALIFICATION_DISCLOSURE_URL,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
/** 运行环境、安全与鉴权仅保留在 .env,不在 HQ 系统设置中维护 */
|
/** 运行环境、安全与鉴权仅保留在 .env,不在 HQ 系统设置中维护 */
|
||||||
export const SYSTEM_CONFIG_GROUPS: SystemConfigGroupMeta[] = [
|
export const SYSTEM_CONFIG_GROUPS: SystemConfigGroupMeta[] = [
|
||||||
@@ -6,6 +24,7 @@ export const SYSTEM_CONFIG_GROUPS: SystemConfigGroupMeta[] = [
|
|||||||
{ key: 'sms', label: '短信' },
|
{ key: 'sms', label: '短信' },
|
||||||
{ key: 'wechat', label: '微信' },
|
{ key: 'wechat', label: '微信' },
|
||||||
{ key: 'wechat_mini', label: '微信小程序配置' },
|
{ key: 'wechat_mini', label: '微信小程序配置' },
|
||||||
|
{ key: 'wechat_mini_share', label: '小程序分享配置' },
|
||||||
{ key: 'oss', label: '对象存储 OSS' },
|
{ key: 'oss', label: '对象存储 OSS' },
|
||||||
{ key: 'app', label: '应用链接' },
|
{ key: 'app', label: '应用链接' },
|
||||||
{ key: 'deploy', label: '发布部署' },
|
{ key: 'deploy', label: '发布部署' },
|
||||||
@@ -18,6 +37,7 @@ const G = {
|
|||||||
sms: 'sms',
|
sms: 'sms',
|
||||||
wechat: 'wechat',
|
wechat: 'wechat',
|
||||||
wechat_mini: 'wechat_mini',
|
wechat_mini: 'wechat_mini',
|
||||||
|
wechat_mini_share: 'wechat_mini_share',
|
||||||
oss: 'oss',
|
oss: 'oss',
|
||||||
app: 'app',
|
app: 'app',
|
||||||
deploy: 'deploy',
|
deploy: 'deploy',
|
||||||
@@ -116,6 +136,288 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
requiresRestart: false,
|
requiresRestart: false,
|
||||||
description: '小程序商品首页底部 footer,建议比例 15:4;上传后需点击右上角「保存」',
|
description: '小程序商品首页底部 footer,建议比例 15:4;上传后需点击右上角「保存」',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'MINI_USER_MIN_VERSION',
|
||||||
|
label: '小程序最低版本',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: '3.4.14',
|
||||||
|
description: 'semver 格式;客户端低于此版本时提示更新',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'USER_H5_URL',
|
||||||
|
label: 'C 端 H5 落地页',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'https://user.example.com/user',
|
||||||
|
description: '推广码二维码 / 未配置时的默认落地页前缀(无末尾斜杠)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'BRAND_LOGO_OSS_BASE',
|
||||||
|
label: '品牌 Logo OSS 根路径',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'https://xxx.oss-cn-beijing.aliyuncs.com/logo/',
|
||||||
|
description: '仅作说明/备份;下方三张 Logo 请直接配置完整 URL',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'BRAND_LOGO_URL',
|
||||||
|
label: '方形 Logo',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '品牌方形 Logo;分享默认图未单独配置时回退此图',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'BRAND_LOGO_WIDE_URL',
|
||||||
|
label: '长方形 Logo',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '含文字,登录页等场景',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'BRAND_LOGO_MARK_URL',
|
||||||
|
label: '图标 Logo',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '默认头像(未微信授权时)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'MINI_USER_STATIC_OSS_BASE',
|
||||||
|
label: '小程序静态资源 OSS 根路径',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'https://xxx.oss-cn-beijing.aliyuncs.com/static/mini-user/',
|
||||||
|
description: '资质公示等静态资源根路径;完整 URL 优先用下方「资质公示图」',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'QUALIFICATION_DISCLOSURE_URL',
|
||||||
|
label: '资质公示长图',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '「我的」页资质公示大图',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'CUSTOMER_SERVICE_PHONE',
|
||||||
|
label: '总部客服电话',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: '13203801799',
|
||||||
|
description: 'C 端联系客服拨号号码',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'MOCK_SMS_FIXED_CODE',
|
||||||
|
label: 'Mock 短信固定验证码',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: '999888',
|
||||||
|
description: '仅 MOCK_SMS 开启时生效;留空则用默认 999888',
|
||||||
|
},
|
||||||
|
|
||||||
|
// —— 小程序分享配置 ——
|
||||||
|
{
|
||||||
|
key: 'SHARE_HINT',
|
||||||
|
label: '分享引导文案',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_HINT,
|
||||||
|
description: '点击分享按钮后的 Toast 提示(小程序内)',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_DEFAULT_TITLE',
|
||||||
|
label: '默认分享标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_TITLE,
|
||||||
|
description: '各场景未单独配置标题时使用',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_DEFAULT_DESC',
|
||||||
|
label: '默认分享描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_DESC,
|
||||||
|
description: 'H5 分享卡片描述;小程序朋友圈/好友卡片副文案回退',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_DEFAULT_IMAGE_URL',
|
||||||
|
label: '默认分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '各场景未配置图且无业务图时使用;建议接近 5:4',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_HOME_TITLE',
|
||||||
|
label: '首页 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_HOME_DESC',
|
||||||
|
label: '首页 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_HOME_IMAGE_URL',
|
||||||
|
label: '首页 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则优先用首页首张轮播图,再回退默认分享图',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORES_TITLE',
|
||||||
|
label: '门店列表 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_STORES_TITLE,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORES_DESC',
|
||||||
|
label: '门店列表 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORES_IMAGE_URL',
|
||||||
|
label: '门店列表 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORE_DETAIL_TITLE',
|
||||||
|
label: '门店详情 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用门店名称',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORE_DETAIL_DESC',
|
||||||
|
label: '门店详情 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用门店简介/地址',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_STORE_DETAIL_IMAGE_URL',
|
||||||
|
label: '门店详情 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用门头图/环境图',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_BENEFIT_TITLE',
|
||||||
|
label: '权益页 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_BENEFIT_TITLE,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_BENEFIT_DESC',
|
||||||
|
label: '权益页 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_BENEFIT_IMAGE_URL',
|
||||||
|
label: '权益页 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_MINE_TITLE',
|
||||||
|
label: '我的 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_MINE_TITLE,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_MINE_DESC',
|
||||||
|
label: '我的 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_MINE_IMAGE_URL',
|
||||||
|
label: '我的 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_PRODUCT_DETAIL_TITLE',
|
||||||
|
label: '商品详情 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用商品名称',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_PRODUCT_DETAIL_DESC',
|
||||||
|
label: '商品详情 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用商品副标题',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_PRODUCT_DETAIL_IMAGE_URL',
|
||||||
|
label: '商品详情 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: '留空则用商品主图',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_ORDER_DETAIL_TITLE',
|
||||||
|
label: '订单详情 · 标题',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: DEFAULT_SHARE_ORDER_TITLE,
|
||||||
|
description: '支持 {productName} 占位符',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_ORDER_DETAIL_DESC',
|
||||||
|
label: '订单详情 · 描述',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'SHARE_ORDER_DETAIL_IMAGE_URL',
|
||||||
|
label: '订单详情 · 分享图',
|
||||||
|
group: G.wechat_mini_share,
|
||||||
|
type: 'image',
|
||||||
|
requiresRestart: false,
|
||||||
|
},
|
||||||
|
|
||||||
{ key: 'OSS_ACCESS_KEY_ID', label: 'OSS AccessKey ID', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
{ key: 'OSS_ACCESS_KEY_ID', label: 'OSS AccessKey ID', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
||||||
{ key: 'OSS_ACCESS_KEY_SECRET', label: 'OSS AccessKey Secret', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
{ key: 'OSS_ACCESS_KEY_SECRET', label: 'OSS AccessKey Secret', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
||||||
@@ -128,7 +430,6 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
{ key: 'OSS_UPLOAD_EXPIRE_SECONDS', label: '直传凭证有效期(秒)', group: G.oss, type: 'number', requiresRestart: false },
|
{ key: 'OSS_UPLOAD_EXPIRE_SECONDS', label: '直传凭证有效期(秒)', group: G.oss, type: 'number', requiresRestart: false },
|
||||||
{ key: 'OSS_MAX_UPLOAD_BYTES', label: '单文件上限(字节)', group: G.oss, type: 'number', requiresRestart: false },
|
{ key: 'OSS_MAX_UPLOAD_BYTES', label: '单文件上限(字节)', group: G.oss, type: 'number', requiresRestart: false },
|
||||||
|
|
||||||
{ key: 'USER_H5_URL', label: 'C 端 H5 落地页', group: G.app, type: 'string', requiresRestart: false },
|
|
||||||
{
|
{
|
||||||
key: 'TENCENT_LBS_KEY',
|
key: 'TENCENT_LBS_KEY',
|
||||||
label: '腾讯位置服务 Key',
|
label: '腾讯位置服务 Key',
|
||||||
@@ -238,6 +539,37 @@ export const SYSTEM_CONFIG_RETIRED_KEYS = [
|
|||||||
|
|
||||||
export const SYSTEM_CONFIG_KEY_SET = new Set(SYSTEM_CONFIG_FIELDS.map((f) => f.key));
|
export const SYSTEM_CONFIG_KEY_SET = new Set(SYSTEM_CONFIG_FIELDS.map((f) => f.key));
|
||||||
|
|
||||||
|
/** 表单空值时展示 / 启动补种的默认值(与 shared-types 常量对齐) */
|
||||||
|
export const SYSTEM_CONFIG_DEFAULTS: Record<string, string> = {
|
||||||
|
USER_H5_URL: DEFAULT_USER_H5_URL.replace(/\/$/, ''),
|
||||||
|
BRAND_LOGO_OSS_BASE: BRAND_LOGO_OSS_BASE,
|
||||||
|
BRAND_LOGO_URL: BRAND_LOGO_URL,
|
||||||
|
BRAND_LOGO_WIDE_URL: BRAND_LOGO_WIDE_URL,
|
||||||
|
BRAND_LOGO_MARK_URL: BRAND_LOGO_MARK_URL,
|
||||||
|
MINI_USER_STATIC_OSS_BASE: MINI_USER_STATIC_OSS_BASE,
|
||||||
|
QUALIFICATION_DISCLOSURE_URL: QUALIFICATION_DISCLOSURE_URL,
|
||||||
|
CUSTOMER_SERVICE_PHONE: CUSTOMER_SERVICE_PHONE,
|
||||||
|
MOCK_SMS_FIXED_CODE: MOCK_SMS_FIXED_CODE,
|
||||||
|
SHARE_HINT: DEFAULT_SHARE_HINT,
|
||||||
|
SHARE_DEFAULT_TITLE: DEFAULT_SHARE_TITLE,
|
||||||
|
SHARE_DEFAULT_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
SHARE_DEFAULT_IMAGE_URL: BRAND_LOGO_URL,
|
||||||
|
SHARE_HOME_TITLE: DEFAULT_SHARE_TITLE,
|
||||||
|
SHARE_HOME_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
SHARE_STORES_TITLE: DEFAULT_SHARE_STORES_TITLE,
|
||||||
|
SHARE_STORES_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
SHARE_BENEFIT_TITLE: DEFAULT_SHARE_BENEFIT_TITLE,
|
||||||
|
SHARE_BENEFIT_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
SHARE_MINE_TITLE: DEFAULT_SHARE_MINE_TITLE,
|
||||||
|
SHARE_MINE_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
SHARE_ORDER_DETAIL_TITLE: DEFAULT_SHARE_ORDER_TITLE,
|
||||||
|
SHARE_ORDER_DETAIL_DESC: DEFAULT_SHARE_DESC,
|
||||||
|
};
|
||||||
|
|
||||||
export function getSystemConfigField(key: string): SystemConfigFieldMeta | undefined {
|
export function getSystemConfigField(key: string): SystemConfigFieldMeta | undefined {
|
||||||
return SYSTEM_CONFIG_FIELDS.find((f) => f.key === key);
|
return SYSTEM_CONFIG_FIELDS.find((f) => f.key === key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getSystemConfigDefault(key: string): string {
|
||||||
|
return SYSTEM_CONFIG_DEFAULTS[key] ?? '';
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type {
|
|||||||
import { loadAppConfig, parseMiniHomeBanners, serializeMiniHomeBanners } from '@dukang/shared-types';
|
import { loadAppConfig, parseMiniHomeBanners, serializeMiniHomeBanners } from '@dukang/shared-types';
|
||||||
import { PrismaService } from '../prisma/prisma.module';
|
import { PrismaService } from '../prisma/prisma.module';
|
||||||
import {
|
import {
|
||||||
|
SYSTEM_CONFIG_DEFAULTS,
|
||||||
SYSTEM_CONFIG_FIELDS,
|
SYSTEM_CONFIG_FIELDS,
|
||||||
SYSTEM_CONFIG_GROUPS,
|
SYSTEM_CONFIG_GROUPS,
|
||||||
SYSTEM_CONFIG_KEY_SET,
|
SYSTEM_CONFIG_KEY_SET,
|
||||||
@@ -42,6 +43,7 @@ export class SystemConfigService implements OnModuleInit {
|
|||||||
try {
|
try {
|
||||||
await this.purgeRetiredKeys();
|
await this.purgeRetiredKeys();
|
||||||
await this.seedMissingFromProcessEnv();
|
await this.seedMissingFromProcessEnv();
|
||||||
|
await this.seedMissingDefaults();
|
||||||
const rows = await this.prisma.systemConfig.findMany();
|
const rows = await this.prisma.systemConfig.findMany();
|
||||||
applyEnvOverlay(Object.fromEntries(rows.map((r) => [r.configKey, r.value])));
|
applyEnvOverlay(Object.fromEntries(rows.map((r) => [r.configKey, r.value])));
|
||||||
this.lastUpdatedAt = rows.reduce<Date | null>(
|
this.lastUpdatedAt = rows.reduce<Date | null>(
|
||||||
@@ -82,7 +84,7 @@ export class SystemConfigService implements OnModuleInit {
|
|||||||
for (const field of fields) {
|
for (const field of fields) {
|
||||||
const fromDb = dbMap.get(field.key);
|
const fromDb = dbMap.get(field.key);
|
||||||
const fromEnv = process.env[field.key];
|
const fromEnv = process.env[field.key];
|
||||||
const raw = fromDb ?? fromEnv ?? '';
|
const raw = (fromDb ?? fromEnv ?? SYSTEM_CONFIG_DEFAULTS[field.key] ?? '').trim();
|
||||||
if (field.secret) {
|
if (field.secret) {
|
||||||
if (raw) configuredSecrets.push(field.key);
|
if (raw) configuredSecrets.push(field.key);
|
||||||
values[field.key] = '';
|
values[field.key] = '';
|
||||||
@@ -227,6 +229,26 @@ export class SystemConfigService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 将代码默认值写入空缺配置,便于 HQ 表单可见、可改 */
|
||||||
|
private async seedMissingDefaults() {
|
||||||
|
const overlay: Record<string, string> = {};
|
||||||
|
for (const field of SYSTEM_CONFIG_FIELDS) {
|
||||||
|
const defaultVal = SYSTEM_CONFIG_DEFAULTS[field.key];
|
||||||
|
if (!defaultVal?.trim()) continue;
|
||||||
|
const existing = await this.prisma.systemConfig.findUnique({ where: { configKey: field.key } });
|
||||||
|
if (existing?.value?.trim()) continue;
|
||||||
|
if (process.env[field.key]?.trim()) continue;
|
||||||
|
const value = this.normalizeByMeta(field, defaultVal);
|
||||||
|
await this.prisma.systemConfig.upsert({
|
||||||
|
where: { configKey: field.key },
|
||||||
|
create: { configKey: field.key, value },
|
||||||
|
update: { value },
|
||||||
|
});
|
||||||
|
overlay[field.key] = value;
|
||||||
|
}
|
||||||
|
if (Object.keys(overlay).length) applyEnvOverlay(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
private normalizeByMeta(meta: { key?: string; type: string }, raw: string): string {
|
private normalizeByMeta(meta: { key?: string; type: string }, raw: string): string {
|
||||||
if (meta.type === 'boolean') {
|
if (meta.type === 'boolean') {
|
||||||
return raw === 'true' || raw === '1' ? 'true' : 'false';
|
return raw === 'true' || raw === '1' ? 'true' : 'false';
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ const CMD_SCENE: Record<string, string> = {
|
|||||||
[XIAOFEIXIA_CMD.ESTIMATE_FREIGHT]: 'ESTIMATE_FREIGHT',
|
[XIAOFEIXIA_CMD.ESTIMATE_FREIGHT]: 'ESTIMATE_FREIGHT',
|
||||||
[XIAOFEIXIA_CMD.BATCH_GET_ORDER]: 'BATCH_GET_SHIPMENT',
|
[XIAOFEIXIA_CMD.BATCH_GET_ORDER]: 'BATCH_GET_SHIPMENT',
|
||||||
[XIAOFEIXIA_CMD.DELIVERY_COVERAGE]: 'CHECK_COVERAGE',
|
[XIAOFEIXIA_CMD.DELIVERY_COVERAGE]: 'CHECK_COVERAGE',
|
||||||
|
[XIAOFEIXIA_CMD.SIGN_PHOTOS]: 'GET_SIGN_PHOTOS',
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CourierLogRef = {
|
export type CourierLogRef = {
|
||||||
|
|||||||
@@ -29,6 +29,6 @@ import type { ICourierProvider } from './courier.types';
|
|||||||
},
|
},
|
||||||
CourierService,
|
CourierService,
|
||||||
],
|
],
|
||||||
exports: [CourierService, CourierConfigService, COURIER_PROVIDER],
|
exports: [CourierService, CourierConfigService, COURIER_PROVIDER, XiaofeixiaProvider],
|
||||||
})
|
})
|
||||||
export class CourierModule {}
|
export class CourierModule {}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import type {
|
|||||||
ShipmentQuery,
|
ShipmentQuery,
|
||||||
TrackCallbackResponse,
|
TrackCallbackResponse,
|
||||||
TrackNode,
|
TrackNode,
|
||||||
|
TrackCallbackPayload,
|
||||||
|
CourierMappedOrderStatus,
|
||||||
} from './courier.types';
|
} from './courier.types';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,6 +47,10 @@ export class CourierService {
|
|||||||
return this.provider.getTrack(query, options);
|
return this.provider.getTrack(query, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]> {
|
||||||
|
return this.provider.getSignPhotos(query, options);
|
||||||
|
}
|
||||||
|
|
||||||
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
||||||
return this.provider.checkDeliveryCoverage(toAddress, options);
|
return this.provider.checkDeliveryCoverage(toAddress, options);
|
||||||
}
|
}
|
||||||
@@ -56,4 +62,12 @@ export class CourierService {
|
|||||||
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse {
|
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse {
|
||||||
return this.provider.buildTrackCallbackResponse(success);
|
return this.provider.buildTrackCallbackResponse(success);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
parseTrackCallback(body: unknown): TrackCallbackPayload | null {
|
||||||
|
return this.provider.parseTrackCallback(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null {
|
||||||
|
return this.provider.mapTrackStatus(status, statusName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -109,6 +109,13 @@ export interface TrackCallbackResponse {
|
|||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 承运商路由回调映射后的订单履约状态 */
|
||||||
|
export type CourierMappedOrderStatus =
|
||||||
|
| 'OUT_WAREHOUSE'
|
||||||
|
| 'SHIPPING'
|
||||||
|
| 'PENDING_RECEIVE'
|
||||||
|
| 'COMPLETED';
|
||||||
|
|
||||||
export interface ICourierProvider {
|
export interface ICourierProvider {
|
||||||
readonly code: CourierProviderCode;
|
readonly code: CourierProviderCode;
|
||||||
|
|
||||||
@@ -117,7 +124,10 @@ export interface ICourierProvider {
|
|||||||
getShipment(query: ShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail>;
|
getShipment(query: ShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail>;
|
||||||
batchGetShipments(query: BatchShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail[]>;
|
batchGetShipments(query: BatchShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail[]>;
|
||||||
getTrack(query: ShipmentQuery, options?: CourierCallOptions): Promise<TrackNode[]>;
|
getTrack(query: ShipmentQuery, options?: CourierCallOptions): Promise<TrackNode[]>;
|
||||||
|
getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]>;
|
||||||
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult>;
|
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult>;
|
||||||
estimateFreight(weight: number, options?: CourierCallOptions): Promise<FreightEstimateResult>;
|
estimateFreight(weight: number, options?: CourierCallOptions): Promise<FreightEstimateResult>;
|
||||||
|
parseTrackCallback(body: unknown): TrackCallbackPayload | null;
|
||||||
|
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null;
|
||||||
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse;
|
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export const XIAOFEIXIA_CMD = {
|
|||||||
GET_ORDER: '100104',
|
GET_ORDER: '100104',
|
||||||
ESTIMATE_FREIGHT: '100105',
|
ESTIMATE_FREIGHT: '100105',
|
||||||
BATCH_GET_ORDER: '100106',
|
BATCH_GET_ORDER: '100106',
|
||||||
|
SIGN_PHOTOS: '100108',
|
||||||
DELIVERY_COVERAGE: '100301',
|
DELIVERY_COVERAGE: '100301',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import type {
|
|||||||
ShipmentDetail,
|
ShipmentDetail,
|
||||||
ShipmentQuery,
|
ShipmentQuery,
|
||||||
TrackCallbackResponse,
|
TrackCallbackResponse,
|
||||||
|
TrackCallbackPayload,
|
||||||
TrackNode,
|
TrackNode,
|
||||||
|
CourierMappedOrderStatus,
|
||||||
} from '../courier.types';
|
} from '../courier.types';
|
||||||
import { XiaofeixiaClient } from './xiaofeixia.client';
|
import { XiaofeixiaClient } from './xiaofeixia.client';
|
||||||
import { XIAOFEIXIA_CMD } from './xiaofeixia.constants';
|
import { XIAOFEIXIA_CMD } from './xiaofeixia.constants';
|
||||||
@@ -121,6 +123,67 @@ export class XiaofeixiaProvider implements ICourierProvider {
|
|||||||
return data ?? [];
|
return data ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]> {
|
||||||
|
this.assertShipmentQuery(query);
|
||||||
|
const data = await this.client.request<string[]>(
|
||||||
|
XIAOFEIXIA_CMD.SIGN_PHOTOS,
|
||||||
|
{
|
||||||
|
number: query.trackingNumber,
|
||||||
|
outNumber: query.outNumber,
|
||||||
|
},
|
||||||
|
options?.xiaofeixia,
|
||||||
|
);
|
||||||
|
return (data ?? []).filter((item) => typeof item === 'string' && item.trim().length > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
parseTrackCallback(body: unknown): TrackCallbackPayload | null {
|
||||||
|
if (!body || typeof body !== 'object') return null;
|
||||||
|
const root = body as Record<string, unknown>;
|
||||||
|
// 兼容顶层字段或 data/payload 包裹
|
||||||
|
const nested =
|
||||||
|
root.data && typeof root.data === 'object'
|
||||||
|
? (root.data as Record<string, unknown>)
|
||||||
|
: root.payload && typeof root.payload === 'object'
|
||||||
|
? (root.payload as Record<string, unknown>)
|
||||||
|
: null;
|
||||||
|
const raw = nested ? { ...nested, ...root } : root;
|
||||||
|
const outNumber = String(raw.outNumber ?? '').trim();
|
||||||
|
const trackingNumber = String(raw.number ?? raw.trackingNumber ?? '').trim();
|
||||||
|
const status = String(raw.status ?? '').trim();
|
||||||
|
const statusName = String(raw.statusName ?? '').trim();
|
||||||
|
const trackInfo = String(raw.trackInfo ?? '').trim();
|
||||||
|
const createTime = String(raw.createTime ?? '').trim();
|
||||||
|
if (!outNumber && !trackingNumber) return null;
|
||||||
|
if (!status && !trackInfo) return null;
|
||||||
|
return {
|
||||||
|
outNumber,
|
||||||
|
trackingNumber,
|
||||||
|
status,
|
||||||
|
statusName,
|
||||||
|
trackInfo,
|
||||||
|
createTime,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null {
|
||||||
|
const name = (statusName || '').trim();
|
||||||
|
if (status === '5' || /签收/.test(name)) {
|
||||||
|
return 'COMPLETED';
|
||||||
|
}
|
||||||
|
switch (String(status).trim()) {
|
||||||
|
case '1':
|
||||||
|
return 'OUT_WAREHOUSE';
|
||||||
|
case '2':
|
||||||
|
case '3':
|
||||||
|
case '4':
|
||||||
|
return 'SHIPPING';
|
||||||
|
case '7':
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
async checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
||||||
const data = await this.client.request<XiaofeixiaDeliveryCoverageData>(
|
const data = await this.client.request<XiaofeixiaDeliveryCoverageData>(
|
||||||
XIAOFEIXIA_CMD.DELIVERY_COVERAGE,
|
XIAOFEIXIA_CMD.DELIVERY_COVERAGE,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { resolveMockSmsFixedCode } from '@dukang/shared-types';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { MockSmsCodeService } from '../../common/mock-sms-code/mock-sms-code.service';
|
import { MockSmsCodeService } from '../../common/mock-sms-code/mock-sms-code.service';
|
||||||
import type { ISmsProvider, SmsActorRef, SmsSendResult } from './sms.interface';
|
import type { ISmsProvider, SmsActorRef, SmsSendResult } from './sms.interface';
|
||||||
import { MOCK_SMS_FIXED_CODE, SmsCodeStore } from './sms-code.store';
|
import { SmsCodeStore } from './sms-code.store';
|
||||||
|
|
||||||
function maskPhone(phone: string) {
|
function maskPhone(phone: string) {
|
||||||
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
||||||
@@ -19,7 +20,8 @@ export class SmsMockProvider implements ISmsProvider {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async send(phone: string, scene: string, actorRef?: SmsActorRef): Promise<SmsSendResult> {
|
async send(phone: string, scene: string, actorRef?: SmsActorRef): Promise<SmsSendResult> {
|
||||||
const code = await this.smsCodeStore.storeCode(phone, scene, MOCK_SMS_FIXED_CODE);
|
const fixedCode = resolveMockSmsFixedCode(process.env);
|
||||||
|
const code = await this.smsCodeStore.storeCode(phone, scene, fixedCode);
|
||||||
await this.mockSmsCodeService.record(phone, scene, code);
|
await this.mockSmsCodeService.record(phone, scene, code);
|
||||||
const masked = maskPhone(phone);
|
const masked = maskPhone(phone);
|
||||||
this.logger.log(`Mock SMS → ${masked} scene=${scene} code=${code}`);
|
this.logger.log(`Mock SMS → ${masked} scene=${scene} code=${code}`);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { AlertService } from '../common/alert/alert.service';
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 财务对账单定时任务(Asia/Shanghai)
|
* 财务对账单定时任务(Asia/Shanghai)
|
||||||
* - 每日 08:00:酒厂日账单 + 门店日账单(统计昨日 00:00~今日 00:00)
|
* - 每日 08:00:酒厂日账单(T+3:3 天前已完成订单)+ 门店日账单(昨日核销)
|
||||||
* - 每月 1 日 08:00:合伙人上一自然月账单 + 物流承运商上一自然月对账
|
* - 每月 1 日 08:00:合伙人上一自然月账单 + 物流承运商上一自然月对账
|
||||||
* - 工作日 18:05:门店提现 T+0 审完预警(FIN-003)
|
* - 工作日 18:05:门店提现 T+0 审完预警(FIN-003)
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { NestFactory } from '@nestjs/core';
|
|||||||
import { loadAppConfig } from '@dukang/shared-types';
|
import { loadAppConfig } from '@dukang/shared-types';
|
||||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { json } from 'express';
|
import { json, urlencoded } from 'express';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||||
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
|
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
|
||||||
@@ -26,6 +26,7 @@ async function bootstrap() {
|
|||||||
app.setGlobalPrefix('api/v1');
|
app.setGlobalPrefix('api/v1');
|
||||||
app.set('trust proxy', true);
|
app.set('trust proxy', true);
|
||||||
app.enableCors({ origin: true, credentials: true });
|
app.enableCors({ origin: true, credentials: true });
|
||||||
|
// 微信支付等需 rawBody;小飞侠回调多为 x-www-form-urlencoded
|
||||||
app.use(
|
app.use(
|
||||||
json({
|
json({
|
||||||
verify: (req, _res, buf) => {
|
verify: (req, _res, buf) => {
|
||||||
@@ -39,6 +40,7 @@ async function bootstrap() {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
app.use(urlencoded({ extended: true }));
|
||||||
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
|
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
|
||||||
app.useGlobalFilters(new HttpExceptionFilter(app.get(AlertService)));
|
app.useGlobalFilters(new HttpExceptionFilter(app.get(AlertService)));
|
||||||
app.useGlobalInterceptors(new ResponseInterceptor(), app.get(LoggingInterceptor));
|
app.useGlobalInterceptors(new ResponseInterceptor(), app.get(LoggingInterceptor));
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { BadRequestException, Body, Controller, Post, UseGuards } from '@nestjs/common';
|
import { BadRequestException, Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
|
||||||
|
import type { Request } from 'express';
|
||||||
import { AnalyticsService } from './analytics.service';
|
import { AnalyticsService } from './analytics.service';
|
||||||
import { PromoCodeService } from '../promo/promo-code.service';
|
import { PromoCodeService } from '../promo/promo-code.service';
|
||||||
|
import { extractClientIp } from '../../common/geo/client-ip.util';
|
||||||
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
import { OptionalJwtAuthGuard } from '../../common/guards/optional-jwt-auth.guard';
|
import { OptionalJwtAuthGuard } from '../../common/guards/optional-jwt-auth.guard';
|
||||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||||
@@ -66,8 +68,13 @@ export class PromoController {
|
|||||||
|
|
||||||
@Post('touch')
|
@Post('touch')
|
||||||
@UseGuards(OptionalJwtAuthGuard)
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
async touch(@CurrentUser() user: AuthUser | undefined, @Body() dto: PromoTouchDto) {
|
async touch(
|
||||||
|
@CurrentUser() user: AuthUser | undefined,
|
||||||
|
@Body() dto: PromoTouchDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
) {
|
||||||
const userId = user?.actorType === ActorType.USER ? user.actorId : undefined;
|
const userId = user?.actorType === ActorType.USER ? user.actorId : undefined;
|
||||||
|
const clientIp = extractClientIp(req) ?? undefined;
|
||||||
const result = await this.promoCodeService.touch(
|
const result = await this.promoCodeService.touch(
|
||||||
{
|
{
|
||||||
promoCode: dto.promoCode,
|
promoCode: dto.promoCode,
|
||||||
@@ -76,6 +83,7 @@ export class PromoController {
|
|||||||
countScan: dto.countScan,
|
countScan: dto.countScan,
|
||||||
},
|
},
|
||||||
userId,
|
userId,
|
||||||
|
{ clientIp, sessionId: dto.sessionId },
|
||||||
);
|
);
|
||||||
|
|
||||||
void this.analyticsService.trackBatchOptional(
|
void this.analyticsService.trackBatchOptional(
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get } from '@nestjs/common';
|
||||||
import { parseMiniHomeBanners } from '@dukang/shared-types';
|
import {
|
||||||
|
parseMiniHomeBanners,
|
||||||
|
resolveClientBrandRuntime,
|
||||||
|
resolveMiniShareRuntime,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import { SystemConfigService } from '../../common/system-config/system-config.service';
|
import { SystemConfigService } from '../../common/system-config/system-config.service';
|
||||||
|
|
||||||
@Controller('common')
|
@Controller('common')
|
||||||
@@ -11,6 +15,9 @@ export class ClientConfigController {
|
|||||||
const cfg = this.systemConfig.getAppConfig();
|
const cfg = this.systemConfig.getAppConfig();
|
||||||
const env = this.systemConfig.getMergedEnv();
|
const env = this.systemConfig.getMergedEnv();
|
||||||
const footer = (env.MINI_HOME_FOOTER_URL ?? '').trim();
|
const footer = (env.MINI_HOME_FOOTER_URL ?? '').trim();
|
||||||
|
const minClientVersion = (env.MINI_USER_MIN_VERSION ?? '').trim() || null;
|
||||||
|
const brand = resolveClientBrandRuntime(env);
|
||||||
|
const share = resolveMiniShareRuntime(env);
|
||||||
return {
|
return {
|
||||||
mockPay: cfg.mockPay,
|
mockPay: cfg.mockPay,
|
||||||
wechatPayEnabled: cfg.wechatPayEnabled,
|
wechatPayEnabled: cfg.wechatPayEnabled,
|
||||||
@@ -19,10 +26,18 @@ export class ClientConfigController {
|
|||||||
wxAuthorize: cfg.wxAuthorize,
|
wxAuthorize: cfg.wxAuthorize,
|
||||||
/** 可选暴露;选点已改为服务端 /common/lbs,前端可不依赖此字段 */
|
/** 可选暴露;选点已改为服务端 /common/lbs,前端可不依赖此字段 */
|
||||||
tencentLbsKey: cfg.tencentLbsKey || undefined,
|
tencentLbsKey: cfg.tencentLbsKey || undefined,
|
||||||
|
minClientVersion,
|
||||||
miniHome: {
|
miniHome: {
|
||||||
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),
|
banners: parseMiniHomeBanners(env.MINI_HOME_BANNERS),
|
||||||
footerUrl: footer || null,
|
footerUrl: footer || null,
|
||||||
},
|
},
|
||||||
|
userH5Url: brand.userH5Url,
|
||||||
|
brandLogoUrl: brand.brandLogoUrl,
|
||||||
|
brandLogoWideUrl: brand.brandLogoWideUrl,
|
||||||
|
brandLogoMarkUrl: brand.brandLogoMarkUrl,
|
||||||
|
qualificationDisclosureUrl: brand.qualificationDisclosureUrl,
|
||||||
|
customerServicePhone: brand.customerServicePhone,
|
||||||
|
share,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ export class SupportTicketListQueryDto {
|
|||||||
@IsIn(['PENDING_REVIEW', 'REJECTED', 'DEVELOPING', 'TESTING', 'PASSED'])
|
@IsIn(['PENDING_REVIEW', 'REJECTED', 'DEVELOPING', 'TESTING', 'PASSED'])
|
||||||
status?: string;
|
status?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['LOW', 'NORMAL', 'HIGH', 'URGENT'])
|
||||||
|
priority?: string;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@Type(() => Number)
|
@Type(() => Number)
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@@ -46,6 +50,10 @@ export class CreateSupportTicketDto {
|
|||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
attachmentUrls?: string[];
|
attachmentUrls?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['LOW', 'NORMAL', 'HIGH', 'URGENT'])
|
||||||
|
priority?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateSupportTicketDto {
|
export class UpdateSupportTicketDto {
|
||||||
@@ -72,6 +80,10 @@ export class UpdateSupportTicketDto {
|
|||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
attachmentUrls?: string[];
|
attachmentUrls?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['LOW', 'NORMAL', 'HIGH', 'URGENT'])
|
||||||
|
priority?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BatchUpdateSupportTicketStatusDto {
|
export class BatchUpdateSupportTicketStatusDto {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {
|
|||||||
Injectable,
|
Injectable,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type { SupportTicketStatus, SupportTicketType } from '@prisma/client';
|
import type { SupportTicketStatus, SupportTicketType, SupportTicketPriority } from '@prisma/client';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import type { CreateDevPlanTaskFromTicketInput } from '@dukang/shared-types';
|
import type { CreateDevPlanTaskFromTicketInput } from '@dukang/shared-types';
|
||||||
import { mapSupportTicketTypeToDevPlanTask } from '@dukang/shared-types';
|
import { mapSupportTicketTypeToDevPlanTask } from '@dukang/shared-types';
|
||||||
@@ -68,6 +68,7 @@ export class SupportTicketService {
|
|||||||
title: dto.title.trim(),
|
title: dto.title.trim(),
|
||||||
content: dto.content?.trim() || null,
|
content: dto.content?.trim() || null,
|
||||||
remark: dto.remark?.trim() || null,
|
remark: dto.remark?.trim() || null,
|
||||||
|
priority: (dto.priority as SupportTicketPriority | undefined) ?? 'NORMAL',
|
||||||
attachmentUrls: dto.attachmentUrls?.length
|
attachmentUrls: dto.attachmentUrls?.length
|
||||||
? (dto.attachmentUrls.map((u) => u.trim()).filter(Boolean) as unknown as Prisma.InputJsonValue)
|
? (dto.attachmentUrls.map((u) => u.trim()).filter(Boolean) as unknown as Prisma.InputJsonValue)
|
||||||
: undefined,
|
: undefined,
|
||||||
@@ -178,6 +179,7 @@ export class SupportTicketService {
|
|||||||
const urls = dto.attachmentUrls.map((u) => u.trim()).filter(Boolean);
|
const urls = dto.attachmentUrls.map((u) => u.trim()).filter(Boolean);
|
||||||
data.attachmentUrls = urls.length ? (urls as unknown as Prisma.InputJsonValue) : Prisma.JsonNull;
|
data.attachmentUrls = urls.length ? (urls as unknown as Prisma.InputJsonValue) : Prisma.JsonNull;
|
||||||
}
|
}
|
||||||
|
if (dto.priority != null) data.priority = dto.priority as SupportTicketPriority;
|
||||||
const updated = await this.prisma.commonSupportTicket.update({ where: { id }, data });
|
const updated = await this.prisma.commonSupportTicket.update({ where: { id }, data });
|
||||||
return serializeBigInt(mapSupportTicketRow(updated));
|
return serializeBigInt(mapSupportTicketRow(updated));
|
||||||
}
|
}
|
||||||
@@ -247,6 +249,9 @@ export class SupportTicketService {
|
|||||||
if (query.status) {
|
if (query.status) {
|
||||||
where.status = query.status as SupportTicketStatus;
|
where.status = query.status as SupportTicketStatus;
|
||||||
}
|
}
|
||||||
|
if (query.priority) {
|
||||||
|
where.priority = query.priority as SupportTicketPriority;
|
||||||
|
}
|
||||||
|
|
||||||
const [items, total] = await Promise.all([
|
const [items, total] = await Promise.all([
|
||||||
this.prisma.commonSupportTicket.findMany({
|
this.prisma.commonSupportTicket.findMany({
|
||||||
|
|||||||
@@ -671,6 +671,10 @@ export class DevPlanService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (status === 'RELEASED') {
|
||||||
|
await this.cascadeVersionReleased(row.id, row.versionNo);
|
||||||
|
}
|
||||||
|
|
||||||
return this.getVersion(row.id);
|
return this.getVersion(row.id);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -739,6 +743,14 @@ export class DevPlanService {
|
|||||||
|
|
||||||
await this.prisma.devPlanVersion.update({ where: { id }, data });
|
await this.prisma.devPlanVersion.update({ where: { id }, data });
|
||||||
|
|
||||||
|
if (
|
||||||
|
dto.status === 'RELEASED' &&
|
||||||
|
existing.status !== 'RELEASED'
|
||||||
|
) {
|
||||||
|
const versionNo = (dto.versionNo ?? existing.versionNo).trim();
|
||||||
|
await this.cascadeVersionReleased(id, versionNo);
|
||||||
|
}
|
||||||
|
|
||||||
if (dto.taskIds != null) await this.replaceVersionTasks(id, dto.taskIds);
|
if (dto.taskIds != null) await this.replaceVersionTasks(id, dto.taskIds);
|
||||||
|
|
||||||
return this.getVersion(id);
|
return this.getVersion(id);
|
||||||
@@ -775,6 +787,46 @@ export class DevPlanService {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async cascadeVersionReleased(versionId: bigint, versionNo: string) {
|
||||||
|
const links = await this.prisma.devPlanVersionTask.findMany({
|
||||||
|
where: { versionId },
|
||||||
|
select: { taskId: true },
|
||||||
|
});
|
||||||
|
if (!links.length) return;
|
||||||
|
|
||||||
|
const taskIds = links.map((l) => l.taskId);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
await tx.devPlanTask.updateMany({
|
||||||
|
where: { id: { in: taskIds }, status: { not: 'RELEASED' } },
|
||||||
|
data: { status: 'RELEASED', completedAt: now },
|
||||||
|
});
|
||||||
|
|
||||||
|
const tasks = await tx.devPlanTask.findMany({
|
||||||
|
where: { id: { in: taskIds }, supportTicketId: { not: null } },
|
||||||
|
select: { supportTicketId: true },
|
||||||
|
});
|
||||||
|
const ticketIds = [
|
||||||
|
...new Set(
|
||||||
|
tasks
|
||||||
|
.map((t) => t.supportTicketId)
|
||||||
|
.filter((id): id is bigint => id != null),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if (!ticketIds.length) return;
|
||||||
|
|
||||||
|
await tx.commonSupportTicket.updateMany({
|
||||||
|
where: { id: { in: ticketIds }, status: { not: 'REJECTED' } },
|
||||||
|
data: {
|
||||||
|
status: 'PUBLISHED',
|
||||||
|
releasedVersionNo: versionNo,
|
||||||
|
publishedAt: now,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private async addVersionTasks(versionId: bigint, taskIds: string[]) {
|
private async addVersionTasks(versionId: bigint, taskIds: string[]) {
|
||||||
|
|
||||||
if (!taskIds.length) return;
|
if (!taskIds.length) return;
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ import {
|
|||||||
} from '@dukang/domain';
|
} from '@dukang/domain';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { CourierService } from '../../integrations/courier/courier.service';
|
import { CourierService } from '../../integrations/courier/courier.service';
|
||||||
import { CourierPayMode } from '../../integrations/courier/courier.types';
|
import { CourierPayMode, type TrackNode } from '../../integrations/courier/courier.types';
|
||||||
import type { XiaofeixiaConfig } from '../../integrations/courier/courier.config';
|
import type { XiaofeixiaConfig } from '../../integrations/courier/courier.config';
|
||||||
|
import { OSS_PROVIDER } from '../../integrations/integrations.constants';
|
||||||
|
import type { IOssProvider } from '../../integrations/oss/oss.interface';
|
||||||
import { TradeService } from '../trade/trade.service';
|
import { TradeService } from '../trade/trade.service';
|
||||||
import { FulfillmentProviderService } from './fulfillment-provider.service';
|
import { FulfillmentProviderService } from './fulfillment-provider.service';
|
||||||
|
|
||||||
@@ -32,6 +34,7 @@ export class FulfillmentService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly courier: CourierService,
|
private readonly courier: CourierService,
|
||||||
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
||||||
|
@Inject(OSS_PROVIDER) private readonly oss: IOssProvider,
|
||||||
@Inject(forwardRef(() => TradeService))
|
@Inject(forwardRef(() => TradeService))
|
||||||
private readonly tradeService: TradeService,
|
private readonly tradeService: TradeService,
|
||||||
) {}
|
) {}
|
||||||
@@ -246,13 +249,30 @@ export class FulfillmentService {
|
|||||||
async getOrderTrack(orderId: bigint) {
|
async getOrderTrack(orderId: bigint) {
|
||||||
const order = await this.prisma.order.findUnique({
|
const order = await this.prisma.order.findUnique({
|
||||||
where: { id: orderId },
|
where: { id: orderId },
|
||||||
include: { delivery: true },
|
include: {
|
||||||
|
delivery: {
|
||||||
|
include: { signPhotoResource: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
const base = {
|
||||||
|
nodes: [] as TrackNode[],
|
||||||
|
signPhotoUrls: [] as string[],
|
||||||
|
estimatedArrival: null as { arriveTime: string; siteName?: string } | null,
|
||||||
|
manualQueryUrl: order?.delivery?.manualQueryUrl ?? null,
|
||||||
|
provider: order?.delivery?.provider,
|
||||||
|
trackingNo: order?.delivery?.trackingNo ?? null,
|
||||||
|
logisticsCompany: order?.delivery?.logisticsCompany ?? null,
|
||||||
|
};
|
||||||
if (!order?.delivery) {
|
if (!order?.delivery) {
|
||||||
return { nodes: [], manualQueryUrl: null };
|
return base;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (order.delivery.provider === 'XFX' && (order.delivery.trackingNo || order.orderNo)) {
|
const isXfx =
|
||||||
|
order.delivery.provider === 'XFX' || isXfxProviderCode(String(order.delivery.provider || ''));
|
||||||
|
const canQueryCourier = isXfx && (order.delivery.trackingNo || order.orderNo);
|
||||||
|
|
||||||
|
if (canQueryCourier) {
|
||||||
try {
|
try {
|
||||||
const options = order.delivery.fulfillmentProviderId
|
const options = order.delivery.fulfillmentProviderId
|
||||||
? {
|
? {
|
||||||
@@ -261,27 +281,44 @@ export class FulfillmentService {
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
: undefined;
|
: undefined;
|
||||||
const nodes = await this.courier.getTrack(
|
const shipmentQuery = {
|
||||||
{
|
trackingNumber: order.delivery.trackingNo ?? undefined,
|
||||||
trackingNumber: order.delivery.trackingNo ?? undefined,
|
outNumber: order.orderNo,
|
||||||
outNumber: order.orderNo,
|
|
||||||
},
|
|
||||||
options,
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
nodes,
|
|
||||||
manualQueryUrl: order.delivery.manualQueryUrl,
|
|
||||||
provider: order.delivery.provider,
|
|
||||||
trackingNo: order.delivery.trackingNo,
|
|
||||||
logisticsCompany: order.delivery.logisticsCompany,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const [nodes, signPhotoDataUris] = await Promise.all([
|
||||||
|
this.courier.getTrack(shipmentQuery, options).catch(() => [] as TrackNode[]),
|
||||||
|
this.courier.getSignPhotos(shipmentQuery, options).catch(() => [] as string[]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
base.nodes = this.sortTrackNodesOldestFirst(nodes);
|
||||||
|
base.signPhotoUrls = await this.resolveSignPhotoUrls(order, signPhotoDataUris);
|
||||||
|
|
||||||
|
if (this.shouldFetchEstimatedArrival(order.status, base.nodes)) {
|
||||||
|
const toAddress = this.buildReceiverAddress(order);
|
||||||
|
if (toAddress) {
|
||||||
|
try {
|
||||||
|
const coverage = await this.courier.checkDeliveryCoverage(toAddress, options);
|
||||||
|
base.estimatedArrival = {
|
||||||
|
arriveTime: coverage.arriveTime,
|
||||||
|
siteName: coverage.siteName,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
// 预估送达失败不阻断
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// fall through
|
// fall through
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (base.signPhotoUrls.length === 0 && order.delivery.signPhotoResource?.url) {
|
||||||
|
base.signPhotoUrls = [order.delivery.signPhotoResource.url];
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
nodes: [],
|
...base,
|
||||||
manualQueryUrl: order.delivery.manualQueryUrl,
|
manualQueryUrl: order.delivery.manualQueryUrl,
|
||||||
provider: order.delivery.provider,
|
provider: order.delivery.provider,
|
||||||
trackingNo: order.delivery.trackingNo,
|
trackingNo: order.delivery.trackingNo,
|
||||||
@@ -289,6 +326,119 @@ export class FulfillmentService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sortTrackNodesOldestFirst(nodes: TrackNode[]): TrackNode[] {
|
||||||
|
return [...nodes].sort((a, b) => {
|
||||||
|
const ta = new Date(a.createTime).getTime();
|
||||||
|
const tb = new Date(b.createTime).getTime();
|
||||||
|
if (Number.isNaN(ta) && Number.isNaN(tb)) return 0;
|
||||||
|
if (Number.isNaN(ta)) return 1;
|
||||||
|
if (Number.isNaN(tb)) return -1;
|
||||||
|
return ta - tb;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildReceiverAddress(order: {
|
||||||
|
receiverProvince?: string | null;
|
||||||
|
receiverCity?: string | null;
|
||||||
|
receiverDistrict?: string | null;
|
||||||
|
receiverAddress?: string | null;
|
||||||
|
}) {
|
||||||
|
const region = [order.receiverProvince, order.receiverCity, order.receiverDistrict]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('');
|
||||||
|
const detail = (order.receiverAddress || '').trim();
|
||||||
|
if (!region && !detail) return '';
|
||||||
|
if (region && detail.startsWith(region)) return detail;
|
||||||
|
return `${region}${detail}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private shouldFetchEstimatedArrival(status: string, nodes: TrackNode[]) {
|
||||||
|
if (!['OUT_WAREHOUSE', 'SHIPPING', 'SHIPPED'].includes(status)) return false;
|
||||||
|
if (nodes.length === 0) return true;
|
||||||
|
return !nodes.some(
|
||||||
|
(node) =>
|
||||||
|
node.statusName?.includes('签收') ||
|
||||||
|
node.trackInfo?.includes('签收') ||
|
||||||
|
node.statusName?.includes('派件'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveSignPhotoUrls(
|
||||||
|
order: {
|
||||||
|
id: bigint;
|
||||||
|
delivery: {
|
||||||
|
id: bigint;
|
||||||
|
signPhotoResourceId: bigint | null;
|
||||||
|
signPhotoResource: { url: string } | null;
|
||||||
|
} | null;
|
||||||
|
},
|
||||||
|
dataUris: string[],
|
||||||
|
): Promise<string[]> {
|
||||||
|
if (!order.delivery || dataUris.length === 0) {
|
||||||
|
return order.delivery?.signPhotoResource?.url ? [order.delivery.signPhotoResource.url] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const urls: string[] = [];
|
||||||
|
let firstResourceId: bigint | null = order.delivery.signPhotoResourceId;
|
||||||
|
|
||||||
|
for (let i = 0; i < dataUris.length; i += 1) {
|
||||||
|
const parsed = this.parseDataUri(dataUris[i]);
|
||||||
|
if (!parsed) continue;
|
||||||
|
|
||||||
|
const result = await this.oss.putObject({
|
||||||
|
bizType: 'SIGN_PHOTO',
|
||||||
|
mediaType: 'IMAGE',
|
||||||
|
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
||||||
|
buffer: parsed.buffer,
|
||||||
|
mimeType: parsed.mimeType,
|
||||||
|
});
|
||||||
|
urls.push(result.url);
|
||||||
|
|
||||||
|
if (!firstResourceId) {
|
||||||
|
const resource = await this.prisma.commonResource.create({
|
||||||
|
data: {
|
||||||
|
ownerType: 'ORDER',
|
||||||
|
ownerId: order.id,
|
||||||
|
bizType: 'SIGN_PHOTO',
|
||||||
|
mediaType: 'IMAGE',
|
||||||
|
ossBucket: result.bucket,
|
||||||
|
ossKey: result.ossKey,
|
||||||
|
url: result.url,
|
||||||
|
fileName: `sign-${order.id}-${i + 1}.${parsed.ext}`,
|
||||||
|
fileSize: BigInt(parsed.buffer.length),
|
||||||
|
mimeType: parsed.mimeType,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
firstResourceId = resource.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (firstResourceId && firstResourceId !== order.delivery.signPhotoResourceId) {
|
||||||
|
await this.prisma.orderDelivery.update({
|
||||||
|
where: { id: order.delivery.id },
|
||||||
|
data: { signPhotoResourceId: firstResourceId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return urls;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseDataUri(dataUri: string): { buffer: Buffer; mimeType: string; ext: string } | null {
|
||||||
|
const trimmed = dataUri.trim();
|
||||||
|
const match = /^data:([^;]+);base64,(.+)$/i.exec(trimmed);
|
||||||
|
const base64 = match ? match[2] : trimmed;
|
||||||
|
const mimeType = match?.[1] || 'image/png';
|
||||||
|
try {
|
||||||
|
const buffer = Buffer.from(base64, 'base64');
|
||||||
|
if (!buffer.length) return null;
|
||||||
|
const ext = mimeType.includes('jpeg') || mimeType.includes('jpg') ? 'jpg' : 'png';
|
||||||
|
return { buffer, mimeType, ext };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async applyManualShip(
|
private async applyManualShip(
|
||||||
order: Order & { delivery: { trackingNo: string | null } | null },
|
order: Order & { delivery: { trackingNo: string | null } | null },
|
||||||
input: ManualShipInput & { operator: string; provider?: 'MANUAL' | 'LOGISTICS' },
|
input: ManualShipInput & { operator: string; provider?: 'MANUAL' | 'LOGISTICS' },
|
||||||
|
|||||||
@@ -1692,6 +1692,10 @@ export class AuthService {
|
|||||||
throw new BadRequestException('首次登录请使用手机验证码,登录后将自动关联微信');
|
throw new BadRequestException('首次登录请使用手机验证码,登录后将自动关联微信');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (account.status !== 'ACTIVE') {
|
||||||
|
throw new BadRequestException('合伙人账号已停用');
|
||||||
|
}
|
||||||
|
|
||||||
account = await this.prisma.partnerAccount.update({
|
account = await this.prisma.partnerAccount.update({
|
||||||
where: { id: account.id },
|
where: { id: account.id },
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ export class AdminStoresService {
|
|||||||
take: pageSize,
|
take: pageSize,
|
||||||
include: {
|
include: {
|
||||||
cityRef: { select: { id: true, name: true, code: true } },
|
cityRef: { select: { id: true, name: true, code: true } },
|
||||||
partnerAccount: { select: { id: true, companyName: true } },
|
partnerAccount: { select: { id: true, companyName: true, name: true, phone: true } },
|
||||||
category: { select: { id: true, name: true, parentId: true } },
|
category: { select: { id: true, name: true, parentId: true } },
|
||||||
bindings: {
|
bindings: {
|
||||||
where: { storeAccount: { isPrimary: 1 } },
|
where: { storeAccount: { isPrimary: 1 } },
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { PromoCodeService } from './promo-code.service';
|
|||||||
import {
|
import {
|
||||||
CreatePromoCodeDto,
|
CreatePromoCodeDto,
|
||||||
PromoCodeListQueryDto,
|
PromoCodeListQueryDto,
|
||||||
|
PromoMetricEventsQueryDto,
|
||||||
|
PromoMetricTimelineQueryDto,
|
||||||
UpdatePromoCodeDto,
|
UpdatePromoCodeDto,
|
||||||
UpdatePromoCodeStatusDto,
|
UpdatePromoCodeStatusDto,
|
||||||
} from './dto/promo-code.dto';
|
} from './dto/promo-code.dto';
|
||||||
@@ -39,6 +41,16 @@ export class AdminPromoCodeController {
|
|||||||
return this.service.stats(BigInt(id));
|
return this.service.stats(BigInt(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get(':id/metrics/timeline')
|
||||||
|
metricsTimeline(@Param('id') id: string, @Query() query: PromoMetricTimelineQueryDto) {
|
||||||
|
return this.service.getMetricsTimeline(BigInt(id), query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id/metrics/events')
|
||||||
|
metricsEvents(@Param('id') id: string, @Query() query: PromoMetricEventsQueryDto) {
|
||||||
|
return this.service.listMetricEvents(BigInt(id), query);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':id/qrcode')
|
@Get(':id/qrcode')
|
||||||
qrcode(@Param('id') id: string) {
|
qrcode(@Param('id') id: string) {
|
||||||
return this.service.getQrcodeUrl(BigInt(id));
|
return this.service.getQrcodeUrl(BigInt(id));
|
||||||
|
|||||||
@@ -87,3 +87,37 @@ export class UpdatePromoCodeStatusDto {
|
|||||||
@IsIn(['ACTIVE', 'DISABLED'])
|
@IsIn(['ACTIVE', 'DISABLED'])
|
||||||
status: PromoCodeStatus;
|
status: PromoCodeStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class PromoMetricTimelineQueryDto {
|
||||||
|
@IsString()
|
||||||
|
dateFrom: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
dateTo: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['day', 'hour'])
|
||||||
|
granularity?: 'day' | 'hour';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PromoMetricEventsQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
page?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@Type(() => Number)
|
||||||
|
pageSize?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['SCAN', 'ATTRIBUTION', 'REGISTER', 'ORDER'])
|
||||||
|
eventType?: 'SCAN' | 'ATTRIBUTION' | 'REGISTER' | 'ORDER';
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
dateFrom?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
dateTo?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { randomBytes } from 'crypto';
|
|||||||
import {
|
import {
|
||||||
PROMO_CODE_SCENE_LABELS,
|
PROMO_CODE_SCENE_LABELS,
|
||||||
PromoCodeScene,
|
PromoCodeScene,
|
||||||
|
PromoMetricEventType,
|
||||||
buildPromoLandingUrl,
|
buildPromoLandingUrl,
|
||||||
loadAppConfig,
|
loadAppConfig,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -16,12 +17,30 @@ import { serializeBigInt } from '../../common/decorators/current-user.decorator'
|
|||||||
import { OSS_PROVIDER, WECHAT_PROVIDER } from '../../integrations/integrations.constants';
|
import { OSS_PROVIDER, WECHAT_PROVIDER } from '../../integrations/integrations.constants';
|
||||||
import type { IOssProvider } from '../../integrations/oss/oss.interface';
|
import type { IOssProvider } from '../../integrations/oss/oss.interface';
|
||||||
import type { IWechatProvider } from '../../integrations/wechat/wechat.interface';
|
import type { IWechatProvider } from '../../integrations/wechat/wechat.interface';
|
||||||
|
import { PromoMetricLogService } from './promo-metric-log.service';
|
||||||
|
import {
|
||||||
|
computePromoMetricPeak,
|
||||||
|
eachPromoMetricDay,
|
||||||
|
eachPromoMetricHour,
|
||||||
|
endOfDay,
|
||||||
|
parsePromoMetricYmd,
|
||||||
|
promoMetricBucketKey,
|
||||||
|
promoMetricEventField,
|
||||||
|
startOfDay,
|
||||||
|
} from './promo-metric.util';
|
||||||
import type {
|
import type {
|
||||||
CreatePromoCodeDto,
|
CreatePromoCodeDto,
|
||||||
PromoCodeListQueryDto,
|
PromoCodeListQueryDto,
|
||||||
|
PromoMetricEventsQueryDto,
|
||||||
|
PromoMetricTimelineQueryDto,
|
||||||
UpdatePromoCodeDto,
|
UpdatePromoCodeDto,
|
||||||
} from './dto/promo-code.dto';
|
} from './dto/promo-code.dto';
|
||||||
|
|
||||||
|
type PromoTouchMeta = {
|
||||||
|
clientIp?: string;
|
||||||
|
sessionId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
type PromoRow = {
|
type PromoRow = {
|
||||||
id: bigint;
|
id: bigint;
|
||||||
code: string;
|
code: string;
|
||||||
@@ -69,6 +88,7 @@ function maskPhone(phone: string | null | undefined) {
|
|||||||
export class PromoCodeService {
|
export class PromoCodeService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly promoMetricLog: PromoMetricLogService,
|
||||||
@Inject(OSS_PROVIDER) private readonly oss: IOssProvider,
|
@Inject(OSS_PROVIDER) private readonly oss: IOssProvider,
|
||||||
@Inject(WECHAT_PROVIDER) private readonly wechat: IWechatProvider,
|
@Inject(WECHAT_PROVIDER) private readonly wechat: IWechatProvider,
|
||||||
) {}
|
) {}
|
||||||
@@ -88,7 +108,11 @@ export class PromoCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 代下单绑定推广码:归因 + 用户来源(若可写) */
|
/** 代下单绑定推广码:归因 + 用户来源(若可写) */
|
||||||
async attributeUserToPromo(userId: bigint, promoId: bigint) {
|
async attributeUserToPromo(
|
||||||
|
userId: bigint,
|
||||||
|
promoId: bigint,
|
||||||
|
meta?: PromoTouchMeta,
|
||||||
|
) {
|
||||||
const promo = await this.prisma.commonPromoCode.findUnique({
|
const promo = await this.prisma.commonPromoCode.findUnique({
|
||||||
where: { id: promoId },
|
where: { id: promoId },
|
||||||
select: { id: true, name: true, status: true },
|
select: { id: true, name: true, status: true },
|
||||||
@@ -108,9 +132,13 @@ export class PromoCodeService {
|
|||||||
firstTouchAt: new Date(),
|
firstTouchAt: new Date(),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
this.logPromoMetric(promo.id, 'ATTRIBUTION', meta, { userId });
|
||||||
}
|
}
|
||||||
await this.applyPromoSourceToUser(userId, promo);
|
const sourceApplied = await this.applyPromoSourceToUser(userId, promo, meta);
|
||||||
return promo;
|
if (sourceApplied) {
|
||||||
|
this.logPromoMetric(promo.id, 'REGISTER', meta, { userId });
|
||||||
|
}
|
||||||
|
return { promo, sourceApplied };
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapOwnerUser(user: PromoRow['ownerUser']) {
|
private mapOwnerUser(user: PromoRow['ownerUser']) {
|
||||||
@@ -393,6 +421,7 @@ export class PromoCodeService {
|
|||||||
countScan?: boolean;
|
countScan?: boolean;
|
||||||
},
|
},
|
||||||
userId?: bigint,
|
userId?: bigint,
|
||||||
|
meta?: PromoTouchMeta,
|
||||||
) {
|
) {
|
||||||
const promoCode = input.promoCode?.trim().toUpperCase();
|
const promoCode = input.promoCode?.trim().toUpperCase();
|
||||||
const qrcodeId = input.qrcodeId?.trim();
|
const qrcodeId = input.qrcodeId?.trim();
|
||||||
@@ -433,7 +462,17 @@ export class PromoCodeService {
|
|||||||
attributed = true;
|
attributed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceApplied = await this.applyPromoSourceToUser(userId, promo);
|
sourceApplied = await this.applyPromoSourceToUser(userId, promo, meta);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldCountScan) {
|
||||||
|
this.logPromoMetric(promo.id, 'SCAN', meta, { userId });
|
||||||
|
}
|
||||||
|
if (attributed) {
|
||||||
|
this.logPromoMetric(promo.id, 'ATTRIBUTION', meta, { userId });
|
||||||
|
}
|
||||||
|
if (sourceApplied) {
|
||||||
|
this.logPromoMetric(promo.id, 'REGISTER', meta, { userId });
|
||||||
}
|
}
|
||||||
|
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
@@ -450,6 +489,7 @@ export class PromoCodeService {
|
|||||||
async applyPromoSourceToUser(
|
async applyPromoSourceToUser(
|
||||||
userId: bigint,
|
userId: bigint,
|
||||||
promo: { id: bigint; name: string },
|
promo: { id: bigint; name: string },
|
||||||
|
meta?: PromoTouchMeta,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const user = await this.prisma.user.findUnique({
|
const user = await this.prisma.user.findUnique({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
@@ -470,6 +510,132 @@ export class PromoCodeService {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logPromoOrderEvent(
|
||||||
|
promoCodeId: bigint,
|
||||||
|
orderId: bigint,
|
||||||
|
userId: bigint,
|
||||||
|
clientIp?: string,
|
||||||
|
): void {
|
||||||
|
this.logPromoMetric(promoCodeId, 'ORDER', { clientIp }, { userId, orderId });
|
||||||
|
}
|
||||||
|
|
||||||
|
private logPromoMetric(
|
||||||
|
promoCodeId: bigint,
|
||||||
|
eventType: PromoMetricEventType,
|
||||||
|
meta: PromoTouchMeta | undefined,
|
||||||
|
ids: { userId?: bigint; orderId?: bigint },
|
||||||
|
): void {
|
||||||
|
this.promoMetricLog.logEvent({
|
||||||
|
promoCodeId,
|
||||||
|
eventType,
|
||||||
|
userId: ids.userId,
|
||||||
|
orderId: ids.orderId,
|
||||||
|
sessionId: meta?.sessionId,
|
||||||
|
clientIp: meta?.clientIp,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMetricsTimeline(promoId: bigint, query: PromoMetricTimelineQueryDto) {
|
||||||
|
await this.ensurePromoExists(promoId);
|
||||||
|
|
||||||
|
const granularity = query.granularity === 'hour' ? 'hour' : 'day';
|
||||||
|
const from = parsePromoMetricYmd(query.dateFrom) ?? startOfDay(new Date());
|
||||||
|
const toParsed = parsePromoMetricYmd(query.dateTo);
|
||||||
|
const to = toParsed ? endOfDay(toParsed) : endOfDay(new Date());
|
||||||
|
|
||||||
|
const keys =
|
||||||
|
granularity === 'hour'
|
||||||
|
? eachPromoMetricHour(from, to)
|
||||||
|
: eachPromoMetricDay(from, to);
|
||||||
|
|
||||||
|
const bucketMap = new Map(
|
||||||
|
keys.map((key) => [key, { key, scan: 0, attribution: 0, register: 0, order: 0 }]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows = await this.prisma.logPromoEvent.findMany({
|
||||||
|
where: {
|
||||||
|
promoCodeId: promoId,
|
||||||
|
createdAt: { gte: from, lte: to },
|
||||||
|
},
|
||||||
|
select: { eventType: true, createdAt: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const key = promoMetricBucketKey(row.createdAt, granularity);
|
||||||
|
const bucket = bucketMap.get(key);
|
||||||
|
if (!bucket) continue;
|
||||||
|
bucket[promoMetricEventField(row.eventType)] += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buckets = keys.map((key) => bucketMap.get(key)!);
|
||||||
|
return serializeBigInt({
|
||||||
|
granularity,
|
||||||
|
dateFrom: query.dateFrom,
|
||||||
|
dateTo: query.dateTo,
|
||||||
|
buckets,
|
||||||
|
peak: computePromoMetricPeak(buckets),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async listMetricEvents(promoId: bigint, query: PromoMetricEventsQueryDto) {
|
||||||
|
await this.ensurePromoExists(promoId);
|
||||||
|
|
||||||
|
const page = query.page && query.page > 0 ? query.page : 1;
|
||||||
|
const pageSize = query.pageSize && query.pageSize > 0 ? Math.min(query.pageSize, 100) : 20;
|
||||||
|
|
||||||
|
const from = query.dateFrom ? parsePromoMetricYmd(query.dateFrom) : undefined;
|
||||||
|
const toParsed = query.dateTo ? parsePromoMetricYmd(query.dateTo) : undefined;
|
||||||
|
const to = toParsed ? endOfDay(toParsed) : undefined;
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
promoCodeId: promoId,
|
||||||
|
...(query.eventType ? { eventType: query.eventType } : {}),
|
||||||
|
...(from || to
|
||||||
|
? {
|
||||||
|
createdAt: {
|
||||||
|
...(from ? { gte: from } : {}),
|
||||||
|
...(to ? { lte: to } : {}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.logPromoEvent.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (page - 1) * pageSize,
|
||||||
|
take: pageSize,
|
||||||
|
}),
|
||||||
|
this.prisma.logPromoEvent.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return serializeBigInt({
|
||||||
|
items: items.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
eventType: row.eventType,
|
||||||
|
userId: row.userId,
|
||||||
|
orderId: row.orderId,
|
||||||
|
sessionId: row.sessionId,
|
||||||
|
clientIp: row.clientIp,
|
||||||
|
ipProvince: row.ipProvince,
|
||||||
|
ipCity: row.ipCity,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
})),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensurePromoExists(promoId: bigint) {
|
||||||
|
const promo = await this.prisma.commonPromoCode.findUnique({
|
||||||
|
where: { id: promoId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!promo) throw new NotFoundException('推广码不存在');
|
||||||
|
}
|
||||||
|
|
||||||
private async statsFromRow(row: { id: bigint; scanCount: number; orderCount: number }) {
|
private async statsFromRow(row: { id: bigint; scanCount: number; orderCount: number }) {
|
||||||
const scanCount = row.scanCount;
|
const scanCount = row.scanCount;
|
||||||
const orderCount = row.orderCount;
|
const orderCount = row.orderCount;
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { PromoMetricEventType } from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { IpGeoService } from '../../common/geo/ip-geo.service';
|
||||||
|
|
||||||
|
export type PromoMetricLogInput = {
|
||||||
|
promoCodeId: bigint;
|
||||||
|
eventType: PromoMetricEventType;
|
||||||
|
userId?: bigint;
|
||||||
|
orderId?: bigint;
|
||||||
|
sessionId?: string;
|
||||||
|
clientIp?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PromoMetricLogService {
|
||||||
|
private readonly logger = new Logger(PromoMetricLogService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly ipGeoService: IpGeoService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
logEvent(input: PromoMetricLogInput): void {
|
||||||
|
void this.writeEvent(input).catch((err) => {
|
||||||
|
this.logger.debug(
|
||||||
|
`promo metric log failed: ${err instanceof Error ? err.message : err}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async writeEvent(input: PromoMetricLogInput): Promise<void> {
|
||||||
|
const clientIp = input.clientIp?.trim() || null;
|
||||||
|
const geo = clientIp ? this.ipGeoService.resolve(clientIp) : { province: null, city: null };
|
||||||
|
|
||||||
|
await this.prisma.logPromoEvent.create({
|
||||||
|
data: {
|
||||||
|
promoCodeId: input.promoCodeId,
|
||||||
|
eventType: input.eventType,
|
||||||
|
userId: input.userId ?? null,
|
||||||
|
orderId: input.orderId ?? null,
|
||||||
|
sessionId: input.sessionId?.trim() || null,
|
||||||
|
clientIp,
|
||||||
|
ipProvince: geo.province,
|
||||||
|
ipCity: geo.city,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user