Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f06530894 | |||
| 1f4506f60b | |||
| a2976cdc8f | |||
| cc0c0a6ef8 | |||
| ee1a3f4b6c | |||
| 52a7d3789d | |||
| 98d52ff173 | |||
| 797b20979d |
@@ -26,3 +26,4 @@ server/dukang-api/assets/fonts/*.ttc
|
|||||||
server/dukang-api/assets/fonts/*.otf
|
server/dukang-api/assets/fonts/*.otf
|
||||||
deploy/auto-release.env
|
deploy/auto-release.env
|
||||||
deploy/backups/
|
deploy/backups/
|
||||||
|
.playwright-mcp/
|
||||||
|
|||||||
@@ -11,10 +11,23 @@ import PackageImagesUpload from './PackageImagesUpload';
|
|||||||
type PackageRow = StorePackageItemDto;
|
type PackageRow = StorePackageItemDto;
|
||||||
|
|
||||||
export type AdminStorePackagesHandle = {
|
export type AdminStorePackagesHandle = {
|
||||||
/** 套餐已加载时写入;加载中则跳过,避免空数据覆盖线上套餐 */
|
/** 仅在用户改过套餐时写入;加载中或未改动则跳过,避免空表单覆盖刚审核通过的线上套餐 */
|
||||||
saveIfLoaded: (opts?: { quiet?: boolean }) => Promise<{ skipped: boolean }>;
|
saveIfLoaded: (opts?: { quiet?: boolean }) => Promise<{ skipped: boolean }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function mapLiveRows(live: StorePackagesResponse['live']): PackageRow[] {
|
||||||
|
return (live ?? []).map((p, i) => {
|
||||||
|
const imageUrls = normalizeStorePackageImageUrls(p);
|
||||||
|
return {
|
||||||
|
...p,
|
||||||
|
price: String(p.price),
|
||||||
|
imageUrl: imageUrls[0] ?? '',
|
||||||
|
imageUrls,
|
||||||
|
sortOrder: i,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function emptyRow(index = 0): PackageRow {
|
function emptyRow(index = 0): PackageRow {
|
||||||
return {
|
return {
|
||||||
name: '',
|
name: '',
|
||||||
@@ -37,6 +50,7 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
|
|||||||
const [pendingRequest, setPendingRequest] = useState<StorePackagesResponse['pendingRequest']>(null);
|
const [pendingRequest, setPendingRequest] = useState<StorePackagesResponse['pendingRequest']>(null);
|
||||||
const itemsRef = useRef(items);
|
const itemsRef = useRef(items);
|
||||||
const loadingRef = useRef(loading);
|
const loadingRef = useRef(loading);
|
||||||
|
const dirtyRef = useRef(false);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -47,36 +61,33 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
|
|||||||
loadingRef.current = loading;
|
loadingRef.current = loading;
|
||||||
}, [loading]);
|
}, [loading]);
|
||||||
|
|
||||||
|
function applyServerPackages(data: StorePackagesResponse) {
|
||||||
|
dirtyRef.current = false;
|
||||||
|
setPendingRequest(data.pendingRequest ?? null);
|
||||||
|
setItems(mapLiveRows(data.live));
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setPendingRequest(null);
|
setPendingRequest(null);
|
||||||
|
dirtyRef.current = false;
|
||||||
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
||||||
.then((data) => {
|
.then((data) => applyServerPackages(data))
|
||||||
setPendingRequest(data.pendingRequest ?? null);
|
|
||||||
setItems(
|
|
||||||
data.live?.length
|
|
||||||
? data.live.map((p, i) => {
|
|
||||||
const imageUrls = normalizeStorePackageImageUrls(p);
|
|
||||||
return {
|
|
||||||
...p,
|
|
||||||
price: String(p.price),
|
|
||||||
imageUrl: imageUrls[0] ?? '',
|
|
||||||
imageUrls,
|
|
||||||
sortOrder: i,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
: [],
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.catch((e) => message.error(e instanceof Error ? e.message : '加载套餐失败'))
|
.catch((e) => message.error(e instanceof Error ? e.message : '加载套餐失败'))
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, [storeId]);
|
}, [storeId]);
|
||||||
|
|
||||||
// 在审核页完成审核后,自动刷新本页「有待审核套餐」提醒
|
// 审核通过/驳回后刷新提醒;用户未改套餐时同步线上结果,避免抽屉里仍显示空套餐
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onChanged = () => {
|
const onChanged = () => {
|
||||||
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
||||||
.then((data) => setPendingRequest(data.pendingRequest ?? null))
|
.then((data) => {
|
||||||
|
setPendingRequest(data.pendingRequest ?? null);
|
||||||
|
if (!dirtyRef.current) {
|
||||||
|
dirtyRef.current = false;
|
||||||
|
setItems(mapLiveRows(data.live));
|
||||||
|
}
|
||||||
|
})
|
||||||
.catch(() => undefined);
|
.catch(() => undefined);
|
||||||
};
|
};
|
||||||
window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
||||||
@@ -108,16 +119,19 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
|
|||||||
) : null;
|
) : null;
|
||||||
|
|
||||||
function updateAt(index: number, patch: Partial<PackageRow>) {
|
function updateAt(index: number, patch: Partial<PackageRow>) {
|
||||||
|
dirtyRef.current = true;
|
||||||
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||||
}
|
}
|
||||||
|
|
||||||
function addRow() {
|
function addRow() {
|
||||||
if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
|
if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
|
||||||
|
dirtyRef.current = true;
|
||||||
setItems((prev) => [...prev, emptyRow(prev.length)]);
|
setItems((prev) => [...prev, emptyRow(prev.length)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeAt(index: number) {
|
function removeAt(index: number) {
|
||||||
const run = () => {
|
const run = () => {
|
||||||
|
dirtyRef.current = true;
|
||||||
setItems((prev) => {
|
setItems((prev) => {
|
||||||
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
||||||
return next.length ? next : [];
|
return next.length ? next : [];
|
||||||
@@ -203,20 +217,8 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (!opts?.quiet) message.success('套餐已保存并生效');
|
if (!opts?.quiet) message.success('套餐已保存并生效');
|
||||||
setItems(
|
dirtyRef.current = false;
|
||||||
data.live?.length
|
setItems(mapLiveRows(data.live));
|
||||||
? data.live.map((p, i) => {
|
|
||||||
const imageUrls = normalizeStorePackageImageUrls(p);
|
|
||||||
return {
|
|
||||||
...p,
|
|
||||||
price: String(p.price),
|
|
||||||
imageUrl: imageUrls[0] ?? '',
|
|
||||||
imageUrls,
|
|
||||||
sortOrder: i,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
: [],
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!opts?.quiet) message.error(e instanceof Error ? e.message : '保存失败');
|
if (!opts?.quiet) message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
throw e;
|
throw e;
|
||||||
@@ -227,7 +229,7 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
|
|||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
saveIfLoaded: async (opts) => {
|
saveIfLoaded: async (opts) => {
|
||||||
if (loadingRef.current) return { skipped: true };
|
if (loadingRef.current || !dirtyRef.current) return { skipped: true };
|
||||||
await save(opts);
|
await save(opts);
|
||||||
return { skipped: false };
|
return { skipped: false };
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -173,7 +173,9 @@ export default function OrderTrackDrawer({
|
|||||||
<Empty
|
<Empty
|
||||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
description={
|
description={
|
||||||
track?.manualQueryUrl
|
track?.queryError
|
||||||
|
? track.queryError
|
||||||
|
: track?.manualQueryUrl
|
||||||
? '暂无实时路由节点,可使用上方物流查询链接'
|
? '暂无实时路由节点,可使用上方物流查询链接'
|
||||||
: '暂无路由信息,请稍后刷新'
|
: '暂无路由信息,请稍后刷新'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ import {
|
|||||||
AccountBookOutlined,
|
AccountBookOutlined,
|
||||||
ProjectOutlined,
|
ProjectOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { hasAnySystemSettingsPermission, hasAnyStoreMenuPermission } from '@dukang/shared-types';
|
import {
|
||||||
|
hasAnySystemSettingsPermission,
|
||||||
|
hasAnyStoreMenuPermission,
|
||||||
|
HQ_ADMIN_ROLES,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import { clearAuth, request, type HqProfile } from '../lib/api';
|
import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||||
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
||||||
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
||||||
@@ -28,6 +32,10 @@ import { ListColumnPrefsProvider } from '../lib/ListColumnPrefsContext';
|
|||||||
|
|
||||||
const { Header, Sider, Content } = Layout;
|
const { Header, Sider, Content } = Layout;
|
||||||
|
|
||||||
|
const HQ_ROLE_LABELS: Record<string, string> = Object.fromEntries(
|
||||||
|
HQ_ADMIN_ROLES.map((r) => [r.value, r.label]),
|
||||||
|
);
|
||||||
|
|
||||||
type MenuItem = NonNullable<MenuProps['items']>[number];
|
type MenuItem = NonNullable<MenuProps['items']>[number];
|
||||||
|
|
||||||
const MENU_ITEMS: MenuProps['items'] = [
|
const MENU_ITEMS: MenuProps['items'] = [
|
||||||
@@ -405,7 +413,9 @@ export default function AdminLayout() {
|
|||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
<Space>
|
<Space>
|
||||||
<span>{profile?.name || '—'}</span>
|
<span>{profile?.name || '—'}</span>
|
||||||
<span style={{ color: '#999' }}>{profile?.adminRole}</span>
|
<span style={{ color: '#999' }}>
|
||||||
|
{HQ_ROLE_LABELS[profile?.adminRole ?? ''] || profile?.adminRole || ''}
|
||||||
|
</span>
|
||||||
<Button type="text" icon={<LogoutOutlined />} onClick={logout}>
|
<Button type="text" icon={<LogoutOutlined />} onClick={logout}>
|
||||||
退出
|
退出
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -236,5 +236,7 @@ export type AdminOrderRow = {
|
|||||||
providerOrderNo: string | null;
|
providerOrderNo: string | null;
|
||||||
logisticsCompany?: string | null;
|
logisticsCompany?: string | null;
|
||||||
manualQueryUrl?: string | null;
|
manualQueryUrl?: string | null;
|
||||||
|
/** 当次应付物流费(按瓶当量 × 承运商计价) */
|
||||||
|
logisticsFee?: number | null;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,16 +1,43 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button, Descriptions, Drawer, Form, Input, Space, Table, Typography, message,
|
Button, Descriptions, Drawer, Form, Input, Space, Table, Typography, message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import OrderTrackDrawer from '../components/OrderTrackDrawer';
|
import OrderTrackDrawer from '../components/OrderTrackDrawer';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { ORDER_STATUS_LABELS, fmtTime } from '../lib/constants';
|
import {
|
||||||
|
DELIVERY_PROVIDER_LABELS,
|
||||||
|
DELIVERY_TYPE_LABELS,
|
||||||
|
ORDER_STATUS_LABELS,
|
||||||
|
fmtTime,
|
||||||
|
} from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
import { useAdminListColumns } from '../lib/useAdminListColumns';
|
||||||
import { AdminListHeader } from '../components/AdminListHeader';
|
import { AdminListHeader } from '../components/AdminListHeader';
|
||||||
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
|
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
|
||||||
|
|
||||||
|
type DeliveryOrder = {
|
||||||
|
id: string;
|
||||||
|
orderNo: string;
|
||||||
|
status: string;
|
||||||
|
deliveryType: string;
|
||||||
|
productName: string;
|
||||||
|
productSpec?: string | null;
|
||||||
|
barcode69?: string | null;
|
||||||
|
quantity: number;
|
||||||
|
saleUnit?: string;
|
||||||
|
bottlesPerUnit?: number;
|
||||||
|
payAmount?: number;
|
||||||
|
receiverName: string;
|
||||||
|
receiverPhone: string;
|
||||||
|
receiverAddress?: string;
|
||||||
|
receiverProvince?: string;
|
||||||
|
receiverCity?: string;
|
||||||
|
receiverDistrict?: string;
|
||||||
|
user?: { id: string; userNo: string; phone: string | null; nickname: string | null };
|
||||||
|
imageResource?: { url: string } | null;
|
||||||
|
};
|
||||||
|
|
||||||
type Row = {
|
type Row = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -19,19 +46,34 @@ type Row = {
|
|||||||
trackingNo: string | null;
|
trackingNo: string | null;
|
||||||
providerOrderNo: string | null;
|
providerOrderNo: string | null;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
/** 当次应付物流费 */
|
|
||||||
logisticsFee?: number | null;
|
logisticsFee?: number | null;
|
||||||
order?: {
|
order?: DeliveryOrder;
|
||||||
id: string;
|
|
||||||
orderNo: string;
|
|
||||||
status: string;
|
|
||||||
receiverName: string;
|
|
||||||
receiverPhone: string;
|
|
||||||
deliveryType: string;
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function formatQty(order?: DeliveryOrder | null) {
|
||||||
|
if (!order || order.quantity == null) return '—';
|
||||||
|
const unit = order.saleUnit === 'BOX' ? '箱' : '瓶';
|
||||||
|
const bottles =
|
||||||
|
order.saleUnit === 'BOX' && order.bottlesPerUnit && order.bottlesPerUnit > 1
|
||||||
|
? `(${order.quantity * order.bottlesPerUnit}瓶)`
|
||||||
|
: '';
|
||||||
|
return `${order.quantity}${unit}${bottles}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAddress(order?: DeliveryOrder | null) {
|
||||||
|
if (!order) return '—';
|
||||||
|
if (order.deliveryType === 'ON_SITE_PICKUP') return '现场取货';
|
||||||
|
const region = [order.receiverProvince, order.receiverCity, order.receiverDistrict]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('');
|
||||||
|
const detail = (order.receiverAddress || '').trim();
|
||||||
|
if (!region) return detail || '—';
|
||||||
|
if (!detail || detail.startsWith(region)) return detail || region;
|
||||||
|
return `${region}${detail}`;
|
||||||
|
}
|
||||||
|
|
||||||
export default function DeliveriesPage() {
|
export default function DeliveriesPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [editForm] = Form.useForm();
|
const [editForm] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
@@ -65,25 +107,91 @@ export default function DeliveriesPage() {
|
|||||||
setTrackOpen(true);
|
setTrackOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openDetail(row: Row) {
|
||||||
|
const d = await request<Row>(`/admin/deliveries/${row.id}`);
|
||||||
|
setDetail(d);
|
||||||
|
editForm.setFieldsValue({
|
||||||
|
provider: d.provider,
|
||||||
|
trackingNo: d.trackingNo,
|
||||||
|
providerOrderNo: d.providerOrderNo,
|
||||||
|
});
|
||||||
|
setDrawerOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
const baseColumns: ColumnsType<Row> = [
|
const baseColumns: ColumnsType<Row> = [
|
||||||
{
|
{
|
||||||
title: '订单号',
|
title: '订单号',
|
||||||
dataIndex: ['order', 'orderNo'],
|
dataIndex: ['order', 'orderNo'],
|
||||||
width: 170,
|
width: 170,
|
||||||
render: (v, row) => (
|
render: (v, row) => (
|
||||||
<AdminPrimaryLink
|
<AdminPrimaryLink onClick={() => void openDetail(row)}>{v}</AdminPrimaryLink>
|
||||||
onClick={async () => {
|
|
||||||
const d = await request<Row>(`/admin/deliveries/${row.id}`);
|
|
||||||
setDetail(d);
|
|
||||||
editForm.setFieldsValue({ provider: d.provider, trackingNo: d.trackingNo, providerOrderNo: d.providerOrderNo });
|
|
||||||
setDrawerOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{v}
|
|
||||||
</AdminPrimaryLink>
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{ title: 'provider', dataIndex: 'provider', width: 90 },
|
{
|
||||||
|
title: '用户',
|
||||||
|
key: 'user',
|
||||||
|
width: 140,
|
||||||
|
render: (_, row) => {
|
||||||
|
const user = row.order?.user;
|
||||||
|
if (!user) return '—';
|
||||||
|
const label = user.userNo || user.phone || '—';
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{user.id ? (
|
||||||
|
<AdminPrimaryLink
|
||||||
|
onClick={() => navigate('/users', { state: { openUserId: String(user.id) } })}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</AdminPrimaryLink>
|
||||||
|
) : (
|
||||||
|
label
|
||||||
|
)}
|
||||||
|
{user.phone && user.userNo ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
|
||||||
|
{user.phone}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '商品',
|
||||||
|
key: 'product',
|
||||||
|
width: 200,
|
||||||
|
render: (_, row) => {
|
||||||
|
const order = row.order;
|
||||||
|
if (!order?.productName) return '—';
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<span>{order.productName}</span>
|
||||||
|
{order.productSpec ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
|
||||||
|
{order.productSpec}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '数量',
|
||||||
|
key: 'quantity',
|
||||||
|
width: 90,
|
||||||
|
render: (_, row) => formatQty(row.order),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '配送方式',
|
||||||
|
dataIndex: ['order', 'deliveryType'],
|
||||||
|
width: 90,
|
||||||
|
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '承运商',
|
||||||
|
dataIndex: 'provider',
|
||||||
|
width: 90,
|
||||||
|
render: (v: string) => DELIVERY_PROVIDER_LABELS[v] || v || '—',
|
||||||
|
},
|
||||||
{ title: '运单号', dataIndex: 'trackingNo', width: 140, render: (v) => v || '—' },
|
{ title: '运单号', dataIndex: 'trackingNo', width: 140, render: (v) => v || '—' },
|
||||||
{
|
{
|
||||||
title: '运费',
|
title: '运费',
|
||||||
@@ -92,20 +200,33 @@ export default function DeliveriesPage() {
|
|||||||
render: (v: number | null | undefined) => (v == null ? '—' : `¥${Number(v).toFixed(2)}`),
|
render: (v: number | null | undefined) => (v == null ? '—' : `¥${Number(v).toFixed(2)}`),
|
||||||
},
|
},
|
||||||
{ title: '第三方单号', dataIndex: 'providerOrderNo', width: 140, render: (v) => v || '—' },
|
{ title: '第三方单号', dataIndex: 'providerOrderNo', width: 140, render: (v) => v || '—' },
|
||||||
{ title: '订单状态', dataIndex: ['order', 'status'], width: 100, render: (s) => ORDER_STATUS_LABELS[s] || s },
|
{
|
||||||
|
title: '订单状态',
|
||||||
|
dataIndex: ['order', 'status'],
|
||||||
|
width: 100,
|
||||||
|
render: (s) => ORDER_STATUS_LABELS[s] || s,
|
||||||
|
},
|
||||||
{ title: '收货人', dataIndex: ['order', 'receiverName'], width: 90 },
|
{ title: '收货人', dataIndex: ['order', 'receiverName'], width: 90 },
|
||||||
|
{
|
||||||
|
title: '收货电话',
|
||||||
|
dataIndex: ['order', 'receiverPhone'],
|
||||||
|
width: 120,
|
||||||
|
render: (v) => v || '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '配送地址',
|
||||||
|
key: 'address',
|
||||||
|
width: 280,
|
||||||
|
ellipsis: true,
|
||||||
|
render: (_, row) => formatAddress(row.order),
|
||||||
|
},
|
||||||
{ title: '更新', dataIndex: 'updatedAt', width: 160, render: fmtTime },
|
{ title: '更新', dataIndex: 'updatedAt', width: 160, render: fmtTime },
|
||||||
{
|
{
|
||||||
title: '操作', width: 140,
|
title: '操作', width: 140,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space size={0}>
|
<Space size={0}>
|
||||||
<Button type="link" size="small" onClick={() => openTrack(row)}>路由</Button>
|
<Button type="link" size="small" onClick={() => openTrack(row)}>路由</Button>
|
||||||
<Button type="link" size="small" onClick={async () => {
|
<Button type="link" size="small" onClick={() => void openDetail(row)}>编辑</Button>
|
||||||
const d = await request<Row>(`/admin/deliveries/${row.id}`);
|
|
||||||
setDetail(d);
|
|
||||||
editForm.setFieldsValue({ provider: d.provider, trackingNo: d.trackingNo, providerOrderNo: d.providerOrderNo });
|
|
||||||
setDrawerOpen(true);
|
|
||||||
}}>编辑</Button>
|
|
||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -113,19 +234,21 @@ export default function DeliveriesPage() {
|
|||||||
|
|
||||||
const { columns, settingsButton, settingsModal } = useAdminListColumns('deliveries', baseColumns, { page, pageSize });
|
const { columns, settingsButton, settingsModal } = useAdminListColumns('deliveries', baseColumns, { page, pageSize });
|
||||||
|
|
||||||
|
const order = detail?.order;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{settingsModal}
|
{settingsModal}
|
||||||
<AdminListHeader title="快递/配送单" settings={settingsButton} />
|
<AdminListHeader title="快递/配送单" settings={settingsButton} />
|
||||||
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
|
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
|
||||||
<Form.Item name="orderNo" label="订单号"><Input allowClear /></Form.Item>
|
<Form.Item name="orderNo" label="订单号"><Input allowClear /></Form.Item>
|
||||||
<Form.Item name="provider" label="provider"><Input allowClear placeholder="MOCK" /></Form.Item>
|
<Form.Item name="provider" label="承运商"><Input allowClear placeholder="XFX" /></Form.Item>
|
||||||
<Form.Item name="trackingNo" label="运单号"><Input allowClear /></Form.Item>
|
<Form.Item name="trackingNo" label="运单号"><Input allowClear /></Form.Item>
|
||||||
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 'max-content' }}
|
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 'max-content' }}
|
||||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||||
<Drawer title="配送单编辑" width={480} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
<Drawer title="配送单编辑" width={560} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||||
extra={
|
extra={
|
||||||
<Space>
|
<Space>
|
||||||
<Button onClick={() => setDrawerOpen(false)}>取消</Button>
|
<Button onClick={() => setDrawerOpen(false)}>取消</Button>
|
||||||
@@ -142,14 +265,63 @@ export default function DeliveriesPage() {
|
|||||||
{detail && (
|
{detail && (
|
||||||
<>
|
<>
|
||||||
<Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}>
|
<Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}>
|
||||||
<Descriptions.Item label="订单">{detail.order?.orderNo}</Descriptions.Item>
|
<Descriptions.Item label="订单">{order?.orderNo || '—'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="收货">{detail.order?.receiverName} {detail.order?.receiverPhone}</Descriptions.Item>
|
<Descriptions.Item label="用户">
|
||||||
|
{order?.user ? (
|
||||||
|
<Space size={8} wrap>
|
||||||
|
{order.user.id ? (
|
||||||
|
<AdminPrimaryLink
|
||||||
|
onClick={() => navigate('/users', { state: { openUserId: String(order.user!.id) } })}
|
||||||
|
>
|
||||||
|
{order.user.userNo}
|
||||||
|
</AdminPrimaryLink>
|
||||||
|
) : (
|
||||||
|
order.user.userNo || '—'
|
||||||
|
)}
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
{[order.user.nickname, order.user.phone].filter(Boolean).join(' / ') || ''}
|
||||||
|
</Typography.Text>
|
||||||
|
</Space>
|
||||||
|
) : '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="商品">
|
||||||
|
<Space align="start">
|
||||||
|
{order?.imageResource?.url ? (
|
||||||
|
<img
|
||||||
|
src={order.imageResource.url}
|
||||||
|
alt=""
|
||||||
|
style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 4 }}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<span>
|
||||||
|
{order?.productName || '—'}
|
||||||
|
{order?.productSpec ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
|
||||||
|
{order.productSpec}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
{order?.barcode69 ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
|
||||||
|
{order.barcode69}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
</Space>
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="数量">{formatQty(order)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="配送方式">
|
||||||
|
{DELIVERY_TYPE_LABELS[order?.deliveryType ?? ''] || order?.deliveryType || '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="收货人">
|
||||||
|
{[order?.receiverName, order?.receiverPhone].filter(Boolean).join(' ') || '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="配送地址">{formatAddress(order)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="运费">
|
<Descriptions.Item label="运费">
|
||||||
{detail.logisticsFee == null ? '—' : `¥${Number(detail.logisticsFee).toFixed(2)}`}
|
{detail.logisticsFee == null ? '—' : `¥${Number(detail.logisticsFee).toFixed(2)}`}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
</Descriptions>
|
</Descriptions>
|
||||||
<Form form={editForm} layout="vertical">
|
<Form form={editForm} layout="vertical">
|
||||||
<Form.Item name="provider" label="provider" rules={[{ required: true }]}><Input /></Form.Item>
|
<Form.Item name="provider" label="承运商" rules={[{ required: true }]}><Input /></Form.Item>
|
||||||
<Form.Item name="providerOrderNo" label="第三方单号"><Input /></Form.Item>
|
<Form.Item name="providerOrderNo" label="第三方单号"><Input /></Form.Item>
|
||||||
<Form.Item name="trackingNo" label="运单号"><Input /></Form.Item>
|
<Form.Item name="trackingNo" label="运单号"><Input /></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
Input,
|
Input,
|
||||||
InputNumber,
|
InputNumber,
|
||||||
Modal,
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Table,
|
Table,
|
||||||
@@ -68,7 +69,10 @@ export default function FulfillmentProvidersPage() {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await request<FulfillmentProviderDto[]>('/admin/fulfillment-providers');
|
const res = await request<FulfillmentProviderDto[]>('/admin/fulfillment-providers');
|
||||||
setRows(res);
|
setRows(Array.isArray(res) ? res : []);
|
||||||
|
} catch (e) {
|
||||||
|
setRows([]);
|
||||||
|
message.error(e instanceof Error ? e.message : '加载承运商失败');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -94,6 +98,7 @@ export default function FulfillmentProvidersPage() {
|
|||||||
extraBottleFee: DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
|
extraBottleFee: DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
|
||||||
boxBottles: DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
|
boxBottles: DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
|
||||||
boxFee: DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
|
boxFee: DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
|
||||||
|
deliveryHintHtml: '',
|
||||||
});
|
});
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
}
|
}
|
||||||
@@ -122,6 +127,7 @@ export default function FulfillmentProvidersPage() {
|
|||||||
extraBottleFee: pricing?.extraBottleFee ?? DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
|
extraBottleFee: pricing?.extraBottleFee ?? DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
|
||||||
boxBottles: pricing?.boxBottles ?? DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
|
boxBottles: pricing?.boxBottles ?? DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
|
||||||
boxFee: pricing?.boxFee ?? DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
|
boxFee: pricing?.boxFee ?? DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
|
||||||
|
deliveryHintHtml: row.deliveryHintHtml || '',
|
||||||
});
|
});
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
}
|
}
|
||||||
@@ -144,6 +150,7 @@ export default function FulfillmentProvidersPage() {
|
|||||||
boxBottles: v.boxBottles != null ? Number(v.boxBottles) : undefined,
|
boxBottles: v.boxBottles != null ? Number(v.boxBottles) : undefined,
|
||||||
boxFee: v.boxFee != null ? Number(v.boxFee) : undefined,
|
boxFee: v.boxFee != null ? Number(v.boxFee) : undefined,
|
||||||
},
|
},
|
||||||
|
deliveryHintHtml: v.deliveryHintHtml?.trim() || null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isXfxProviderCode(String(v.code)) && v.type === FulfillmentProviderType.API) {
|
if (isXfxProviderCode(String(v.code)) && v.type === FulfillmentProviderType.API) {
|
||||||
@@ -176,6 +183,16 @@ export default function FulfillmentProvidersPage() {
|
|||||||
void load();
|
void load();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function remove(row: FulfillmentProviderDto) {
|
||||||
|
try {
|
||||||
|
await request(`/admin/fulfillment-providers/${row.id}`, { method: 'DELETE' });
|
||||||
|
message.success('已删除');
|
||||||
|
void load();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const baseColumns: ColumnsType<FulfillmentProviderDto> = [
|
const baseColumns: ColumnsType<FulfillmentProviderDto> = [
|
||||||
{ title: '编码', dataIndex: 'code', width: 100 },
|
{ title: '编码', dataIndex: 'code', width: 100 },
|
||||||
{
|
{
|
||||||
@@ -230,11 +247,23 @@ export default function FulfillmentProvidersPage() {
|
|||||||
{ title: '更新时间', dataIndex: 'updatedAt', width: 170, render: fmtTime },
|
{ title: '更新时间', dataIndex: 'updatedAt', width: 170, render: fmtTime },
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 80,
|
width: 140,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
|
<Space size={0}>
|
||||||
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
||||||
编辑
|
编辑
|
||||||
</Button>
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title={`确认删除承运商「${row.name}」?`}
|
||||||
|
okText="删除"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
onConfirm={() => void remove(row)}
|
||||||
|
>
|
||||||
|
<Button type="link" size="small" danger>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -288,6 +317,17 @@ export default function FulfillmentProvidersPage() {
|
|||||||
<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>
|
||||||
|
<Form.Item
|
||||||
|
name="deliveryHintHtml"
|
||||||
|
label="配送信息提示"
|
||||||
|
extra="C 端同城送展示。支持 HTML:span/p/br/b/strong/i/em/font,style 可用 color、font-weight、font-size、font-style。回车换行会原样显示。空则回退「同城配送,预计24小时内送到」。"
|
||||||
|
>
|
||||||
|
<Input.TextArea
|
||||||
|
rows={3}
|
||||||
|
maxLength={2000}
|
||||||
|
placeholder='<span style="color:#A61D24;font-weight:700;font-size:13px">同城配送,预计24小时内送到</span>'
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
<Divider orientation="left">物流对账</Divider>
|
<Divider orientation="left">物流对账</Divider>
|
||||||
<Form.Item name="settlementMethod" label="结算方式" rules={[{ required: true }]}>
|
<Form.Item name="settlementMethod" label="结算方式" rules={[{ required: true }]}>
|
||||||
|
|||||||
@@ -674,6 +674,13 @@ export default function OrdersPage() {
|
|||||||
width: 90,
|
width: 90,
|
||||||
render: (v: number) => `¥${v}`,
|
render: (v: number) => `¥${v}`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: '运费',
|
||||||
|
key: 'logisticsFee',
|
||||||
|
width: 90,
|
||||||
|
render: (_, row) =>
|
||||||
|
row.delivery?.logisticsFee == null ? '—' : `¥${Number(row.delivery.logisticsFee).toFixed(2)}`,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '好客权益',
|
title: '好客权益',
|
||||||
width: 200,
|
width: 200,
|
||||||
@@ -1158,6 +1165,11 @@ export default function OrdersPage() {
|
|||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="运单号">{detail.delivery.trackingNo || '—'}</Descriptions.Item>
|
<Descriptions.Item label="运单号">{detail.delivery.trackingNo || '—'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="三方单号">{detail.delivery.providerOrderNo || '—'}</Descriptions.Item>
|
<Descriptions.Item label="三方单号">{detail.delivery.providerOrderNo || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="运费">
|
||||||
|
{detail.delivery.logisticsFee == null
|
||||||
|
? '—'
|
||||||
|
: `¥${Number(detail.delivery.logisticsFee).toFixed(2)}`}
|
||||||
|
</Descriptions.Item>
|
||||||
{detail.delivery.manualQueryUrl && (
|
{detail.delivery.manualQueryUrl && (
|
||||||
<Descriptions.Item label="查询链接">
|
<Descriptions.Item label="查询链接">
|
||||||
<a href={detail.delivery.manualQueryUrl} target="_blank" rel="noreferrer">
|
<a href={detail.delivery.manualQueryUrl} target="_blank" rel="noreferrer">
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Navigate, useLocation } from 'react-router-dom';
|
import { Navigate, useLocation } from 'react-router-dom';
|
||||||
import { getStoreProfile, hasShopWxSession } from '../lib/api';
|
import { getStoreProfile, hasShopWxSession } from '../lib/api';
|
||||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||||
|
import { peekShopReturnTo, rememberShopReturnPath } from '../lib/shop-redeem-return';
|
||||||
|
|
||||||
const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
|
const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
|
||||||
const SELECT_STORE_PATH = '/select-store';
|
const SELECT_STORE_PATH = '/select-store';
|
||||||
@@ -18,14 +19,17 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (authenticated && location.pathname === '/login') {
|
if (authenticated && location.pathname === '/login') {
|
||||||
return <Navigate to={needsSelectStore ? SELECT_STORE_PATH : '/'} replace />;
|
const next = needsSelectStore ? SELECT_STORE_PATH : (peekShopReturnTo() || '/');
|
||||||
|
return <Navigate to={next} replace />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authenticated && needsSelectStore && location.pathname !== SELECT_STORE_PATH) {
|
if (authenticated && needsSelectStore && location.pathname !== SELECT_STORE_PATH) {
|
||||||
|
rememberShopReturnPath(location);
|
||||||
return <Navigate to={SELECT_STORE_PATH} replace />;
|
return <Navigate to={SELECT_STORE_PATH} replace />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||||
|
rememberShopReturnPath(location);
|
||||||
const profile = getStoreProfile();
|
const profile = getStoreProfile();
|
||||||
if (profile && hasShopWxSession() && location.pathname !== '/login') {
|
if (profile && hasShopWxSession() && location.pathname !== '/login') {
|
||||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||||
|
|||||||
@@ -1,22 +1 @@
|
|||||||
/** 从微信扫码结果解析核销 token(32 位 hex 或带 token 参数的 URL) */
|
export { parseRedeemTokenFromScan } from '@dukang/shared-types';
|
||||||
export function parseRedeemTokenFromScan(raw: string): string | null {
|
|
||||||
const trimmed = raw.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
|
|
||||||
if (/^[a-f0-9]{32}$/i.test(trimmed)) {
|
|
||||||
return trimmed.toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const url = trimmed.startsWith('http') ? new URL(trimmed) : new URL(trimmed, 'https://local.invalid');
|
|
||||||
const fromQuery = url.searchParams.get('token');
|
|
||||||
if (fromQuery && /^[a-f0-9]{32}$/i.test(fromQuery)) {
|
|
||||||
return fromQuery.toLowerCase();
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
/* not a URL */
|
|
||||||
}
|
|
||||||
|
|
||||||
const hexMatch = trimmed.match(/[a-f0-9]{32}/i);
|
|
||||||
return hexMatch ? hexMatch[0].toLowerCase() : null;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { hardNavigateInWechat, shouldHardNavigateForJssdk } from '@dukang/weixin-sdk';
|
||||||
|
|
||||||
|
/** iOS 微信内用整页跳转,避免 JSSDK 入场 URL 与 SPA 路径不一致 */
|
||||||
|
export function goShopPath(
|
||||||
|
path: string,
|
||||||
|
navigate: (path: string, opts?: { replace?: boolean }) => void,
|
||||||
|
opts?: { replace?: boolean },
|
||||||
|
): void {
|
||||||
|
if (shouldHardNavigateForJssdk()) {
|
||||||
|
hardNavigateInWechat(path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
navigate(path, { replace: opts?.replace ?? true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/** 扫核销码落地 /redeem?token= 后未登录或需选店,记下回跳路径(OAuth 整页跳转会丢掉 location.state) */
|
||||||
|
export const SHOP_REDEEM_RETURN_KEY = 'shop_redeem_return';
|
||||||
|
|
||||||
|
function isRedeemReturnPath(path: string): boolean {
|
||||||
|
if (!path.startsWith('/redeem')) return false;
|
||||||
|
if (path.startsWith('/redeem/')) return false;
|
||||||
|
try {
|
||||||
|
const url = new URL(path, 'https://local.invalid');
|
||||||
|
return !!url.searchParams.get('token')?.trim();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberShopReturnTo(path: string): void {
|
||||||
|
if (!isRedeemReturnPath(path)) return;
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(SHOP_REDEEM_RETURN_KEY, path);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberShopReturnPath(location: { pathname: string; search: string }): void {
|
||||||
|
rememberShopReturnTo(`${location.pathname}${location.search}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function peekShopReturnTo(): string | null {
|
||||||
|
try {
|
||||||
|
const path = sessionStorage.getItem(SHOP_REDEEM_RETURN_KEY);
|
||||||
|
return path && isRedeemReturnPath(path) ? path : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function consumeShopReturnTo(): string | null {
|
||||||
|
const path = peekShopReturnTo();
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem(SHOP_REDEEM_RETURN_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { useNavigate, useSearchParams } from 'react-router-dom';
|
|||||||
import WeakNetFallbackPanel from '../components/WeakNetFallbackPanel';
|
import WeakNetFallbackPanel from '../components/WeakNetFallbackPanel';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { reportRedeemFailure } from '../lib/redeem-failure';
|
import { reportRedeemFailure } from '../lib/redeem-failure';
|
||||||
|
import { consumeShopReturnTo } from '../lib/shop-redeem-return';
|
||||||
import { toastError } from '../lib/toast';
|
import { toastError } from '../lib/toast';
|
||||||
import { useStorePageView } from '../lib/usePageView';
|
import { useStorePageView } from '../lib/usePageView';
|
||||||
|
|
||||||
@@ -47,6 +48,7 @@ export default function RedeemConfirmPage() {
|
|||||||
navigate('/', { replace: true });
|
navigate('/', { replace: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
consumeShopReturnTo();
|
||||||
setToken(scanned);
|
setToken(scanned);
|
||||||
}, [searchParams, navigate]);
|
}, [searchParams, navigate]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useMemo } from 'react';
|
import { useEffect, useMemo } from 'react';
|
||||||
import { useLocation, useNavigate } from 'react-router-dom';
|
import { useLocation, useNavigate } from 'react-router-dom';
|
||||||
|
import { goShopPath } from '../lib/shop-nav';
|
||||||
import { notifyRedeemSuccess } from '../lib/useRedeemSuccessBus';
|
import { notifyRedeemSuccess } from '../lib/useRedeemSuccessBus';
|
||||||
import { formatMoney, toMoneyNumber } from '../lib/money';
|
import { formatMoney, toMoneyNumber } from '../lib/money';
|
||||||
|
|
||||||
@@ -35,10 +36,12 @@ export default function RedeemSuccessPage() {
|
|||||||
});
|
});
|
||||||
}, [redeemNo, amount]);
|
}, [redeemNo, amount]);
|
||||||
|
|
||||||
|
const goHome = () => goShopPath('/', navigate, { replace: true });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="shop-success-page">
|
<div className="shop-success-page">
|
||||||
<header className="shop-success-header">
|
<header className="shop-success-header">
|
||||||
<button type="button" className="shop-redeem-back" onClick={() => navigate('/')} aria-label="返回">
|
<button type="button" className="shop-redeem-back" onClick={goHome} aria-label="返回">
|
||||||
<span className="material-symbols-outlined">arrow_back</span>
|
<span className="material-symbols-outlined">arrow_back</span>
|
||||||
</button>
|
</button>
|
||||||
<h1 className="app-page-title">杜康好客</h1>
|
<h1 className="app-page-title">杜康好客</h1>
|
||||||
@@ -85,11 +88,11 @@ export default function RedeemSuccessPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="shop-success-actions">
|
<div className="shop-success-actions">
|
||||||
<button type="button" className="shop-success-primary-btn" onClick={() => navigate('/')}>
|
<button type="button" className="shop-success-primary-btn" onClick={goHome}>
|
||||||
<span>继续核销</span>
|
<span>继续核销</span>
|
||||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>qr_code_scanner</span>
|
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>qr_code_scanner</span>
|
||||||
</button>
|
</button>
|
||||||
<button type="button" className="shop-success-outline-btn" onClick={() => navigate('/')}>
|
<button type="button" className="shop-success-outline-btn" onClick={goHome}>
|
||||||
<span>返回首页</span>
|
<span>返回首页</span>
|
||||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>home</span>
|
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>home</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||||
import { hardNavigateInWechat, shouldHardNavigateForJssdk } from '@dukang/weixin-sdk';
|
|
||||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||||
import {
|
import {
|
||||||
needsStoreSelection,
|
needsStoreSelection,
|
||||||
@@ -10,13 +9,11 @@ import {
|
|||||||
type ShopSessionPayload,
|
type ShopSessionPayload,
|
||||||
type ShopStoreOption,
|
type ShopStoreOption,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
|
import { goShopPath } from '../lib/shop-nav';
|
||||||
|
import { consumeShopReturnTo, peekShopReturnTo } from '../lib/shop-redeem-return';
|
||||||
|
|
||||||
function goShopHome(navigate: (path: string, opts?: { replace?: boolean }) => void) {
|
function goAfterSelectStore(navigate: (path: string, opts?: { replace?: boolean }) => void) {
|
||||||
if (shouldHardNavigateForJssdk()) {
|
goShopPath(consumeShopReturnTo() || '/', navigate);
|
||||||
hardNavigateInWechat('/');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
navigate('/', { replace: true });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function SelectStorePage() {
|
export default function SelectStorePage() {
|
||||||
@@ -46,7 +43,7 @@ export default function SelectStorePage() {
|
|||||||
async function onSelect(storeId: string) {
|
async function onSelect(storeId: string) {
|
||||||
if (loadingId) return;
|
if (loadingId) return;
|
||||||
if (storeId === currentStoreId) {
|
if (storeId === currentStoreId) {
|
||||||
goShopHome(navigate);
|
goAfterSelectStore(navigate);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setLoadingId(storeId);
|
setLoadingId(storeId);
|
||||||
@@ -54,7 +51,7 @@ export default function SelectStorePage() {
|
|||||||
try {
|
try {
|
||||||
const session = await selectStore(storeId);
|
const session = await selectStore(storeId);
|
||||||
applySession(session);
|
applySession(session);
|
||||||
goShopHome(navigate);
|
goAfterSelectStore(navigate);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setMsg(e instanceof Error ? e.message : '选店失败');
|
setMsg(e instanceof Error ? e.message : '选店失败');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -170,16 +167,14 @@ export default function SelectStorePage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** After login/wechat: route to select-store or home */
|
/** After login/wechat: route to select-store, redeem return, or home */
|
||||||
export function routeAfterShopLogin(
|
export function routeAfterShopLogin(
|
||||||
session: ShopSessionPayload,
|
session: ShopSessionPayload,
|
||||||
navigate: (path: string, opts?: { replace?: boolean }) => void,
|
navigate: (path: string, opts?: { replace?: boolean }) => void,
|
||||||
) {
|
) {
|
||||||
const path = needsStoreSelection(session) ? '/select-store' : '/';
|
if (needsStoreSelection(session)) {
|
||||||
// iOS 微信:必须整页跳转,让业务页成为 JSSDK 新入场 URL,否则扫码验签必挂
|
goShopPath('/select-store', navigate);
|
||||||
if (shouldHardNavigateForJssdk()) {
|
|
||||||
hardNavigateInWechat(path);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
navigate(path, { replace: true });
|
goShopPath(peekShopReturnTo() || '/', navigate);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@dukang/mini-user",
|
"name": "@dukang/mini-user",
|
||||||
"version": "3.5.4",
|
"version": "3.5.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
import { Button, Text } from '@tarojs/components';
|
import { Button, Text } from '@tarojs/components';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
|
import { toast } from '../lib/api';
|
||||||
|
import { getBrandAssetsSync, loadBrandAssets } from '../lib/brand-assets';
|
||||||
|
import { openWecomCustomerServiceChat } from '../lib/wecom-cs';
|
||||||
|
|
||||||
export type ContactCsSessionContext = {
|
export type ContactCsSessionContext = {
|
||||||
orderId?: string;
|
orderId?: string;
|
||||||
@@ -16,7 +20,7 @@ type ContactCsButtonProps = {
|
|||||||
|
|
||||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||||
|
|
||||||
/** 组装 session-from(微信限制约 1000 字符) */
|
/** 组装 session-from(微信限制约 1000 字符;原生小程序客服兜底用) */
|
||||||
export function buildCsSessionFrom(session?: ContactCsSessionContext): string {
|
export function buildCsSessionFrom(session?: ContactCsSessionContext): string {
|
||||||
if (!session) return 'dukang|from=mini-user';
|
if (!session) return 'dukang|from=mini-user';
|
||||||
const parts = ['dukang'];
|
const parts = ['dukang'];
|
||||||
@@ -26,16 +30,59 @@ export function buildCsSessionFrom(session?: ContactCsSessionContext): string {
|
|||||||
return parts.join('|');
|
return parts.join('|');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function canOpenWecom(url: string, corpId: string) {
|
||||||
|
return !!url.trim() && !!corpId.trim();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 微信小程序客服入口(open-type=contact)。
|
* C 端在线客服:
|
||||||
* 非 weapp 环境不渲染,由调用方走电话等兜底。
|
* - weapp 且已配置 CorpID + kfid:调起企业微信「微信客服」
|
||||||
|
* - weapp 未配 CorpID:回退 open-type=contact
|
||||||
|
* - H5:有 kfid 则打开企微客服链接
|
||||||
*/
|
*/
|
||||||
export default function ContactCsButton({
|
export default function ContactCsButton({
|
||||||
className = '',
|
className = '',
|
||||||
children = '联系在线客服',
|
children = '联系在线客服',
|
||||||
session,
|
session,
|
||||||
}: ContactCsButtonProps) {
|
}: ContactCsButtonProps) {
|
||||||
if (!isWeapp) return null;
|
const [cs, setCs] = useState(() => getBrandAssetsSync());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadBrandAssets().then(setCs);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const wecomChatReady = canOpenWecom(cs.customerServiceWecomUrl, cs.wecomCorpId);
|
||||||
|
const wecomWebReady = !!cs.customerServiceWecomUrl.trim();
|
||||||
|
|
||||||
|
if (!isWeapp && !wecomWebReady) return null;
|
||||||
|
|
||||||
|
async function openWecom() {
|
||||||
|
try {
|
||||||
|
if (isWeapp && wecomChatReady) {
|
||||||
|
await openWecomCustomerServiceChat({
|
||||||
|
url: cs.customerServiceWecomUrl,
|
||||||
|
corpId: cs.wecomCorpId,
|
||||||
|
session,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typeof window !== 'undefined' && cs.customerServiceWecomUrl) {
|
||||||
|
window.location.href = cs.customerServiceWecomUrl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast('请在微信内打开后联系客服');
|
||||||
|
} catch (e) {
|
||||||
|
toast(e instanceof Error ? e.message : '无法打开客服');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wecomChatReady || (!isWeapp && wecomWebReady)) {
|
||||||
|
return (
|
||||||
|
<Button className={className} hoverClass="none" onClick={() => void openWecom()}>
|
||||||
|
{typeof children === 'string' ? <Text>{children}</Text> : children}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { RichText, Text } from '@tarojs/components';
|
||||||
|
import { deliveryHintHtmlToRichNodes } from '@dukang/shared-types';
|
||||||
|
import { DEFAULT_LOCAL_DELIVERY_HINT } from '../lib/local-delivery';
|
||||||
|
|
||||||
|
type DeliveryHintHtmlProps = {
|
||||||
|
html?: string | null;
|
||||||
|
className?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 承运商配送提示:HTML 用 RichText;textarea 里的换行转成 br */
|
||||||
|
export default function DeliveryHintHtml({
|
||||||
|
html,
|
||||||
|
className = '',
|
||||||
|
}: DeliveryHintHtmlProps) {
|
||||||
|
const raw = (html || '').trim() || DEFAULT_LOCAL_DELIVERY_HINT;
|
||||||
|
const nodes = deliveryHintHtmlToRichNodes(raw);
|
||||||
|
const looksHtml = /<[a-z][\s\S]*>/i.test(nodes);
|
||||||
|
if (!looksHtml) {
|
||||||
|
return <Text className={className}>{nodes}</Text>;
|
||||||
|
}
|
||||||
|
return <RichText className={className} nodes={nodes} />;
|
||||||
|
}
|
||||||
@@ -10,10 +10,11 @@ import {
|
|||||||
const CANVAS_ID = 'redeem-qr-canvas';
|
const CANVAS_ID = 'redeem-qr-canvas';
|
||||||
|
|
||||||
type RedeemQrCodeProps = {
|
type RedeemQrCodeProps = {
|
||||||
token: string;
|
/** 二维码内容:门店 H5 落地 URL,缺省回退 token */
|
||||||
|
payload: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function drawOnWeappCanvas(token: string) {
|
function drawOnWeappCanvas(payload: string) {
|
||||||
const page = Taro.getCurrentInstance().page;
|
const page = Taro.getCurrentInstance().page;
|
||||||
const query = page ? Taro.createSelectorQuery().in(page) : Taro.createSelectorQuery();
|
const query = page ? Taro.createSelectorQuery().in(page) : Taro.createSelectorQuery();
|
||||||
query
|
query
|
||||||
@@ -33,33 +34,33 @@ function drawOnWeappCanvas(token: string) {
|
|||||||
canvas.width = layoutW * dpr;
|
canvas.width = layoutW * dpr;
|
||||||
canvas.height = layoutH * dpr;
|
canvas.height = layoutH * dpr;
|
||||||
ctx.scale(dpr, dpr);
|
ctx.scale(dpr, dpr);
|
||||||
drawRedeemQrOnCanvas(ctx, token, drawSize);
|
drawRedeemQrOnCanvas(ctx, payload, drawSize);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function RedeemQrCode({ token }: RedeemQrCodeProps) {
|
export default function RedeemQrCode({ payload }: RedeemQrCodeProps) {
|
||||||
const [imgSrc, setImgSrc] = useState('');
|
const [imgSrc, setImgSrc] = useState('');
|
||||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!token) {
|
if (!payload) {
|
||||||
setImgSrc('');
|
setImgSrc('');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isWeapp) {
|
if (isWeapp) {
|
||||||
const timer = setTimeout(() => drawOnWeappCanvas(token), 120);
|
const timer = setTimeout(() => drawOnWeappCanvas(payload), 120);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void buildRedeemQrDataUrl(token).then((url) => {
|
void buildRedeemQrDataUrl(payload).then((url) => {
|
||||||
if (!cancelled) setImgSrc(url);
|
if (!cancelled) setImgSrc(url);
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [token, isWeapp]);
|
}, [payload, isWeapp]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View className="redeem-qr-box">
|
<View className="redeem-qr-box">
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
BRAND_LOGO_URL,
|
BRAND_LOGO_URL,
|
||||||
BRAND_LOGO_WIDE_URL,
|
BRAND_LOGO_WIDE_URL,
|
||||||
CUSTOMER_SERVICE_PHONE,
|
CUSTOMER_SERVICE_PHONE,
|
||||||
|
CUSTOMER_SERVICE_WECOM_URL,
|
||||||
QUALIFICATION_DISCLOSURE_URL,
|
QUALIFICATION_DISCLOSURE_URL,
|
||||||
type ClientRuntimeConfig,
|
type ClientRuntimeConfig,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -14,6 +15,8 @@ export type BrandAssets = {
|
|||||||
brandLogoMarkUrl: string;
|
brandLogoMarkUrl: string;
|
||||||
qualificationDisclosureUrl: string;
|
qualificationDisclosureUrl: string;
|
||||||
customerServicePhone: string;
|
customerServicePhone: string;
|
||||||
|
customerServiceWecomUrl: string;
|
||||||
|
wecomCorpId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const FALLBACK: BrandAssets = {
|
const FALLBACK: BrandAssets = {
|
||||||
@@ -22,6 +25,8 @@ const FALLBACK: BrandAssets = {
|
|||||||
brandLogoMarkUrl: BRAND_LOGO_MARK_URL,
|
brandLogoMarkUrl: BRAND_LOGO_MARK_URL,
|
||||||
qualificationDisclosureUrl: QUALIFICATION_DISCLOSURE_URL,
|
qualificationDisclosureUrl: QUALIFICATION_DISCLOSURE_URL,
|
||||||
customerServicePhone: CUSTOMER_SERVICE_PHONE,
|
customerServicePhone: CUSTOMER_SERVICE_PHONE,
|
||||||
|
customerServiceWecomUrl: CUSTOMER_SERVICE_WECOM_URL,
|
||||||
|
wecomCorpId: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
let cached: BrandAssets | null = null;
|
let cached: BrandAssets | null = null;
|
||||||
@@ -35,6 +40,9 @@ function fromConfig(config: ClientRuntimeConfig | null | undefined): BrandAssets
|
|||||||
qualificationDisclosureUrl:
|
qualificationDisclosureUrl:
|
||||||
config?.qualificationDisclosureUrl?.trim() || FALLBACK.qualificationDisclosureUrl,
|
config?.qualificationDisclosureUrl?.trim() || FALLBACK.qualificationDisclosureUrl,
|
||||||
customerServicePhone: config?.customerServicePhone?.trim() || FALLBACK.customerServicePhone,
|
customerServicePhone: config?.customerServicePhone?.trim() || FALLBACK.customerServicePhone,
|
||||||
|
customerServiceWecomUrl:
|
||||||
|
config?.customerServiceWecomUrl?.trim() || FALLBACK.customerServiceWecomUrl,
|
||||||
|
wecomCorpId: config?.wecomCorpId?.trim() || FALLBACK.wecomCorpId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import Taro from '@tarojs/taro';
|
|||||||
import { fetchClientConfig } from './pay-wechat';
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
|
|
||||||
/** 与 package.json version 同步,供服务端 minClientVersion 比对 */
|
/** 与 package.json version 同步,供服务端 minClientVersion 比对 */
|
||||||
export const APP_VERSION = '3.5.4';
|
export const APP_VERSION = '3.5.10';
|
||||||
|
|
||||||
export const APP_VERSION_LABEL = `v${APP_VERSION}`;
|
export const APP_VERSION_LABEL = `v${APP_VERSION}`;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import type { LocalDeliveryDto } from '@dukang/shared-types';
|
||||||
|
import { DEFAULT_LOCAL_DELIVERY_HINT } from '@dukang/shared-types';
|
||||||
|
import { request } from './api';
|
||||||
|
|
||||||
|
export { DEFAULT_LOCAL_DELIVERY_HINT };
|
||||||
|
|
||||||
|
const CACHE_TTL_MS = 60_000;
|
||||||
|
let cached: LocalDeliveryDto[] | null = null;
|
||||||
|
let cachedAt = 0;
|
||||||
|
let inflight: Promise<LocalDeliveryDto[]> | null = null;
|
||||||
|
|
||||||
|
function cityAliases(name: string): string[] {
|
||||||
|
const raw = name.trim();
|
||||||
|
if (!raw) return [];
|
||||||
|
const noSuffix = raw.replace(/市$/, '');
|
||||||
|
const withSuffix = raw.endsWith('市') ? raw : `${raw}市`;
|
||||||
|
return [raw, noSuffix, withSuffix];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadLocalDeliveries(force = false): Promise<LocalDeliveryDto[]> {
|
||||||
|
if (!force && cached && Date.now() - cachedAt < CACHE_TTL_MS) return cached;
|
||||||
|
if (!force && inflight) return inflight;
|
||||||
|
inflight = request<LocalDeliveryDto[]>('/catalog/local-deliveries')
|
||||||
|
.then((list) => {
|
||||||
|
cached = Array.isArray(list) ? list : [];
|
||||||
|
cachedAt = Date.now();
|
||||||
|
return cached;
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
cached = cached ?? [];
|
||||||
|
return cached;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
inflight = null;
|
||||||
|
});
|
||||||
|
return inflight;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchLocalDelivery(
|
||||||
|
list: LocalDeliveryDto[],
|
||||||
|
opts: { cityCode?: string | null; cityName?: string | null },
|
||||||
|
): LocalDeliveryDto | null {
|
||||||
|
const code = String(opts.cityCode || '').trim();
|
||||||
|
if (code) {
|
||||||
|
const byCode = list.find((row) => row.city.code === code);
|
||||||
|
if (byCode) return byCode;
|
||||||
|
}
|
||||||
|
const names = new Set(cityAliases(String(opts.cityName || '')));
|
||||||
|
if (!names.size) return null;
|
||||||
|
return list.find((row) => cityAliases(row.city.name).some((n) => names.has(n))) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveLocalDeliveryHintHtml(row: LocalDeliveryDto | null): string {
|
||||||
|
const html = row?.hintHtml?.trim();
|
||||||
|
if (html) return html;
|
||||||
|
return DEFAULT_LOCAL_DELIVERY_HINT;
|
||||||
|
}
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
import { DEFAULT_LOCAL_DELIVERY_HINT } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
/** @deprecated 使用 DEFAULT_LOCAL_DELIVERY_HINT;空配置回退 */
|
||||||
|
export const LOCAL_DELIVERY_ETA_HINT = DEFAULT_LOCAL_DELIVERY_HINT;
|
||||||
|
|
||||||
/** 商品履约能力(与 HQ / 交易硬闸一致) */
|
/** 商品履约能力(与 HQ / 交易硬闸一致) */
|
||||||
|
|
||||||
export type FulfillmentFlags = {
|
export type FulfillmentFlags = {
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ const QR_OPTIONS = {
|
|||||||
color: { dark: '#1f1a17', light: '#ffffff' },
|
color: { dark: '#1f1a17', light: '#ffffff' },
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** 在 2d Canvas 上绘制二维码(小程序 / H5 通用) */
|
/** 在 2d Canvas 上绘制二维码(小程序 / H5 通用;payload 为落地 URL 或纯 token) */
|
||||||
export function drawRedeemQrOnCanvas(
|
export function drawRedeemQrOnCanvas(
|
||||||
ctx: CanvasRenderingContext2D,
|
ctx: CanvasRenderingContext2D,
|
||||||
token: string,
|
payload: string,
|
||||||
sizePx = QR_SIZE,
|
sizePx = QR_SIZE,
|
||||||
) {
|
) {
|
||||||
const qr = QRCode.create(token, { errorCorrectionLevel: 'M' });
|
const qr = QRCode.create(payload, { errorCorrectionLevel: 'M' });
|
||||||
const count = qr.modules.size;
|
const count = qr.modules.size;
|
||||||
const cell = sizePx / count;
|
const cell = sizePx / count;
|
||||||
|
|
||||||
@@ -31,11 +31,11 @@ export function drawRedeemQrOnCanvas(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** H5:Data URL;失败时回退到与 h5-user 相同的外部 QR 服务 */
|
/** H5:Data URL;失败时回退到与 h5-user 相同的外部 QR 服务 */
|
||||||
export async function buildRedeemQrDataUrl(token: string): Promise<string> {
|
export async function buildRedeemQrDataUrl(payload: string): Promise<string> {
|
||||||
try {
|
try {
|
||||||
return await QRCode.toDataURL(token, QR_OPTIONS);
|
return await QRCode.toDataURL(payload, QR_OPTIONS);
|
||||||
} catch {
|
} catch {
|
||||||
return `https://api.qrserver.com/v1/create-qr-code/?size=${QR_SIZE * 2}x${QR_SIZE * 2}&data=${encodeURIComponent(token)}`;
|
return `https://api.qrserver.com/v1/create-qr-code/?size=${QR_SIZE * 2}x${QR_SIZE * 2}&data=${encodeURIComponent(payload)}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
|
||||||
|
export type WecomCsSessionContext = {
|
||||||
|
orderId?: string;
|
||||||
|
orderNo?: string;
|
||||||
|
from?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OpenCsChatOption = {
|
||||||
|
extInfo: { url: string };
|
||||||
|
corpId: string;
|
||||||
|
showMessageCard?: boolean;
|
||||||
|
sendMessageTitle?: string;
|
||||||
|
sendMessagePath?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OpenCsChatFn = (option: OpenCsChatOption) => Promise<unknown>;
|
||||||
|
|
||||||
|
function getTaroOpenCsChat(): OpenCsChatFn | null {
|
||||||
|
const api = (Taro as unknown as { openCustomerServiceChat?: OpenCsChatFn }).openCustomerServiceChat;
|
||||||
|
return typeof api === 'function' ? api : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getWxOpenCsChat(): ((option: OpenCsChatOption & {
|
||||||
|
success?: () => void;
|
||||||
|
fail?: (err: { errMsg?: string }) => void;
|
||||||
|
}) => void) | null {
|
||||||
|
const wxApi = (
|
||||||
|
globalThis as {
|
||||||
|
wx?: {
|
||||||
|
openCustomerServiceChat?: (option: OpenCsChatOption & {
|
||||||
|
success?: () => void;
|
||||||
|
fail?: (err: { errMsg?: string }) => void;
|
||||||
|
}) => void;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
).wx?.openCustomerServiceChat;
|
||||||
|
return typeof wxApi === 'function' ? wxApi : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 小程序调起企业微信「微信客服」会话 */
|
||||||
|
export async function openWecomCustomerServiceChat(params: {
|
||||||
|
url: string;
|
||||||
|
corpId: string;
|
||||||
|
session?: WecomCsSessionContext;
|
||||||
|
}): Promise<void> {
|
||||||
|
const url = params.url.trim();
|
||||||
|
const corpId = params.corpId.trim();
|
||||||
|
if (!url || !corpId) {
|
||||||
|
throw new Error('企微客服未配置');
|
||||||
|
}
|
||||||
|
|
||||||
|
const option: OpenCsChatOption = {
|
||||||
|
extInfo: { url },
|
||||||
|
corpId,
|
||||||
|
};
|
||||||
|
if (params.session?.orderNo || params.session?.orderId) {
|
||||||
|
option.showMessageCard = true;
|
||||||
|
option.sendMessageTitle = params.session.orderNo
|
||||||
|
? `订单 ${params.session.orderNo}`
|
||||||
|
: '订单咨询';
|
||||||
|
if (params.session.orderId) {
|
||||||
|
option.sendMessagePath = `pages/order-detail/index?id=${params.session.orderId}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const taroApi = getTaroOpenCsChat();
|
||||||
|
if (taroApi) {
|
||||||
|
await taroApi(option);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const wxApi = getWxOpenCsChat();
|
||||||
|
if (!wxApi) {
|
||||||
|
throw new Error('当前微信版本不支持企业微信客服');
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
wxApi({
|
||||||
|
...option,
|
||||||
|
success: () => resolve(),
|
||||||
|
fail: (err) => reject(new Error(err?.errMsg || '无法打开企业微信客服')),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -16,35 +16,43 @@ function dialPhone(phone: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function CustomerServicePage() {
|
export default function CustomerServicePage() {
|
||||||
const [phone, setPhone] = useState(() => getBrandAssetsSync().customerServicePhone);
|
const [brand, setBrand] = useState(() => getBrandAssetsSync());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void loadBrandAssets().then((b) => setPhone(b.customerServicePhone));
|
void loadBrandAssets().then(setBrand);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const phone = brand.customerServicePhone;
|
||||||
|
const wecomReady = !!brand.customerServiceWecomUrl.trim() && !!brand.wecomCorpId.trim();
|
||||||
|
const wecomUrlReady = !!brand.customerServiceWecomUrl.trim();
|
||||||
|
|
||||||
|
const hint = isWeapp
|
||||||
|
? wecomReady
|
||||||
|
? '点击下方按钮,进入企业微信客服会话'
|
||||||
|
: '点击下方按钮,进入在线客服会话'
|
||||||
|
: wecomUrlReady
|
||||||
|
? '点击下方按钮进入企业微信客服,或拨打客服电话'
|
||||||
|
: '请在微信小程序内打开以使用在线客服,或拨打客服电话';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="sub" className="cs-page">
|
<PageShell variant="sub" className="cs-page">
|
||||||
<SubPageHeader title="联系客服" />
|
<SubPageHeader title="联系客服" />
|
||||||
<View className="sub-page-body inset-page cs-body">
|
<View className="sub-page-body inset-page cs-body">
|
||||||
<Text className="cs-brand">杜康好客客服</Text>
|
<Text className="cs-brand">杜康好客客服</Text>
|
||||||
<Text className="cs-hint">
|
<Text className="cs-hint">{hint}</Text>
|
||||||
{isWeapp
|
|
||||||
? '点击下方按钮,进入小程序在线客服会话'
|
|
||||||
: '请在微信小程序内打开以使用在线客服,或拨打客服电话'}
|
|
||||||
</Text>
|
|
||||||
<Text className="cs-hours">工作时间:9:00 - 21:00</Text>
|
<Text className="cs-hours">工作时间:9:00 - 21:00</Text>
|
||||||
|
|
||||||
{isWeapp ? (
|
{isWeapp || wecomUrlReady ? (
|
||||||
<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(phone)}>
|
<View className={isWeapp || wecomUrlReady ? 'cs-phone-link' : 'cs-call-btn'} onClick={() => dialPhone(phone)}>
|
||||||
<Text>
|
<Text>
|
||||||
{isWeapp ? `或拨打客服电话 ${phone}` : '拨打客服电话'}
|
{isWeapp || wecomUrlReady ? `或拨打客服电话 ${phone}` : '拨打客服电话'}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{!isWeapp ? (
|
{!isWeapp && !wecomUrlReady ? (
|
||||||
<Text className="cs-phone-display">{phone}</Text>
|
<Text className="cs-phone-display">{phone}</Text>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import { maskPhone } from '../../lib/phone';
|
|||||||
import { ensurePayReady } from '../../lib/pay-ready';
|
import { ensurePayReady } from '../../lib/pay-ready';
|
||||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import DeliveryHintHtml from '../../components/DeliveryHintHtml';
|
||||||
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
||||||
|
import { loadLocalDeliveries, matchLocalDelivery, resolveLocalDeliveryHintHtml } from '../../lib/local-delivery';
|
||||||
import { getProductMainImage } from '../../lib/product-images';
|
import { getProductMainImage } from '../../lib/product-images';
|
||||||
import BenefitFigure from '../../components/BenefitFigure';
|
import BenefitFigure from '../../components/BenefitFigure';
|
||||||
|
|
||||||
@@ -75,6 +77,7 @@ export default function OrderConfirmPage() {
|
|||||||
const [addresses, setAddresses] = useState<Address[]>([]);
|
const [addresses, setAddresses] = useState<Address[]>([]);
|
||||||
const [addressId, setAddressId] = useState(checkoutCtx.addressId || '');
|
const [addressId, setAddressId] = useState(checkoutCtx.addressId || '');
|
||||||
const [preview, setPreview] = useState<OrderPreview | null>(null);
|
const [preview, setPreview] = useState<OrderPreview | null>(null);
|
||||||
|
const [localHintHtml, setLocalHintHtml] = useState('');
|
||||||
const [previewLoading, setPreviewLoading] = useState(false);
|
const [previewLoading, setPreviewLoading] = useState(false);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [msg, setMsg] = useState('');
|
const [msg, setMsg] = useState('');
|
||||||
@@ -151,6 +154,18 @@ export default function OrderConfirmPage() {
|
|||||||
[addresses, addressId],
|
[addresses, addressId],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const cityName = selectedAddress?.city;
|
||||||
|
if (!cityName) {
|
||||||
|
setLocalHintHtml('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void loadLocalDeliveries().then((list) => {
|
||||||
|
const row = matchLocalDelivery(list, { cityName });
|
||||||
|
setLocalHintHtml(row ? resolveLocalDeliveryHintHtml(row) : '');
|
||||||
|
});
|
||||||
|
}, [selectedAddress?.city]);
|
||||||
|
|
||||||
const allowCross =
|
const allowCross =
|
||||||
preview?.allowCrossCityDelivery !== undefined
|
preview?.allowCrossCityDelivery !== undefined
|
||||||
? canCrossCity({ allowCrossCityDelivery: preview.allowCrossCityDelivery })
|
? canCrossCity({ allowCrossCityDelivery: preview.allowCrossCityDelivery })
|
||||||
@@ -339,6 +354,12 @@ export default function OrderConfirmPage() {
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{!isCross && addressOk && addressId && localHintHtml ? (
|
||||||
|
<View className="order-card">
|
||||||
|
<DeliveryHintHtml className="u-muted" html={localHintHtml} />
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{preview ? (
|
{preview ? (
|
||||||
<>
|
<>
|
||||||
<View className="order-card">
|
<View className="order-card">
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import ContactCsButton from '../../components/ContactCsButton';
|
|||||||
import LogisticsRichText from '../../components/LogisticsRichText';
|
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 DeliveryHintHtml from '../../components/DeliveryHintHtml';
|
||||||
|
import { loadLocalDeliveries, matchLocalDelivery, resolveLocalDeliveryHintHtml } from '../../lib/local-delivery';
|
||||||
import {
|
import {
|
||||||
formatEstimatedArrival,
|
formatEstimatedArrival,
|
||||||
isLogisticsNotArrived,
|
isLogisticsNotArrived,
|
||||||
@@ -83,6 +85,22 @@ const STATUS_LABELS: Record<string, string> = {
|
|||||||
REFUNDED: '已退款',
|
REFUNDED: '已退款',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function applyLocalDeliveryHint(
|
||||||
|
data: OrderDetail,
|
||||||
|
setLocalHintHtml: (html: string) => void,
|
||||||
|
) {
|
||||||
|
if (data.deliveryType !== 'LOCAL') {
|
||||||
|
setLocalHintHtml('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void loadLocalDeliveries().then((list) => {
|
||||||
|
const row = data.receiverCity
|
||||||
|
? matchLocalDelivery(list, { cityName: data.receiverCity })
|
||||||
|
: null;
|
||||||
|
setLocalHintHtml(resolveLocalDeliveryHintHtml(row));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function fullReceiverAddress(order: OrderDetail) {
|
function fullReceiverAddress(order: OrderDetail) {
|
||||||
const detail = (order.receiverAddress || '').trim();
|
const detail = (order.receiverAddress || '').trim();
|
||||||
const region = [order.receiverProvince, order.receiverCity, order.receiverDistrict]
|
const region = [order.receiverProvince, order.receiverCity, order.receiverDistrict]
|
||||||
@@ -102,6 +120,7 @@ export default function OrderDetailPage() {
|
|||||||
const [latestTrack, setLatestTrack] = useState<OrderTrackNode | null>(null);
|
const [latestTrack, setLatestTrack] = useState<OrderTrackNode | null>(null);
|
||||||
const [estimatedArrival, setEstimatedArrival] = useState<OrderTrackEstimatedArrival | null>(null);
|
const [estimatedArrival, setEstimatedArrival] = useState<OrderTrackEstimatedArrival | null>(null);
|
||||||
const [trackLoading, setTrackLoading] = useState(false);
|
const [trackLoading, setTrackLoading] = useState(false);
|
||||||
|
const [localHintHtml, setLocalHintHtml] = useState('');
|
||||||
|
|
||||||
async function loadOrderTrack(delivery: OrderDetail['delivery'], orderStatus?: string) {
|
async function loadOrderTrack(delivery: OrderDetail['delivery'], orderStatus?: string) {
|
||||||
if (!orderId || !shouldLoadOrderTrack(delivery)) {
|
if (!orderId || !shouldLoadOrderTrack(delivery)) {
|
||||||
@@ -133,6 +152,7 @@ export default function OrderDetailPage() {
|
|||||||
.then((data) => {
|
.then((data) => {
|
||||||
setOrder(data);
|
setOrder(data);
|
||||||
void loadOrderTrack(data.delivery, data.status);
|
void loadOrderTrack(data.delivery, data.status);
|
||||||
|
applyLocalDeliveryHint(data, setLocalHintHtml);
|
||||||
})
|
})
|
||||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||||
}, [orderId]);
|
}, [orderId]);
|
||||||
@@ -144,6 +164,7 @@ export default function OrderDetailPage() {
|
|||||||
.then((data) => {
|
.then((data) => {
|
||||||
setOrder(data);
|
setOrder(data);
|
||||||
void loadOrderTrack(data.delivery, data.status);
|
void loadOrderTrack(data.delivery, data.status);
|
||||||
|
applyLocalDeliveryHint(data, setLocalHintHtml);
|
||||||
})
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
});
|
});
|
||||||
@@ -361,6 +382,12 @@ export default function OrderDetailPage() {
|
|||||||
{order.createdAt ? String(order.createdAt).slice(0, 19).replace('T', ' ') : '-'}
|
{order.createdAt ? String(order.createdAt).slice(0, 19).replace('T', ' ') : '-'}
|
||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
|
{order.deliveryType === 'LOCAL' && localHintHtml ? (
|
||||||
|
<View className="order-row">
|
||||||
|
<Text className="order-row-label">配送时效</Text>
|
||||||
|
<DeliveryHintHtml className="order-row-value" html={localHintHtml} />
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -39,6 +39,10 @@ export default function RedeemCodePage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const token = decodeURIComponent(router.params.token ?? '');
|
const token = decodeURIComponent(router.params.token ?? '');
|
||||||
const amount = Number(router.params.amount ?? 0);
|
const amount = Number(router.params.amount ?? 0);
|
||||||
|
const landingUrl = router.params.landingUrl
|
||||||
|
? decodeURIComponent(router.params.landingUrl)
|
||||||
|
: '';
|
||||||
|
const qrPayload = landingUrl || token;
|
||||||
|
|
||||||
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
||||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
@@ -148,7 +152,7 @@ export default function RedeemCodePage() {
|
|||||||
<View className="redeem-code-panel">
|
<View className="redeem-code-panel">
|
||||||
<Text className="redeem-code-head">请向收银员出示此码</Text>
|
<Text className="redeem-code-head">请向收银员出示此码</Text>
|
||||||
<View className="redeem-qr-wrap">
|
<View className="redeem-qr-wrap">
|
||||||
<RedeemQrCode token={token} />
|
<RedeemQrCode payload={qrPayload} />
|
||||||
</View>
|
</View>
|
||||||
<View className={`redeem-timer${timerSec > 0 && timerSec < REDEEM_TOKEN_TTL_SECONDS ? ' redeem-timer--active' : ''}`}>
|
<View className={`redeem-timer${timerSec > 0 && timerSec < REDEEM_TOKEN_TTL_SECONDS ? ' redeem-timer--active' : ''}`}>
|
||||||
<Text className="redeem-timer-value">{formatTimer(timerSec)}</Text>
|
<Text className="redeem-timer-value">{formatTimer(timerSec)}</Text>
|
||||||
|
|||||||
@@ -113,12 +113,15 @@ export default function RedeemPage() {
|
|||||||
const body: { amount: number; couponId?: string } = { amount: value };
|
const body: { amount: number; couponId?: string } = { amount: value };
|
||||||
if (couponId) body.couponId = couponId;
|
if (couponId) body.couponId = couponId;
|
||||||
|
|
||||||
const data = await request<{ token: string; amount: number }>('/redeem/tokens', {
|
const data = await request<{ token: string; amount: number; landingUrl?: string }>('/redeem/tokens', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data: body,
|
data: body,
|
||||||
});
|
});
|
||||||
|
const landingQs = data.landingUrl
|
||||||
|
? `&landingUrl=${encodeURIComponent(data.landingUrl)}`
|
||||||
|
: '';
|
||||||
Taro.navigateTo({
|
Taro.navigateTo({
|
||||||
url: `/pages/redeem-code/index?token=${encodeURIComponent(data.token)}&amount=${data.amount}`,
|
url: `/pages/redeem-code/index?token=${encodeURIComponent(data.token)}&amount=${data.amount}${landingQs}`,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast(e instanceof Error ? e.message : '生成失败');
|
toast(e instanceof Error ? e.message : '生成失败');
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import Taro, {
|
|||||||
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 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';
|
||||||
@@ -356,7 +355,6 @@ export default function StoreDetailPage() {
|
|||||||
solid={headerSolid}
|
solid={headerSolid}
|
||||||
titleVisible={headerSolid}
|
titleVisible={headerSolid}
|
||||||
onBack={goBack}
|
onBack={goBack}
|
||||||
right={<ShareNavButton payload={sharePayload} />}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<View className="store-detail-hero full-bleed">
|
<View className="store-detail-hero full-bleed">
|
||||||
@@ -407,13 +405,11 @@ export default function StoreDetailPage() {
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<View className="store-detail-tags">
|
|
||||||
{store.category?.name ? (
|
{store.category?.name ? (
|
||||||
|
<View className="store-detail-tags">
|
||||||
<Text className="store-detail-tag">{store.category.name}</Text>
|
<Text className="store-detail-tag">{store.category.name}</Text>
|
||||||
) : null}
|
|
||||||
<Text className="store-detail-tag">可核销</Text>
|
|
||||||
<Text className="store-detail-tag">好客门店</Text>
|
|
||||||
</View>
|
</View>
|
||||||
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{marqueeLines.length > 0 ? (
|
{marqueeLines.length > 0 ? (
|
||||||
|
|||||||
@@ -29,6 +29,7 @@
|
|||||||
| 3.5.7 | 08-23 | 门店端核销记录时间显示秒;首页「今日核销金额」文案 | [`v3.5.7`](./杜康好客-v3.5.7-开发文档.md) |
|
| 3.5.7 | 08-23 | 门店端核销记录时间显示秒;首页「今日核销金额」文案 | [`v3.5.7`](./杜康好客-v3.5.7-开发文档.md) |
|
||||||
| 3.5.8 | 08-24 | HQ 单账号追加/撤销权限;运营改客服修复;城市门店服务+城市范围 | [`v3.5.8`](./杜康好客-v3.5.8-开发文档.md) |
|
| 3.5.8 | 08-24 | HQ 单账号追加/撤销权限;运营改客服修复;城市门店服务+城市范围 | [`v3.5.8`](./杜康好客-v3.5.8-开发文档.md) |
|
||||||
| 3.5.9 | 08-25 | 门店累计核销好客权益;HQ 表格去省略号;序号列 + 列设置 + 拖表头改列宽;用户备注 / 手机号不脱敏 | [`v3.5.9`](./杜康好客-v3.5.9-开发文档.md) |
|
| 3.5.9 | 08-25 | 门店累计核销好客权益;HQ 表格去省略号;序号列 + 列设置 + 拖表头改列宽;用户备注 / 手机号不脱敏 | [`v3.5.9`](./杜康好客-v3.5.9-开发文档.md) |
|
||||||
|
| 3.5.10 | 08-25 | C 端门店详情去掉分享按钮;同城送提示改承运商 HTML;小程序客服接通企微微信客服 | [`v3.5.10`](./杜康好客-v3.5.10-开发文档.md) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -64,9 +64,11 @@
|
|||||||
| 3.5.7 | [`门店核销记录时间秒 + 今日核销金额文案`](./杜康好客-v3.5.7-开发文档.md) | 🔶 开发完成 |
|
| 3.5.7 | [`门店核销记录时间秒 + 今日核销金额文案`](./杜康好客-v3.5.7-开发文档.md) | 🔶 开发完成 |
|
||||||
| 3.5.8 | [`HQ 追加/撤销权限 + 运营改客服 + 城市门店服务`](./杜康好客-v3.5.8-开发文档.md) | 🔶 开发完成 |
|
| 3.5.8 | [`HQ 追加/撤销权限 + 运营改客服 + 城市门店服务`](./杜康好客-v3.5.8-开发文档.md) | 🔶 开发完成 |
|
||||||
| 3.5.9 | [`门店累计核销 + HQ 去截断 + 列设置`](./杜康好客-v3.5.9-开发文档.md) | 🔶 开发完成 |
|
| 3.5.9 | [`门店累计核销 + HQ 去截断 + 列设置`](./杜康好客-v3.5.9-开发文档.md) | 🔶 开发完成 |
|
||||||
|
| 3.5.10 | [`门店详情去分享按钮 + 同城提示改承运商 HTML + 小程序客服接企微`](./杜康好客-v3.5.10-开发文档.md) | 🔶 开发完成 |
|
||||||
|
|
||||||
| 日期 | 说明 |
|
| 日期 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
|
| 2026-08-25 | v3.5.10:门店详情去掉分享按钮;同城送提示改承运商 HTML(`GET /catalog/local-deliveries`);小程序客服接通企微(需填 CorpID) |
|
||||||
| 2026-08-25 | v3.5.9:门店列表累计核销好客权益;HQ 表格去省略号;主列表序号 + 列设置/列宽存 HQ 账号;用户列表备注(不改昵称)、手机号不脱敏;订单列表状态可多选 |
|
| 2026-08-25 | v3.5.9:门店列表累计核销好客权益;HQ 表格去省略号;主列表序号 + 列设置/列宽存 HQ 账号;用户列表备注(不改昵称)、手机号不脱敏;订单列表状态可多选 |
|
||||||
| 2026-08-24 | v3.5.8:HQ 单账号追加/撤销权限;运营改客服;城市门店服务与城市范围;分类删除权限与概览按权限/城市裁剪 |
|
| 2026-08-24 | v3.5.8:HQ 单账号追加/撤销权限;运营改客服;城市门店服务与城市范围;分类删除权限与概览按权限/城市裁剪 |
|
||||||
| 2026-08-23 | v3.5.7:门店核销记录时间显示秒;首页「今日到账金额」→「今日核销金额」 |
|
| 2026-08-23 | v3.5.7:门店核销记录时间显示秒;首页「今日到账金额」→「今日核销金额」 |
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# 杜康好客 · v3.5.10 开发文档
|
||||||
|
|
||||||
|
> **2026-08-25** · mini-user / API
|
||||||
|
> **主题**:门店详情去掉分享按钮;同城配送提示 24 小时内送到;小程序客服接通企业微信
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 版本目标
|
||||||
|
|
||||||
|
| # | 任务 | 类型 | 交付 |
|
||||||
|
|---|------|------|------|
|
||||||
|
| 1 | DPT-20260824-896 | BUG | C 端门店详情去掉顶栏「分享」按钮 |
|
||||||
|
| 2 | DPT-20260824-601 | 优化 | 同城送提示改承运商「配送信息提示」(HTML);C 端 `GET /catalog/local-deliveries` |
|
||||||
|
| 3 | DPT-20260822-651 | 需求 | 小程序在线客服调起企业微信「微信客服」 |
|
||||||
|
|
||||||
|
**不做**:改配送规则 / 改 SLA 计算;合伙人/门店端客服;禁用微信右上角「···」分享菜单。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 门店详情去掉分享按钮
|
||||||
|
|
||||||
|
`pages/store-detail` 顶栏不再渲染 `ShareNavButton`。
|
||||||
|
|
||||||
|
右上角微信原生菜单仍可分享(`enableShareAppMessage` / `WechatShareReady` 保留)。只要去掉页面上的分享按钮。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 同城送提示(承运商 HTML)
|
||||||
|
|
||||||
|
不再写死文案。以用户**收货地址城市**为准:该市 `common_city.status=ACTIVE`(已开城)→ 同城,展示对应仓配承运商的「配送信息提示」;未开城 → 跨城,只展示「总部物流、运费到付」。
|
||||||
|
|
||||||
|
```
|
||||||
|
收货市 → 开城仓库(ACTIVE,优先 API_AUTO 且已绑承运商)→ 承运商.delivery_hint_html
|
||||||
|
```
|
||||||
|
|
||||||
|
空字段时 C 端回退纯文本 `同城配送,预计24小时内送到`。不改下单 / 推单 / 起购。
|
||||||
|
|
||||||
|
### 3.1 承运商字段
|
||||||
|
|
||||||
|
`common_fulfillment_provider.delivery_hint_html` TEXT NULL。允许 `span/p/br/b/strong/i/em/font`,style 仅 `color` / `font-weight` / `font-size` / `font-style`。保存与下发前消毒。HQ 文本框里的回车在 C 端转成换行(不必手写 `<br/>`)。
|
||||||
|
|
||||||
|
HQ「仓配管理 → 承运商」多行输入,例如:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<span style="color:#A61D24;font-weight:700;font-size:13px">同城配送,预计24小时内送到</span>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 API
|
||||||
|
|
||||||
|
`GET /catalog/local-deliveries`(公开)。可选 `cityCode` / `cityName`。
|
||||||
|
|
||||||
|
每项:`city` · `warehouse` · `provider` · `hintHtml`。未开城 / 无仓 / 无承运商返回空列表或 `hintHtml=null`,不报错。
|
||||||
|
|
||||||
|
### 3.3 C 端
|
||||||
|
|
||||||
|
| 页面 | 何时展示 |
|
||||||
|
|------|----------|
|
||||||
|
| 商品详情 | 可线上购;用当前选城预览 |
|
||||||
|
| 确认订单 | 收货市已开城且地址校验通过;`RichText` |
|
||||||
|
| 订单详情 | `deliveryType === LOCAL`;按收货市匹配 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 小程序客服接通企业微信
|
||||||
|
|
||||||
|
原先 `open-type=contact` 进入**小程序原生客服**。本版在已配置企微参数时改为 `wx.openCustomerServiceChat`,进入企业微信「微信客服」(与 H5 kfid 同一套)。
|
||||||
|
|
||||||
|
### 配置(HQ → 系统设置 → 微信小程序配置)
|
||||||
|
|
||||||
|
| 键 | 说明 |
|
||||||
|
|----|------|
|
||||||
|
| `CUSTOMER_SERVICE_WECOM_URL` | 微信客服 kfid 链接;缺省用代码常量 |
|
||||||
|
| `WECOM_CORP_ID` | 企业 ID(`ww` 开头)。企微「我的企业」可查 |
|
||||||
|
|
||||||
|
`GET /common/client-config` 下发 `customerServiceWecomUrl`、`wecomCorpId`。
|
||||||
|
|
||||||
|
### 行为
|
||||||
|
|
||||||
|
| 环境 | 条件 | 行为 |
|
||||||
|
|------|------|------|
|
||||||
|
| 小程序 | 链接 + CorpID 都有 | `openCustomerServiceChat`;订单详情可带订单卡片 |
|
||||||
|
| 小程序 | 未填 CorpID | 回退 `open-type=contact` |
|
||||||
|
| H5 | 有 kfid 链接 | 打开企微客服网页 |
|
||||||
|
|
||||||
|
### 企微侧前置(运营)
|
||||||
|
|
||||||
|
1. 开通企业微信「微信客服」,拿到 kfid 链接。
|
||||||
|
2. 把 C 端小程序关联到该企业的微信客服。
|
||||||
|
3. 把 CorpID 填进系统设置。未填则用户仍走小程序原生客服。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4.1 Prisma
|
||||||
|
|
||||||
|
`common_fulfillment_provider.delivery_hint_html` TEXT NULL。脚本:[`migrate-fulfillment-delivery-hint-v3510.sql`](../server/dukang-api/prisma/migrate-fulfillment-delivery-hint-v3510.sql)。
|
||||||
|
|
||||||
|
## 5. 验收清单
|
||||||
|
|
||||||
|
- [ ] 门店详情顶栏没有分享按钮;返回/导航/拨打不受影响
|
||||||
|
- [ ] HQ 承运商可编辑「配送信息提示」HTML(颜色/粗细/字号);非法标签被去掉
|
||||||
|
- [ ] `GET /catalog/local-deliveries` 按开城列出仓库+承运商+hintHtml;`cityName` 可筛收货市
|
||||||
|
- [ ] 商品详情(可线上购)按当前选城展示承运商提示(空则回退「同城配送,预计24小时内送到」)
|
||||||
|
- [ ] 确认订单:收货市已开城显示 HTML 提示;未开城只显示「总部物流、运费到付」
|
||||||
|
- [ ] 同城订单详情「配送时效」为该市承运商提示
|
||||||
|
- [ ] 系统设置可改客服链接与 CorpID;保存后 `client-config` 立即带出
|
||||||
|
- [ ] 小程序已填 CorpID:联系客服进入企微微信客服(非小程序原生客服后台)
|
||||||
|
- [ ] 未填 CorpID:小程序仍能打开原生客服,不白屏
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 关键路径
|
||||||
|
|
||||||
|
| 域 | 路径 |
|
||||||
|
|----|------|
|
||||||
|
| 门店详情 | `apps/mini-user/src/pages/store-detail/index.tsx` |
|
||||||
|
| 同城提示 | `fulfillment-provider.service.ts` · `GET /catalog/local-deliveries` · `DeliveryHintHtml` |
|
||||||
|
| 客服按钮 | `apps/mini-user/src/components/ContactCsButton.tsx` · `lib/wecom-cs.ts` |
|
||||||
|
| 下发 | `client-config.controller.ts` · `packages/shared-types` `config.ts` / `wechat.ts` |
|
||||||
|
| HQ 配置 | `system-config.registry.ts` |
|
||||||
@@ -45,6 +45,8 @@ C 端购酒核销 · 门店扫码核销+打款 · 合伙人拓店履约 · WebAd
|
|||||||
|
|
||||||
**HQ 列表(v3.5.9)**:主表不省略号、可横滑;最左序号;列设置(显隐/顺序)与列宽(拖表头)存 `hq_account.list_column_prefs`。主展示列下划线,点击进编辑或详情。门店列表「累计核销好客权益」= 该店 `RedeemRecord.amount` 合计。用户列表昵称只读(点击进详情);双击「备注」离开即保存(`hq_remark`);列表手机号不脱敏。
|
**HQ 列表(v3.5.9)**:主表不省略号、可横滑;最左序号;列设置(显隐/顺序)与列宽(拖表头)存 `hq_account.list_column_prefs`。主展示列下划线,点击进编辑或详情。门店列表「累计核销好客权益」= 该店 `RedeemRecord.amount` 合计。用户列表昵称只读(点击进详情);双击「备注」离开即保存(`hq_remark`);列表手机号不脱敏。
|
||||||
|
|
||||||
|
**C 端(v3.5.10)**:门店详情无顶栏分享按钮。同城送提示取开城仓库绑定承运商的 `delivery_hint_html`(`GET /catalog/local-deliveries`,按收货市是否开城);空则回退「同城配送,预计24小时内送到」。在线客服优先 `wx.openCustomerServiceChat`(`CUSTOMER_SERVICE_WECOM_URL` + `WECOM_CORP_ID`);未配 CorpID 回退小程序原生客服。
|
||||||
|
|
||||||
## 5. 验收用例(必过)
|
## 5. 验收用例(必过)
|
||||||
|
|
||||||
**主链路 15 项**:登录、4 SKU、起购、支付+权益、双通道核销、payout、关店不可见、拓店审核、配送完成、退款、T+1/T+30…
|
**主链路 15 项**:登录、4 SKU、起购、支付+权益、双通道核销、payout、关店不可见、拓店审核、配送完成、退款、T+1/T+30…
|
||||||
|
|||||||
+6
-3
@@ -22,10 +22,11 @@
|
|||||||
|
|
||||||
- 四 Tab:首页/权益/门店/我的;微信登录+7天会话
|
- 四 Tab:首页/权益/门店/我的;微信登录+7天会话
|
||||||
- 下单:选城→商品→地址→起购校验→微信支付→权益1:1
|
- 下单:选城→商品→地址→起购校验→微信支付→权益1:1
|
||||||
- 权益:直接核销(≤总余额) / 单据核销(≤单据);出码3分钟
|
- 权益:直接核销(≤总余额) / 单据核销(≤单据);出码3分钟。二维码内容为门店 H5 URL(`{SHOP_H5_URL}/redeem?token=`),微信扫一扫直达核销确认页
|
||||||
- 门店:仅 OPEN;详情含套餐/电话(脱敏可拨打)/两段营业时间
|
- 门店:仅 OPEN;详情含套餐/电话(脱敏可拨打)/两段营业时间
|
||||||
- 订单 Tab:待付款/已付款/已完成;物流详情(签收照/拨号/ETA)
|
- 订单 Tab:待付款/已付款/已完成;物流详情(签收照/拨号/ETA)
|
||||||
- 售后:客服入口;发票/四类型工单按 PRD Wave 进度
|
- 售后:客服入口(小程序优先企微微信客服,未配 CorpID 回退原生客服);发票/四类型工单按 PRD Wave 进度
|
||||||
|
- 同城送:收货市已开城则展示承运商「配送信息提示」(HTML);未开城走跨城到付;门店详情无顶栏分享按钮
|
||||||
- 版本:`minClientVersion` 过低强制更新或退出
|
- 版本:`minClientVersion` 过低强制更新或退出
|
||||||
- 「我的」头像昵称:`chooseAvatar` + `input type=nickname`(见下「踩坑」)
|
- 「我的」头像昵称:`chooseAvatar` + `input type=nickname`(见下「踩坑」)
|
||||||
|
|
||||||
@@ -47,7 +48,7 @@
|
|||||||
|
|
||||||
## 3. 门店端(h5-shop)
|
## 3. 门店端(h5-shop)
|
||||||
|
|
||||||
- 登录绑定门店;首页扫码核销(微信 JSSDK)
|
- 登录绑定门店;首页扫码核销(微信 JSSDK);也可微信扫一扫用户核销码直达确认页(仍需点「确认核销」)
|
||||||
- 核销记录;今日汇总;到账金额×60%展示
|
- 核销记录;今日汇总;到账金额×60%展示
|
||||||
- 营业状态开关;Mine 门店信息
|
- 营业状态开关;Mine 门店信息
|
||||||
- 套餐:列表编辑→提交 HQ 审核(v3.4.10)
|
- 套餐:列表编辑→提交 HQ 审核(v3.4.10)
|
||||||
@@ -68,6 +69,7 @@
|
|||||||
| 规则 | 说明 |
|
| 规则 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| iOS 登录/选店后 | 用 `location.replace(path)`(`hardNavigateInWechat`),禁止仅 React Router navigate |
|
| iOS 登录/选店后 | 用 `location.replace(path)`(`hardNavigateInWechat`),禁止仅 React Router navigate |
|
||||||
|
| 微信扫一扫落地核销页 | 成功后须 `hardNavigateInWechat('/')` 回首页,否则入场 URL 仍是 `/redeem?token=`,下次首页扫码验签失败 |
|
||||||
| iOS 签名 URL | `getJssdkSignUrl()` = 入场 URL,**保留** OAuth `code/state`;后端 `jssdk-config` 勿剔除 |
|
| iOS 签名 URL | `getJssdkSignUrl()` = 入场 URL,**保留** OAuth `code/state`;后端 `jssdk-config` 勿剔除 |
|
||||||
| 已绑定微信 | 短信登录后**不要**再强制 OAuth(避免反复重置入场 URL) |
|
| 已绑定微信 | 短信登录后**不要**再强制 OAuth(避免反复重置入场 URL) |
|
||||||
| 扫码仍失败 | 弹窗引导「刷新页面」/「重新授权微信」,勿只提示再点一次 |
|
| 扫码仍失败 | 弹窗引导「刷新页面」/「重新授权微信」,勿只提示再点一次 |
|
||||||
@@ -150,6 +152,7 @@ HQ 账号/角色(`hq-permissions`,生效=(角色∪追加)−撤销;可绑
|
|||||||
| 智能机器人 | `/wecom/bots` 长连接指令 |
|
| 智能机器人 | `/wecom/bots` 长连接指令 |
|
||||||
| 消息推送 | `/wecom/pushes` Webhook+eventKey |
|
| 消息推送 | `/wecom/pushes` Webhook+eventKey |
|
||||||
| 日志 | `/logs/wecom-bots` |
|
| 日志 | `/logs/wecom-bots` |
|
||||||
|
| C 端微信客服 | 系统设置 `CUSTOMER_SERVICE_WECOM_URL` + `WECOM_CORP_ID`;小程序须已关联该企业微信客服 |
|
||||||
|
|
||||||
eventKey:`alert.ops` · `support_ticket.created` · `dev_plan.task_dispatch` · 支付/核销/结算告警。
|
eventKey:`alert.ops` · `support_ticket.created` · `dev_plan.task_dispatch` · 支付/核销/结算告警。
|
||||||
|
|
||||||
|
|||||||
@@ -19,9 +19,11 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"dev": "tsc --watch",
|
"dev": "tsc --watch",
|
||||||
|
"test": "vitest run",
|
||||||
"lint": "eslint src"
|
"lint": "eslint src"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.4.5"
|
"typescript": "^5.4.5",
|
||||||
|
"vitest": "^1.6.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,11 +30,16 @@ export interface AppConfig {
|
|||||||
tencentLbsSecretKey: string;
|
tencentLbsSecretKey: string;
|
||||||
/** C 端 H5 落地页(推广码二维码链接前缀) */
|
/** C 端 H5 落地页(推广码二维码链接前缀) */
|
||||||
userH5Url: string;
|
userH5Url: string;
|
||||||
|
/** 门店 H5 落地页(用户核销码二维码链接前缀) */
|
||||||
|
shopH5Url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 推广码 / C 端 H5 默认落地页(系统设置 USER_H5_URL 未配时回退;HQ 可改) */
|
/** 推广码 / 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';
|
||||||
|
|
||||||
|
/** 门店 H5 默认落地页(系统设置 SHOP_H5_URL 未配时回退;HQ 可改) */
|
||||||
|
export const DEFAULT_SHOP_H5_URL = 'https://shop.dukanghaoke.com';
|
||||||
|
|
||||||
/** 品牌 Logo OSS 根路径(默认;系统设置 BRAND_LOGO_OSS_BASE 可覆盖) */
|
/** 品牌 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/';
|
||||||
|
|
||||||
@@ -58,12 +63,15 @@ export const QUALIFICATION_DISCLOSURE_URL = `${MINI_USER_STATIC_OSS_BASE}qualifi
|
|||||||
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 企业微信「微信客服」链接(C 端「在线客服」;微信内网页点击后进入原生客服会话)
|
* 企业微信「微信客服」链接(C 端「在线客服」;微信内网页 / 小程序 openCustomerServiceChat)
|
||||||
* 可在 h5-user 用 VITE_CS_WECOM_URL 覆盖
|
* 可在系统设置 CUSTOMER_SERVICE_WECOM_URL 覆盖
|
||||||
*/
|
*/
|
||||||
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';
|
||||||
|
|
||||||
|
/** 企业微信 CorpID(小程序 wx.openCustomerServiceChat 必填;系统设置 WECOM_CORP_ID) */
|
||||||
|
export const WECOM_CORP_ID = '';
|
||||||
|
|
||||||
/** 从 env / 系统设置解析的 C 端品牌与客服展示配置(缺省回退常量) */
|
/** 从 env / 系统设置解析的 C 端品牌与客服展示配置(缺省回退常量) */
|
||||||
export type ClientBrandRuntime = {
|
export type ClientBrandRuntime = {
|
||||||
userH5Url: string;
|
userH5Url: string;
|
||||||
@@ -74,6 +82,8 @@ export type ClientBrandRuntime = {
|
|||||||
miniUserStaticOssBase: string;
|
miniUserStaticOssBase: string;
|
||||||
qualificationDisclosureUrl: string;
|
qualificationDisclosureUrl: string;
|
||||||
customerServicePhone: string;
|
customerServicePhone: string;
|
||||||
|
customerServiceWecomUrl: string;
|
||||||
|
wecomCorpId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function resolveClientBrandRuntime(
|
export function resolveClientBrandRuntime(
|
||||||
@@ -95,6 +105,8 @@ export function resolveClientBrandRuntime(
|
|||||||
(e.QUALIFICATION_DISCLOSURE_URL || '').trim() ||
|
(e.QUALIFICATION_DISCLOSURE_URL || '').trim() ||
|
||||||
`${staticBase}qualification-disclosure.png`,
|
`${staticBase}qualification-disclosure.png`,
|
||||||
customerServicePhone: (e.CUSTOMER_SERVICE_PHONE || CUSTOMER_SERVICE_PHONE).trim(),
|
customerServicePhone: (e.CUSTOMER_SERVICE_PHONE || CUSTOMER_SERVICE_PHONE).trim(),
|
||||||
|
customerServiceWecomUrl: (e.CUSTOMER_SERVICE_WECOM_URL || CUSTOMER_SERVICE_WECOM_URL).trim(),
|
||||||
|
wecomCorpId: (e.WECOM_CORP_ID || WECOM_CORP_ID).trim(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,6 +277,7 @@ export function loadAppConfig(env?: Record<string, string | undefined>): AppConf
|
|||||||
tencentLbsKey: e.TENCENT_LBS_KEY ?? '',
|
tencentLbsKey: e.TENCENT_LBS_KEY ?? '',
|
||||||
tencentLbsSecretKey: e.TENCENT_LBS_SECRET_KEY ?? '',
|
tencentLbsSecretKey: e.TENCENT_LBS_SECRET_KEY ?? '',
|
||||||
userH5Url: (e.USER_H5_URL || DEFAULT_USER_H5_URL).replace(/\/$/, ''),
|
userH5Url: (e.USER_H5_URL || DEFAULT_USER_H5_URL).replace(/\/$/, ''),
|
||||||
|
shopH5Url: (e.SHOP_H5_URL || DEFAULT_SHOP_H5_URL).replace(/\/$/, ''),
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
...base,
|
...base,
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { isXfxProviderCode } from './fulfillment-provider';
|
||||||
|
|
||||||
|
describe('isXfxProviderCode', () => {
|
||||||
|
it('匹配标准编码与城市前缀', () => {
|
||||||
|
expect(isXfxProviderCode('XFX')).toBe(true);
|
||||||
|
expect(isXfxProviderCode('xiaofeixia')).toBe(true);
|
||||||
|
expect(isXfxProviderCode('ZZXFX')).toBe(true);
|
||||||
|
expect(isXfxProviderCode('XFX_ZZ')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('不匹配普通承运商', () => {
|
||||||
|
expect(isXfxProviderCode('')).toBe(false);
|
||||||
|
expect(isXfxProviderCode('LOGISTICS')).toBe(false);
|
||||||
|
expect(isXfxProviderCode('MANUAL')).toBe(false);
|
||||||
|
expect(isXfxProviderCode('SF')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -55,6 +55,8 @@ export interface FulfillmentProviderDto {
|
|||||||
settlementMethod: LogisticsSettlementMethod;
|
settlementMethod: LogisticsSettlementMethod;
|
||||||
pricingRules?: LogisticsPricingRuleDto | null;
|
pricingRules?: LogisticsPricingRuleDto | null;
|
||||||
prepaidBalance: number;
|
prepaidBalance: number;
|
||||||
|
/** C 端同城配送提示(已消毒 HTML) */
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -74,6 +76,7 @@ export interface CreateFulfillmentProviderInput {
|
|||||||
bankAccountNo?: string | null;
|
bankAccountNo?: string | null;
|
||||||
settlementMethod?: LogisticsSettlementMethod;
|
settlementMethod?: LogisticsSettlementMethod;
|
||||||
pricingRules?: LogisticsPricingRuleDto | null;
|
pricingRules?: LogisticsPricingRuleDto | null;
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateFulfillmentProviderInput {
|
export interface UpdateFulfillmentProviderInput {
|
||||||
@@ -89,6 +92,7 @@ export interface UpdateFulfillmentProviderInput {
|
|||||||
bankAccountNo?: string | null;
|
bankAccountNo?: string | null;
|
||||||
settlementMethod?: LogisticsSettlementMethod;
|
settlementMethod?: LogisticsSettlementMethod;
|
||||||
pricingRules?: LogisticsPricingRuleDto | null;
|
pricingRules?: LogisticsPricingRuleDto | null;
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { DEFAULT_XFX_LOGISTICS_PRICING };
|
export { DEFAULT_XFX_LOGISTICS_PRICING };
|
||||||
@@ -110,6 +114,91 @@ export interface WarehouseFulfillmentConfig {
|
|||||||
|
|
||||||
export const XFX_PROVIDER_CODES = ['XFX', 'XIAOFEIXIA'] as const;
|
export const XFX_PROVIDER_CODES = ['XFX', 'XIAOFEIXIA'] as const;
|
||||||
|
|
||||||
|
/** 小飞侠承运商编码:精确 XFX/XIAOFEIXIA,以及城市前缀如 ZZXFX */
|
||||||
export function isXfxProviderCode(code: string): boolean {
|
export function isXfxProviderCode(code: string): boolean {
|
||||||
return (XFX_PROVIDER_CODES as readonly string[]).includes(code.trim().toUpperCase());
|
const c = code.trim().toUpperCase();
|
||||||
|
if (!c) return false;
|
||||||
|
if ((XFX_PROVIDER_CODES as readonly string[]).includes(c)) return true;
|
||||||
|
if (c.includes('XIAOFEIXIA')) return true;
|
||||||
|
return c.endsWith('XFX') || c.startsWith('XFX');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 承运商未配置提示时 C 端回退文案 */
|
||||||
|
export const DEFAULT_LOCAL_DELIVERY_HINT = '同城配送,预计24小时内送到';
|
||||||
|
|
||||||
|
export const LOCAL_DELIVERY_HINT_MAX_LEN = 2000;
|
||||||
|
|
||||||
|
const HINT_ALLOWED_TAGS = new Set(['span', 'p', 'br', 'b', 'strong', 'i', 'em', 'font']);
|
||||||
|
const HINT_ALLOWED_STYLES = new Set(['color', 'font-weight', 'font-size', 'font-style']);
|
||||||
|
|
||||||
|
export type LocalDeliveryDto = {
|
||||||
|
city: { id: string; code: string; name: string };
|
||||||
|
warehouse: { id: string; name: string; fulfillmentMode: string } | null;
|
||||||
|
provider: { id: string; code: string; name: string } | null;
|
||||||
|
hintHtml: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function sanitizeHintStyle(raw: string): string {
|
||||||
|
return raw
|
||||||
|
.split(';')
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((part) => {
|
||||||
|
const idx = part.indexOf(':');
|
||||||
|
if (idx <= 0) return '';
|
||||||
|
const key = part.slice(0, idx).trim().toLowerCase();
|
||||||
|
const value = part.slice(idx + 1).trim();
|
||||||
|
if (!HINT_ALLOWED_STYLES.has(key)) return '';
|
||||||
|
if (/url\s*\(|expression\s*\(|javascript\s*:/i.test(value)) return '';
|
||||||
|
return `${key}:${value}`;
|
||||||
|
})
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(';');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 文本换行转成 br,供 C 端 RichText 使用(不改 HQ 存盘原文) */
|
||||||
|
export function deliveryHintHtmlToRichNodes(html: string): string {
|
||||||
|
return html
|
||||||
|
.replace(/\r\n|\r|\n/g, '<br/>')
|
||||||
|
.replace(/(?:<br\s*\/?>){3,}/gi, '<br/><br/>');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 承运商配送提示 HTML:去掉脚本/事件,只保留字号颜色粗细 */
|
||||||
|
export function sanitizeDeliveryHintHtml(raw?: string | null): string | null {
|
||||||
|
if (raw == null) return null;
|
||||||
|
let html = String(raw).trim();
|
||||||
|
if (!html) return null;
|
||||||
|
if (html.length > LOCAL_DELIVERY_HINT_MAX_LEN) {
|
||||||
|
html = html.slice(0, LOCAL_DELIVERY_HINT_MAX_LEN);
|
||||||
|
}
|
||||||
|
html = html.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, '');
|
||||||
|
html = html.replace(/on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '');
|
||||||
|
html = html.replace(/javascript\s*:/gi, '');
|
||||||
|
html = html.replace(/<\/?([a-zA-Z][a-zA-Z0-9]*)\b([^>]*)>/g, (_full, tag: string, attrs: string) => {
|
||||||
|
const name = String(tag).toLowerCase();
|
||||||
|
const closing = String(_full).startsWith('</');
|
||||||
|
if (!HINT_ALLOWED_TAGS.has(name)) return '';
|
||||||
|
if (name === 'br') return closing ? '' : '<br/>';
|
||||||
|
if (closing) return `</${name}>`;
|
||||||
|
let style = '';
|
||||||
|
const styleMatch = String(attrs).match(/\sstyle\s*=\s*("([^"]*)"|'([^']*)')/i);
|
||||||
|
if (styleMatch) {
|
||||||
|
style = sanitizeHintStyle(styleMatch[2] ?? styleMatch[3] ?? '');
|
||||||
|
}
|
||||||
|
let color = '';
|
||||||
|
let size = '';
|
||||||
|
if (name === 'font') {
|
||||||
|
const colorMatch = String(attrs).match(/\scolor\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||||
|
if (colorMatch) color = (colorMatch[2] ?? colorMatch[3] ?? colorMatch[4] ?? '').trim();
|
||||||
|
const sizeMatch = String(attrs).match(/\ssize\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||||
|
if (sizeMatch) size = (sizeMatch[2] ?? sizeMatch[3] ?? sizeMatch[4] ?? '').trim();
|
||||||
|
}
|
||||||
|
const extra: string[] = [];
|
||||||
|
if (style) extra.push(`style="${style}"`);
|
||||||
|
if (color) extra.push(`color="${color.replace(/"/g, '')}"`);
|
||||||
|
if (size) extra.push(`size="${size.replace(/"/g, '')}"`);
|
||||||
|
return extra.length ? `<${name} ${extra.join(' ')}>` : `<${name}>`;
|
||||||
|
});
|
||||||
|
const cleaned = html.replace(/ /g, ' ').trim();
|
||||||
|
return cleaned || null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { buildShopRedeemLandingUrl, parseRedeemTokenFromScan } from './redeem';
|
||||||
|
|
||||||
|
const TOKEN = 'a1b2c3d4e5f6789012345678901234ab';
|
||||||
|
|
||||||
|
describe('buildShopRedeemLandingUrl', () => {
|
||||||
|
it('joins shop H5 origin with /redeem?token=', () => {
|
||||||
|
expect(buildShopRedeemLandingUrl('https://shop.dukanghaoke.com', TOKEN)).toBe(
|
||||||
|
`https://shop.dukanghaoke.com/redeem?token=${TOKEN}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('strips trailing slash on the base', () => {
|
||||||
|
expect(buildShopRedeemLandingUrl('https://shop-test.dukanghaoke.com/', TOKEN)).toBe(
|
||||||
|
`https://shop-test.dukanghaoke.com/redeem?token=${TOKEN}`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('parseRedeemTokenFromScan', () => {
|
||||||
|
it('accepts a raw 32-hex token', () => {
|
||||||
|
expect(parseRedeemTokenFromScan(TOKEN.toUpperCase())).toBe(TOKEN);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts token from shop landing URL', () => {
|
||||||
|
const url = buildShopRedeemLandingUrl('https://shop.dukanghaoke.com', TOKEN);
|
||||||
|
expect(parseRedeemTokenFromScan(url)).toBe(TOKEN);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('strips WeChat QR_CODE prefix before parsing URL', () => {
|
||||||
|
const url = buildShopRedeemLandingUrl('https://shop.dukanghaoke.com', TOKEN);
|
||||||
|
expect(parseRedeemTokenFromScan(`QR_CODE,${url}`)).toBe(TOKEN);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for empty or unrelated content', () => {
|
||||||
|
expect(parseRedeemTokenFromScan('')).toBeNull();
|
||||||
|
expect(parseRedeemTokenFromScan('https://shop.dukanghaoke.com/records')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -9,6 +9,48 @@ export interface RedeemTokenResult {
|
|||||||
expireAt: string;
|
expireAt: string;
|
||||||
amount: number;
|
amount: number;
|
||||||
boundStoreId?: string | null;
|
boundStoreId?: string | null;
|
||||||
|
/** 门店 H5 核销确认页落地 URL(写入二维码,微信扫一扫可直达) */
|
||||||
|
landingUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const REDEEM_TOKEN_HEX = /^[a-f0-9]{32}$/i;
|
||||||
|
|
||||||
|
/** 门店核销确认页落地 URL,供用户端核销码使用 */
|
||||||
|
export function buildShopRedeemLandingUrl(shopH5Url: string, token: string): string {
|
||||||
|
const base = shopH5Url.replace(/\/$/, '');
|
||||||
|
return `${base}/redeem?token=${encodeURIComponent(token)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 微信扫码偶发 `QR_CODE,payload` 前缀 */
|
||||||
|
function stripScanTypePrefix(raw: string): string {
|
||||||
|
const comma = raw.indexOf(',');
|
||||||
|
if (comma > 0 && comma < 24 && /^[A-Z0-9_]+$/.test(raw.slice(0, comma))) {
|
||||||
|
return raw.slice(comma + 1).trim();
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从微信扫码结果解析核销 token(32 位 hex 或带 token 参数的 URL) */
|
||||||
|
export function parseRedeemTokenFromScan(raw: string): string | null {
|
||||||
|
const trimmed = stripScanTypePrefix(raw.trim());
|
||||||
|
if (!trimmed) return null;
|
||||||
|
|
||||||
|
if (REDEEM_TOKEN_HEX.test(trimmed)) {
|
||||||
|
return trimmed.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = trimmed.startsWith('http') ? new URL(trimmed) : new URL(trimmed, 'https://local.invalid');
|
||||||
|
const fromQuery = url.searchParams.get('token');
|
||||||
|
if (fromQuery && REDEEM_TOKEN_HEX.test(fromQuery)) {
|
||||||
|
return fromQuery.toLowerCase();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* not a URL */
|
||||||
|
}
|
||||||
|
|
||||||
|
const hexMatch = trimmed.match(/[a-f0-9]{32}/i);
|
||||||
|
return hexMatch ? hexMatch[0].toLowerCase() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RedeemPreviewDto {
|
export interface RedeemPreviewDto {
|
||||||
|
|||||||
@@ -95,6 +95,8 @@ export interface OrderTrackDto {
|
|||||||
provider?: string;
|
provider?: string;
|
||||||
trackingNo?: string | null;
|
trackingNo?: string | null;
|
||||||
logisticsCompany?: string | null;
|
logisticsCompany?: string | null;
|
||||||
|
/** 承运商查询失败原因(有则 HQ/C 端应展示,避免空白「暂无路由」) */
|
||||||
|
queryError?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
||||||
|
|||||||
@@ -64,6 +64,10 @@ export type ClientRuntimeConfig = {
|
|||||||
qualificationDisclosureUrl?: string;
|
qualificationDisclosureUrl?: string;
|
||||||
/** 总部客服电话 */
|
/** 总部客服电话 */
|
||||||
customerServicePhone?: string;
|
customerServicePhone?: string;
|
||||||
|
/** 企业微信「微信客服」链接(kfid) */
|
||||||
|
customerServiceWecomUrl?: string;
|
||||||
|
/** 企业微信 CorpID(小程序调起企微客服) */
|
||||||
|
wecomCorpId?: string;
|
||||||
/** 合伙人入驻:企微客服二维码图片 URL */
|
/** 合伙人入驻:企微客服二维码图片 URL */
|
||||||
partnerOnboardCsQrUrl?: string | null;
|
partnerOnboardCsQrUrl?: string | null;
|
||||||
/** 合伙人入驻:企微客服提示文案 */
|
/** 合伙人入驻:企微客服提示文案 */
|
||||||
|
|||||||
@@ -9,5 +9,6 @@
|
|||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"]
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["src/**/*.test.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
Generated
+3
@@ -279,6 +279,9 @@ importers:
|
|||||||
typescript:
|
typescript:
|
||||||
specifier: ^5.4.5
|
specifier: ^5.4.5
|
||||||
version: 5.9.3
|
version: 5.9.3
|
||||||
|
vitest:
|
||||||
|
specifier: ^1.6.1
|
||||||
|
version: 1.6.1(@types/node@25.9.5)(sass@1.101.0)(terser@5.48.0)
|
||||||
|
|
||||||
packages/shared-ui:
|
packages/shared-ui:
|
||||||
devDependencies:
|
devDependencies:
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ MOCK_WECHAT=true
|
|||||||
# C 端 H5 落地页(推广码二维码链接前缀,USER_H5_URL)
|
# C 端 H5 落地页(推广码二维码链接前缀,USER_H5_URL)
|
||||||
# 未配置时默认 https://user.runxian.top/user;本地开发可设为 http://localhost:5173/user
|
# 未配置时默认 https://user.runxian.top/user;本地开发可设为 http://localhost:5173/user
|
||||||
# USER_H5_URL=https://user.runxian.top/user
|
# USER_H5_URL=https://user.runxian.top/user
|
||||||
|
# 门店 H5 落地页(用户核销码二维码链接前缀,SHOP_H5_URL)
|
||||||
|
# 未配置时默认 https://shop.dukanghaoke.com;本地开发可设为 http://localhost:5174
|
||||||
|
# SHOP_H5_URL=https://shop.dukanghaoke.com
|
||||||
|
|
||||||
# 反向代理后提取真实客户端 IP(下单 IP 定位)
|
# 反向代理后提取真实客户端 IP(下单 IP 定位)
|
||||||
TRUST_PROXY=true
|
TRUST_PROXY=true
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ TRUST_PROXY=true
|
|||||||
|
|
||||||
# C 端 H5 落地页(推广码二维码;生产统一入口)
|
# C 端 H5 落地页(推广码二维码;生产统一入口)
|
||||||
USER_H5_URL=https://user.runxian.top/user
|
USER_H5_URL=https://user.runxian.top/user
|
||||||
|
# 门店 H5 落地页(用户核销码二维码)
|
||||||
|
SHOP_H5_URL=https://shop.dukanghaoke.com
|
||||||
|
|
||||||
MOCK_WECHAT=false
|
MOCK_WECHAT=false
|
||||||
WX_APP_ID=
|
WX_APP_ID=
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ TRUST_PROXY=true
|
|||||||
|
|
||||||
# C 端 H5(测试域)
|
# C 端 H5(测试域)
|
||||||
USER_H5_URL=https://user-test.dukanghaoke.com/user
|
USER_H5_URL=https://user-test.dukanghaoke.com/user
|
||||||
|
# 门店 H5(测试域,核销码落地页)
|
||||||
|
SHOP_H5_URL=https://shop-test.dukanghaoke.com
|
||||||
|
|
||||||
# 正式号配置可与生产相同,但 Mock 打开后不走真实支付
|
# 正式号配置可与生产相同,但 Mock 打开后不走真实支付
|
||||||
WX_APP_ID=
|
WX_APP_ID=
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- v3.5.10:承运商「配送信息提示」(C 端同城送 HTML)
|
||||||
|
ALTER TABLE `common_fulfillment_provider`
|
||||||
|
ADD COLUMN `delivery_hint_html` TEXT NULL AFTER `prepaid_balance`;
|
||||||
@@ -1057,6 +1057,8 @@ model FulfillmentProvider {
|
|||||||
settlementMethod LogisticsSettlementMethod @default(PREPAID) @map("settlement_method")
|
settlementMethod LogisticsSettlementMethod @default(PREPAID) @map("settlement_method")
|
||||||
pricingRulesJson String? @map("pricing_rules_json") @db.Text
|
pricingRulesJson String? @map("pricing_rules_json") @db.Text
|
||||||
prepaidBalance Decimal @default(0) @map("prepaid_balance") @db.Decimal(12, 2)
|
prepaidBalance Decimal @default(0) @map("prepaid_balance") @db.Decimal(12, 2)
|
||||||
|
/// C 端同城配送提示(HTML,消毒后下发)
|
||||||
|
deliveryHintHtml String? @map("delivery_hint_html") @db.Text
|
||||||
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)
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ const fixed = {
|
|||||||
AUTO_APPROVE_STORE: 'true',
|
AUTO_APPROVE_STORE: 'true',
|
||||||
TRUST_PROXY: 'true',
|
TRUST_PROXY: 'true',
|
||||||
USER_H5_URL: 'https://user-test.dukanghaoke.com/user',
|
USER_H5_URL: 'https://user-test.dukanghaoke.com/user',
|
||||||
|
SHOP_H5_URL: 'https://shop-test.dukanghaoke.com',
|
||||||
WX_PAY_NOTIFY_URL: 'https://api-test.dukanghaoke.com/api/v1/callbacks/wechat/pay',
|
WX_PAY_NOTIFY_URL: 'https://api-test.dukanghaoke.com/api/v1/callbacks/wechat/pay',
|
||||||
OSS_UPLOAD_PREFIX: 'staging/uploads',
|
OSS_UPLOAD_PREFIX: 'staging/uploads',
|
||||||
WECOM_AIBOT_ENABLED: 'false',
|
WECOM_AIBOT_ENABLED: 'false',
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ export const HqOperationAction = {
|
|||||||
LOGISTICS_BILL_CONFIRM: 'LOGISTICS_BILL_CONFIRM',
|
LOGISTICS_BILL_CONFIRM: 'LOGISTICS_BILL_CONFIRM',
|
||||||
LOGISTICS_BILL_BATCH_CONFIRM: 'LOGISTICS_BILL_BATCH_CONFIRM',
|
LOGISTICS_BILL_BATCH_CONFIRM: 'LOGISTICS_BILL_BATCH_CONFIRM',
|
||||||
LOGISTICS_PROVIDER_RECHARGE: 'LOGISTICS_PROVIDER_RECHARGE',
|
LOGISTICS_PROVIDER_RECHARGE: 'LOGISTICS_PROVIDER_RECHARGE',
|
||||||
|
LOGISTICS_PROVIDER_DELETE: 'LOGISTICS_PROVIDER_DELETE',
|
||||||
REDEEM_DEBUG_CREATE_TOKEN: 'REDEEM_DEBUG_CREATE_TOKEN',
|
REDEEM_DEBUG_CREATE_TOKEN: 'REDEEM_DEBUG_CREATE_TOKEN',
|
||||||
REDEEM_DEBUG_CONFIRM: 'REDEEM_DEBUG_CONFIRM',
|
REDEEM_DEBUG_CONFIRM: 'REDEEM_DEBUG_CONFIRM',
|
||||||
PROMO_CODE_CREATE: 'PROMO_CODE_CREATE',
|
PROMO_CODE_CREATE: 'PROMO_CODE_CREATE',
|
||||||
@@ -202,6 +203,7 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
|||||||
[HqOperationAction.LOGISTICS_BILL_CONFIRM]: '物流对账单确认结算',
|
[HqOperationAction.LOGISTICS_BILL_CONFIRM]: '物流对账单确认结算',
|
||||||
[HqOperationAction.LOGISTICS_BILL_BATCH_CONFIRM]: '批量物流对账单结算',
|
[HqOperationAction.LOGISTICS_BILL_BATCH_CONFIRM]: '批量物流对账单结算',
|
||||||
[HqOperationAction.LOGISTICS_PROVIDER_RECHARGE]: '物流承运商充值',
|
[HqOperationAction.LOGISTICS_PROVIDER_RECHARGE]: '物流承运商充值',
|
||||||
|
[HqOperationAction.LOGISTICS_PROVIDER_DELETE]: '删除物流承运商',
|
||||||
[HqOperationAction.REDEEM_DEBUG_CREATE_TOKEN]: '核销调试-生成码',
|
[HqOperationAction.REDEEM_DEBUG_CREATE_TOKEN]: '核销调试-生成码',
|
||||||
[HqOperationAction.REDEEM_DEBUG_CONFIRM]: '核销调试-确认核销',
|
[HqOperationAction.REDEEM_DEBUG_CONFIRM]: '核销调试-确认核销',
|
||||||
[HqOperationAction.PROMO_CODE_CREATE]: '创建推广码',
|
[HqOperationAction.PROMO_CODE_CREATE]: '创建推广码',
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
BRAND_LOGO_URL,
|
BRAND_LOGO_URL,
|
||||||
BRAND_LOGO_WIDE_URL,
|
BRAND_LOGO_WIDE_URL,
|
||||||
CUSTOMER_SERVICE_PHONE,
|
CUSTOMER_SERVICE_PHONE,
|
||||||
|
CUSTOMER_SERVICE_WECOM_URL,
|
||||||
DEFAULT_SHARE_BENEFIT_TITLE,
|
DEFAULT_SHARE_BENEFIT_TITLE,
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
DEFAULT_SHARE_HINT,
|
DEFAULT_SHARE_HINT,
|
||||||
@@ -12,6 +13,7 @@ import {
|
|||||||
DEFAULT_SHARE_ORDER_TITLE,
|
DEFAULT_SHARE_ORDER_TITLE,
|
||||||
DEFAULT_SHARE_STORES_TITLE,
|
DEFAULT_SHARE_STORES_TITLE,
|
||||||
DEFAULT_SHARE_TITLE,
|
DEFAULT_SHARE_TITLE,
|
||||||
|
DEFAULT_SHOP_H5_URL,
|
||||||
DEFAULT_USER_H5_URL,
|
DEFAULT_USER_H5_URL,
|
||||||
MINI_USER_STATIC_OSS_BASE,
|
MINI_USER_STATIC_OSS_BASE,
|
||||||
MOCK_SMS_FIXED_CODE,
|
MOCK_SMS_FIXED_CODE,
|
||||||
@@ -154,6 +156,15 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
placeholder: 'https://user.example.com/user',
|
placeholder: 'https://user.example.com/user',
|
||||||
description: '推广码二维码 / 未配置时的默认落地页前缀(无末尾斜杠)',
|
description: '推广码二维码 / 未配置时的默认落地页前缀(无末尾斜杠)',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'SHOP_H5_URL',
|
||||||
|
label: '门店 H5 落地页',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'https://shop.dukanghaoke.com',
|
||||||
|
description: '用户核销码二维码链接前缀;扫码直达门店核销确认页(无末尾斜杠)',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'BRAND_LOGO_OSS_BASE',
|
key: 'BRAND_LOGO_OSS_BASE',
|
||||||
label: '品牌 Logo OSS 根路径',
|
label: '品牌 Logo OSS 根路径',
|
||||||
@@ -213,6 +224,24 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
placeholder: '13203801799',
|
placeholder: '13203801799',
|
||||||
description: 'C 端联系客服拨号号码',
|
description: 'C 端联系客服拨号号码',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'CUSTOMER_SERVICE_WECOM_URL',
|
||||||
|
label: '企微微信客服链接',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'https://work.weixin.qq.com/kfid/kfc…',
|
||||||
|
description: 'C 端在线客服 kfid 链接;小程序需同时配置下方企业 ID',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'WECOM_CORP_ID',
|
||||||
|
label: '企微企业 ID(CorpID)',
|
||||||
|
group: G.wechat_mini,
|
||||||
|
type: 'string',
|
||||||
|
requiresRestart: false,
|
||||||
|
placeholder: 'wwxxxxxxxxxxxx',
|
||||||
|
description: '企业微信「我的企业」企业 ID。小程序须已关联该企业的微信客服;未填则回退小程序原生客服',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: 'PARTNER_ONBOARD_CS_QR_URL',
|
key: 'PARTNER_ONBOARD_CS_QR_URL',
|
||||||
label: '合伙人入驻 · 企微客服二维码',
|
label: '合伙人入驻 · 企微客服二维码',
|
||||||
@@ -584,6 +613,7 @@ export const SYSTEM_CONFIG_KEY_SET = new Set(SYSTEM_CONFIG_FIELDS.map((f) => f.k
|
|||||||
/** 表单空值时展示 / 启动补种的默认值(与 shared-types 常量对齐) */
|
/** 表单空值时展示 / 启动补种的默认值(与 shared-types 常量对齐) */
|
||||||
export const SYSTEM_CONFIG_DEFAULTS: Record<string, string> = {
|
export const SYSTEM_CONFIG_DEFAULTS: Record<string, string> = {
|
||||||
USER_H5_URL: DEFAULT_USER_H5_URL.replace(/\/$/, ''),
|
USER_H5_URL: DEFAULT_USER_H5_URL.replace(/\/$/, ''),
|
||||||
|
SHOP_H5_URL: DEFAULT_SHOP_H5_URL.replace(/\/$/, ''),
|
||||||
BRAND_LOGO_OSS_BASE: BRAND_LOGO_OSS_BASE,
|
BRAND_LOGO_OSS_BASE: BRAND_LOGO_OSS_BASE,
|
||||||
BRAND_LOGO_URL: BRAND_LOGO_URL,
|
BRAND_LOGO_URL: BRAND_LOGO_URL,
|
||||||
BRAND_LOGO_WIDE_URL: BRAND_LOGO_WIDE_URL,
|
BRAND_LOGO_WIDE_URL: BRAND_LOGO_WIDE_URL,
|
||||||
@@ -591,6 +621,7 @@ export const SYSTEM_CONFIG_DEFAULTS: Record<string, string> = {
|
|||||||
MINI_USER_STATIC_OSS_BASE: MINI_USER_STATIC_OSS_BASE,
|
MINI_USER_STATIC_OSS_BASE: MINI_USER_STATIC_OSS_BASE,
|
||||||
QUALIFICATION_DISCLOSURE_URL: QUALIFICATION_DISCLOSURE_URL,
|
QUALIFICATION_DISCLOSURE_URL: QUALIFICATION_DISCLOSURE_URL,
|
||||||
CUSTOMER_SERVICE_PHONE: CUSTOMER_SERVICE_PHONE,
|
CUSTOMER_SERVICE_PHONE: CUSTOMER_SERVICE_PHONE,
|
||||||
|
CUSTOMER_SERVICE_WECOM_URL: CUSTOMER_SERVICE_WECOM_URL,
|
||||||
MOCK_SMS_FIXED_CODE: MOCK_SMS_FIXED_CODE,
|
MOCK_SMS_FIXED_CODE: MOCK_SMS_FIXED_CODE,
|
||||||
SHARE_HINT: DEFAULT_SHARE_HINT,
|
SHARE_HINT: DEFAULT_SHARE_HINT,
|
||||||
SHARE_DEFAULT_TITLE: DEFAULT_SHARE_TITLE,
|
SHARE_DEFAULT_TITLE: DEFAULT_SHARE_TITLE,
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ export class ClientConfigController {
|
|||||||
brandLogoMarkUrl: brand.brandLogoMarkUrl,
|
brandLogoMarkUrl: brand.brandLogoMarkUrl,
|
||||||
qualificationDisclosureUrl: brand.qualificationDisclosureUrl,
|
qualificationDisclosureUrl: brand.qualificationDisclosureUrl,
|
||||||
customerServicePhone: brand.customerServicePhone,
|
customerServicePhone: brand.customerServicePhone,
|
||||||
|
customerServiceWecomUrl: brand.customerServiceWecomUrl || null,
|
||||||
|
wecomCorpId: brand.wecomCorpId || null,
|
||||||
partnerOnboardCsQrUrl: (env.PARTNER_ONBOARD_CS_QR_URL ?? '').trim() || null,
|
partnerOnboardCsQrUrl: (env.PARTNER_ONBOARD_CS_QR_URL ?? '').trim() || null,
|
||||||
partnerOnboardCsHint:
|
partnerOnboardCsHint:
|
||||||
(env.PARTNER_ONBOARD_CS_HINT ?? '').trim() ||
|
(env.PARTNER_ONBOARD_CS_HINT ?? '').trim() ||
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { DEFAULT_XFX_LOGISTICS_PRICING } from '@dukang/shared-types';
|
||||||
|
import { calcDeliveryFreightAmount } from './delivery-freight.util';
|
||||||
|
|
||||||
|
describe('calcDeliveryFreightAmount', () => {
|
||||||
|
it('瓶装按小飞侠默认计价:2瓶6元', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'LOCAL',
|
||||||
|
provider: 'XFX',
|
||||||
|
}),
|
||||||
|
).toBe(6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('箱装先换算瓶数:1箱6瓶=14元', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 1,
|
||||||
|
bottlesPerUnit: 6,
|
||||||
|
deliveryType: 'LOCAL',
|
||||||
|
provider: 'XFX',
|
||||||
|
}),
|
||||||
|
).toBe(14);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('现场提货不计运费', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'ON_SITE_PICKUP',
|
||||||
|
provider: 'XFX',
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无承运商计价时返回 null;有自定义规则则用之', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'CROSS_CITY',
|
||||||
|
provider: 'LOGISTICS',
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'CROSS_CITY',
|
||||||
|
provider: 'LOGISTICS',
|
||||||
|
pricing: { ...DEFAULT_XFX_LOGISTICS_PRICING },
|
||||||
|
}),
|
||||||
|
).toBe(6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('同城即使 provider=MANUAL 也按小飞侠默认计价', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'LOCAL',
|
||||||
|
provider: 'MANUAL',
|
||||||
|
}),
|
||||||
|
).toBe(6);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('城市小飞侠编码 ZZXFX 使用默认计价', () => {
|
||||||
|
expect(
|
||||||
|
calcDeliveryFreightAmount({
|
||||||
|
quantity: 4,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
deliveryType: 'LOCAL',
|
||||||
|
provider: 'MANUAL',
|
||||||
|
providerCode: 'ZZXFX',
|
||||||
|
}),
|
||||||
|
).toBe(10);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { calcLogisticsFeeByBottles, toBottleQuantity, type LogisticsPricingRule } from '@dukang/domain';
|
||||||
|
import { DEFAULT_XFX_LOGISTICS_PRICING, isXfxProviderCode } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
export type DeliveryFreightInput = {
|
||||||
|
quantity: number;
|
||||||
|
bottlesPerUnit?: number | null;
|
||||||
|
deliveryType?: string | null;
|
||||||
|
provider?: string | null;
|
||||||
|
providerCode?: string | null;
|
||||||
|
pricing?: LogisticsPricingRule | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 当次应付物流费:按瓶当量 + 承运商计价;现场提货 / 无规则返回 null */
|
||||||
|
export function calcDeliveryFreightAmount(input: DeliveryFreightInput): number | null {
|
||||||
|
if (input.deliveryType === 'ON_SITE_PICKUP') return null;
|
||||||
|
const bottles = toBottleQuantity(
|
||||||
|
input.quantity,
|
||||||
|
input.bottlesPerUnit && input.bottlesPerUnit > 0 ? input.bottlesPerUnit : 1,
|
||||||
|
);
|
||||||
|
if (bottles <= 0) return null;
|
||||||
|
const code = (input.providerCode || input.provider || '').trim();
|
||||||
|
const useDefaultXfx =
|
||||||
|
isXfxProviderCode(code) || (input.deliveryType === 'LOCAL' && code.toUpperCase() !== 'LOGISTICS');
|
||||||
|
const rule = input.pricing ?? (useDefaultXfx ? { ...DEFAULT_XFX_LOGISTICS_PRICING } : null);
|
||||||
|
if (!rule) return null;
|
||||||
|
try {
|
||||||
|
return calcLogisticsFeeByBottles(bottles, rule);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
DEFAULT_XFX_LOGISTICS_PRICING,
|
DEFAULT_XFX_LOGISTICS_PRICING,
|
||||||
isXfxProviderCode,
|
isXfxProviderCode,
|
||||||
|
sanitizeDeliveryHintHtml,
|
||||||
type LogisticsPricingRuleDto,
|
type LogisticsPricingRuleDto,
|
||||||
type XiaofeixiaProviderConfig,
|
type XiaofeixiaProviderConfig,
|
||||||
type XiaofeixiaProviderConfigPublic,
|
type XiaofeixiaProviderConfigPublic,
|
||||||
@@ -30,6 +31,7 @@ export type CreateFulfillmentProviderInput = {
|
|||||||
bankAccountNo?: string | null;
|
bankAccountNo?: string | null;
|
||||||
settlementMethod?: LogisticsSettlementMethod | string;
|
settlementMethod?: LogisticsSettlementMethod | string;
|
||||||
pricingRules?: LogisticsPricingRuleDto | null;
|
pricingRules?: LogisticsPricingRuleDto | null;
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type UpdateFulfillmentProviderInput = Partial<CreateFulfillmentProviderInput>;
|
export type UpdateFulfillmentProviderInput = Partial<CreateFulfillmentProviderInput>;
|
||||||
@@ -88,23 +90,22 @@ export class FulfillmentProviderService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 取第一个启用的小飞侠承运商配置(联调/兼容) */
|
/** 取第一个启用且凭证完整的小飞侠承运商配置(含 ZZXFX 等城市编码) */
|
||||||
async resolveDefaultXiaofeixiaConfig(): Promise<XiaofeixiaConfig | null> {
|
async resolveDefaultXiaofeixiaConfig(): Promise<XiaofeixiaConfig | null> {
|
||||||
const row = await this.prisma.fulfillmentProvider.findFirst({
|
const rows = await this.prisma.fulfillmentProvider.findMany({
|
||||||
where: {
|
where: { status: 'ACTIVE', type: 'API' },
|
||||||
status: 'ACTIVE',
|
|
||||||
type: 'API',
|
|
||||||
code: { in: ['XFX', 'XIAOFEIXIA'] },
|
|
||||||
},
|
|
||||||
orderBy: { updatedAt: 'desc' },
|
orderBy: { updatedAt: 'desc' },
|
||||||
});
|
});
|
||||||
if (!row?.configJson) return null;
|
for (const row of rows) {
|
||||||
|
if (!isXfxProviderCode(row.code) || !row.configJson) continue;
|
||||||
try {
|
try {
|
||||||
return await this.resolveXiaofeixiaConfig(row.id);
|
return await this.resolveXiaofeixiaConfig(row.id);
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
async create(input: CreateFulfillmentProviderInput) {
|
async create(input: CreateFulfillmentProviderInput) {
|
||||||
const code = input.code.trim().toUpperCase();
|
const code = input.code.trim().toUpperCase();
|
||||||
@@ -149,6 +150,7 @@ export class FulfillmentProviderService {
|
|||||||
bankAccountNo: this.normOptional(input.bankAccountNo),
|
bankAccountNo: this.normOptional(input.bankAccountNo),
|
||||||
settlementMethod,
|
settlementMethod,
|
||||||
pricingRulesJson,
|
pricingRulesJson,
|
||||||
|
deliveryHintHtml: sanitizeDeliveryHintHtml(input.deliveryHintHtml),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return this.toDto(row);
|
return this.toDto(row);
|
||||||
@@ -195,11 +197,43 @@ export class FulfillmentProviderService {
|
|||||||
? { settlementMethod: this.parseSettlementMethod(input.settlementMethod)! }
|
? { settlementMethod: this.parseSettlementMethod(input.settlementMethod)! }
|
||||||
: {}),
|
: {}),
|
||||||
...(pricingRulesJson !== undefined ? { pricingRulesJson } : {}),
|
...(pricingRulesJson !== undefined ? { pricingRulesJson } : {}),
|
||||||
|
...(input.deliveryHintHtml !== undefined
|
||||||
|
? { deliveryHintHtml: sanitizeDeliveryHintHtml(input.deliveryHintHtml) }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return this.toDto(row);
|
return this.toDto(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async remove(id: bigint) {
|
||||||
|
const current = await this.prisma.fulfillmentProvider.findUnique({ where: { id } });
|
||||||
|
if (!current) throw new NotFoundException('仓配承运商不存在');
|
||||||
|
|
||||||
|
const [billCount, ledgerCount] = await Promise.all([
|
||||||
|
this.prisma.logisticsBill.count({ where: { fulfillmentProviderId: id } }),
|
||||||
|
this.prisma.logisticsPrepaidLedger.count({ where: { fulfillmentProviderId: id } }),
|
||||||
|
]);
|
||||||
|
if (billCount > 0) {
|
||||||
|
throw new BadRequestException(`该承运商已有 ${billCount} 笔物流对账单,不能删除`);
|
||||||
|
}
|
||||||
|
if (ledgerCount > 0) {
|
||||||
|
throw new BadRequestException('该承运商已有充值/扣款流水,不能删除');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.$transaction(async (tx) => {
|
||||||
|
await tx.cityWarehouse.updateMany({
|
||||||
|
where: { fulfillmentProviderId: id },
|
||||||
|
data: { fulfillmentProviderId: null, fulfillmentMode: 'MANUAL' },
|
||||||
|
});
|
||||||
|
await tx.orderDelivery.updateMany({
|
||||||
|
where: { fulfillmentProviderId: id },
|
||||||
|
data: { fulfillmentProviderId: null },
|
||||||
|
});
|
||||||
|
await tx.fulfillmentProvider.delete({ where: { id } });
|
||||||
|
});
|
||||||
|
return { ok: true, id: id.toString() };
|
||||||
|
}
|
||||||
|
|
||||||
/** 充值(结算模块可复用) */
|
/** 充值(结算模块可复用) */
|
||||||
async rechargePrepaid(providerId: bigint, amount: number, remark?: string) {
|
async rechargePrepaid(providerId: bigint, amount: number, remark?: string) {
|
||||||
if (!(amount > 0)) throw new BadRequestException('充值金额须大于 0');
|
if (!(amount > 0)) throw new BadRequestException('充值金额须大于 0');
|
||||||
@@ -413,6 +447,7 @@ export class FulfillmentProviderService {
|
|||||||
settlementMethod?: string;
|
settlementMethod?: string;
|
||||||
pricingRulesJson?: string | null;
|
pricingRulesJson?: string | null;
|
||||||
prepaidBalance?: Prisma.Decimal | number;
|
prepaidBalance?: Prisma.Decimal | number;
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}) {
|
}) {
|
||||||
@@ -434,8 +469,61 @@ export class FulfillmentProviderService {
|
|||||||
settlementMethod: row.settlementMethod ?? 'PREPAID',
|
settlementMethod: row.settlementMethod ?? 'PREPAID',
|
||||||
pricingRules: this.parsePricingRules(row.pricingRulesJson ?? null),
|
pricingRules: this.parsePricingRules(row.pricingRulesJson ?? null),
|
||||||
prepaidBalance: Number(row.prepaidBalance ?? 0),
|
prepaidBalance: Number(row.prepaidBalance ?? 0),
|
||||||
|
deliveryHintHtml: sanitizeDeliveryHintHtml(row.deliveryHintHtml ?? null),
|
||||||
createdAt: row.createdAt.toISOString(),
|
createdAt: row.createdAt.toISOString(),
|
||||||
updatedAt: row.updatedAt.toISOString(),
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async listLocalDeliveries(filter?: { cityCode?: string; cityName?: string }) {
|
||||||
|
const cityCode = filter?.cityCode?.trim() || '';
|
||||||
|
const cityName = filter?.cityName?.trim() || '';
|
||||||
|
const cities = await this.prisma.commonCity.findMany({
|
||||||
|
where: {
|
||||||
|
status: 'ACTIVE',
|
||||||
|
...(cityCode ? { code: cityCode } : {}),
|
||||||
|
...(cityName && !cityCode
|
||||||
|
? { name: { in: this.cityNameAliases(cityName) } }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
warehouses: {
|
||||||
|
where: { status: 'ACTIVE' },
|
||||||
|
include: { fulfillmentProvider: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { name: 'asc' },
|
||||||
|
});
|
||||||
|
|
||||||
|
return cities.map((city) => {
|
||||||
|
const preferred =
|
||||||
|
city.warehouses.find((w) => w.fulfillmentMode === 'API_AUTO' && w.fulfillmentProviderId) ??
|
||||||
|
city.warehouses.find((w) => w.fulfillmentProviderId) ??
|
||||||
|
null;
|
||||||
|
const provider = preferred?.fulfillmentProvider ?? null;
|
||||||
|
return {
|
||||||
|
city: { id: city.id.toString(), code: city.code, name: city.name },
|
||||||
|
warehouse: preferred
|
||||||
|
? {
|
||||||
|
id: preferred.id.toString(),
|
||||||
|
name: preferred.name,
|
||||||
|
fulfillmentMode: preferred.fulfillmentMode,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
provider: provider
|
||||||
|
? { id: provider.id.toString(), code: provider.code, name: provider.name }
|
||||||
|
: null,
|
||||||
|
hintHtml: sanitizeDeliveryHintHtml(provider?.deliveryHintHtml ?? null),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private cityNameAliases(name: string): string[] {
|
||||||
|
const raw = name.trim();
|
||||||
|
if (!raw) return [];
|
||||||
|
const noSuffix = raw.replace(/市$/, '');
|
||||||
|
const withSuffix = raw.endsWith('市') ? raw : `${raw}市`;
|
||||||
|
return Array.from(new Set([raw, noSuffix, withSuffix]));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import { IntegrationsModule } from '../../integrations/integrations.module';
|
|||||||
import { TradeModule } from '../trade/trade.module';
|
import { TradeModule } from '../trade/trade.module';
|
||||||
import { FulfillmentProviderService } from './fulfillment-provider.service';
|
import { FulfillmentProviderService } from './fulfillment-provider.service';
|
||||||
import { FulfillmentService } from './fulfillment.service';
|
import { FulfillmentService } from './fulfillment.service';
|
||||||
|
import { LocalDeliveriesController } from './local-deliveries.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [IntegrationsModule, forwardRef(() => TradeModule)],
|
imports: [IntegrationsModule, forwardRef(() => TradeModule)],
|
||||||
|
controllers: [LocalDeliveriesController],
|
||||||
providers: [FulfillmentProviderService, FulfillmentService],
|
providers: [FulfillmentProviderService, FulfillmentService],
|
||||||
exports: [FulfillmentProviderService, FulfillmentService],
|
exports: [FulfillmentProviderService, FulfillmentService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
XFX_AUTO_DISPATCH_MAX_BOXES,
|
XFX_AUTO_DISPATCH_MAX_BOXES,
|
||||||
calcOrderBoxCount,
|
calcOrderBoxCount,
|
||||||
shouldHoldAutoCourierDispatch,
|
shouldHoldAutoCourierDispatch,
|
||||||
|
toBottleQuantity,
|
||||||
} 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';
|
||||||
@@ -15,6 +16,9 @@ import { OSS_PROVIDER } from '../../integrations/integrations.constants';
|
|||||||
import type { IOssProvider } from '../../integrations/oss/oss.interface';
|
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';
|
||||||
|
import { buildXfxGoodsPayload } from './xfx-goods.util';
|
||||||
|
|
||||||
|
type OrderForXfxDispatch = Order & { product?: { spec: string } | null };
|
||||||
|
|
||||||
export type ManualShipInput = {
|
export type ManualShipInput = {
|
||||||
logisticsCompany: string;
|
logisticsCompany: string;
|
||||||
@@ -42,7 +46,7 @@ export class FulfillmentService {
|
|||||||
async dispatchAfterPay(orderId: bigint) {
|
async dispatchAfterPay(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: true, product: { select: { spec: true } } },
|
||||||
});
|
});
|
||||||
if (!order || order.payStatus !== 'PAID') return;
|
if (!order || order.payStatus !== 'PAID') return;
|
||||||
|
|
||||||
@@ -77,7 +81,10 @@ export class FulfillmentService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 大单拦截:≥10 箱不自动推小飞侠,待总部确认后推单或自配送(按瓶当量)
|
// 大单拦截:≥10 箱不自动推小飞侠,待总部确认后推单或自配送(按瓶当量)
|
||||||
const bottleQty = order.quantity * (order.bottlesPerUnit > 0 ? order.bottlesPerUnit : 1);
|
const bottleQty = toBottleQuantity(
|
||||||
|
order.quantity,
|
||||||
|
order.bottlesPerUnit > 0 ? order.bottlesPerUnit : 1,
|
||||||
|
);
|
||||||
if (shouldHoldAutoCourierDispatch(bottleQty)) {
|
if (shouldHoldAutoCourierDispatch(bottleQty)) {
|
||||||
const boxes = calcOrderBoxCount(bottleQty);
|
const boxes = calcOrderBoxCount(bottleQty);
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
@@ -118,7 +125,7 @@ export class FulfillmentService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async dispatchApiAuto(order: Order, warehouse: CityWarehouse, provider: FulfillmentProvider) {
|
async dispatchApiAuto(order: OrderForXfxDispatch, warehouse: CityWarehouse, provider: FulfillmentProvider) {
|
||||||
if (!isXfxProviderCode(provider.code)) {
|
if (!isXfxProviderCode(provider.code)) {
|
||||||
this.logger.warn(`承运商 ${provider.code} 自动推单尚未实现,订单 ${order.orderNo} 保持待发货`);
|
this.logger.warn(`承运商 ${provider.code} 自动推单尚未实现,订单 ${order.orderNo} 保持待发货`);
|
||||||
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
await this.ensureDeliveryRecord(order.id, 'MANUAL', provider.id);
|
||||||
@@ -137,6 +144,13 @@ export class FulfillmentService {
|
|||||||
|
|
||||||
const fromLng = warehouse.lng != null ? Number(warehouse.lng) : 113.665;
|
const fromLng = warehouse.lng != null ? Number(warehouse.lng) : 113.665;
|
||||||
const fromLat = warehouse.lat != null ? Number(warehouse.lat) : 34.757;
|
const fromLat = warehouse.lat != null ? Number(warehouse.lat) : 34.757;
|
||||||
|
const { goodsName, goodsNum } = buildXfxGoodsPayload({
|
||||||
|
productName: order.productName,
|
||||||
|
productSpec: order.productSpec,
|
||||||
|
physicalSpec: order.product?.spec,
|
||||||
|
quantity: order.quantity,
|
||||||
|
bottlesPerUnit: order.bottlesPerUnit,
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await this.courier.createShipment(
|
const result = await this.courier.createShipment(
|
||||||
@@ -155,8 +169,8 @@ export class FulfillmentService {
|
|||||||
address: `${order.receiverProvince}${order.receiverCity}${order.receiverDistrict}`,
|
address: `${order.receiverProvince}${order.receiverCity}${order.receiverDistrict}`,
|
||||||
addressDetail: order.receiverAddress,
|
addressDetail: order.receiverAddress,
|
||||||
},
|
},
|
||||||
goodsName: order.productName,
|
goodsName,
|
||||||
goodsNum: order.quantity * (order.bottlesPerUnit > 0 ? order.bottlesPerUnit : 1),
|
goodsNum,
|
||||||
weight: 2,
|
weight: 2,
|
||||||
payMode: CourierPayMode.SENDER,
|
payMode: CourierPayMode.SENDER,
|
||||||
remark: `仓配自动发货 ${order.orderNo}`,
|
remark: `仓配自动发货 ${order.orderNo}`,
|
||||||
@@ -252,9 +266,13 @@ export class FulfillmentService {
|
|||||||
where: { id: orderId },
|
where: { id: orderId },
|
||||||
include: {
|
include: {
|
||||||
delivery: {
|
delivery: {
|
||||||
include: { signPhotoResource: true },
|
include: {
|
||||||
|
signPhotoResource: true,
|
||||||
|
fulfillmentProvider: { select: { id: true, code: true } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
fulfillmentWarehouse: { select: { fulfillmentProviderId: true } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const base = {
|
const base = {
|
||||||
nodes: [] as TrackNode[],
|
nodes: [] as TrackNode[],
|
||||||
@@ -264,35 +282,44 @@ export class FulfillmentService {
|
|||||||
provider: order?.delivery?.provider,
|
provider: order?.delivery?.provider,
|
||||||
trackingNo: order?.delivery?.trackingNo ?? null,
|
trackingNo: order?.delivery?.trackingNo ?? null,
|
||||||
logisticsCompany: order?.delivery?.logisticsCompany ?? null,
|
logisticsCompany: order?.delivery?.logisticsCompany ?? null,
|
||||||
|
queryError: null as string | null,
|
||||||
};
|
};
|
||||||
if (!order?.delivery) {
|
if (!order?.delivery) {
|
||||||
return base;
|
return base;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const providerCode = order.delivery.fulfillmentProvider?.code || String(order.delivery.provider || '');
|
||||||
const isXfx =
|
const isXfx =
|
||||||
order.delivery.provider === 'XFX' || isXfxProviderCode(String(order.delivery.provider || ''));
|
order.delivery.provider === 'XFX' ||
|
||||||
const canQueryCourier = isXfx && (order.delivery.trackingNo || order.orderNo);
|
isXfxProviderCode(providerCode) ||
|
||||||
|
order.deliveryType === 'LOCAL';
|
||||||
|
const canQueryCourier = isXfx && !!(order.delivery.trackingNo || order.orderNo);
|
||||||
|
|
||||||
if (canQueryCourier) {
|
if (canQueryCourier) {
|
||||||
try {
|
try {
|
||||||
const options = order.delivery.fulfillmentProviderId
|
const xiaofeixia = await this.resolveTrackXiaofeixiaConfig({
|
||||||
? {
|
delivery: order.delivery,
|
||||||
xiaofeixia: await this.fulfillmentProviderService.resolveXiaofeixiaConfig(
|
fulfillmentWarehouse: order.fulfillmentWarehouse,
|
||||||
order.delivery.fulfillmentProviderId,
|
});
|
||||||
),
|
const options = xiaofeixia ? { xiaofeixia } : undefined;
|
||||||
}
|
|
||||||
: undefined;
|
|
||||||
const shipmentQuery = {
|
const shipmentQuery = {
|
||||||
trackingNumber: order.delivery.trackingNo ?? undefined,
|
trackingNumber: order.delivery.trackingNo ?? undefined,
|
||||||
outNumber: order.orderNo,
|
outNumber: order.orderNo,
|
||||||
};
|
};
|
||||||
|
|
||||||
const [nodes, signPhotoDataUris] = await Promise.all([
|
const [trackResult, signPhotoDataUris] = await Promise.all([
|
||||||
this.courier.getTrack(shipmentQuery, options).catch(() => [] as TrackNode[]),
|
this.courier
|
||||||
|
.getTrack(shipmentQuery, options)
|
||||||
|
.then((nodes) => ({ nodes: Array.isArray(nodes) ? nodes : [], error: null as string | null }))
|
||||||
|
.catch((err: unknown) => ({
|
||||||
|
nodes: [] as TrackNode[],
|
||||||
|
error: err instanceof Error ? err.message : '查询路由失败',
|
||||||
|
})),
|
||||||
this.courier.getSignPhotos(shipmentQuery, options).catch(() => [] as string[]),
|
this.courier.getSignPhotos(shipmentQuery, options).catch(() => [] as string[]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
base.nodes = this.sortTrackNodesOldestFirst(nodes);
|
base.nodes = this.sortTrackNodesOldestFirst(trackResult.nodes);
|
||||||
|
base.queryError = trackResult.error;
|
||||||
base.signPhotoUrls = await this.resolveSignPhotoUrls(order, signPhotoDataUris);
|
base.signPhotoUrls = await this.resolveSignPhotoUrls(order, signPhotoDataUris);
|
||||||
|
|
||||||
if (this.shouldFetchEstimatedArrival(order.status, base.nodes)) {
|
if (this.shouldFetchEstimatedArrival(order.status, base.nodes)) {
|
||||||
@@ -309,8 +336,8 @@ export class FulfillmentService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (err) {
|
||||||
// fall through
|
base.queryError = err instanceof Error ? err.message : '查询路由失败';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -327,6 +354,28 @@ export class FulfillmentService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async resolveTrackXiaofeixiaConfig(order: {
|
||||||
|
delivery: { fulfillmentProviderId: bigint | null } | null;
|
||||||
|
fulfillmentWarehouse?: { fulfillmentProviderId: bigint | null } | null;
|
||||||
|
}): Promise<XiaofeixiaConfig | null> {
|
||||||
|
const ids = [
|
||||||
|
order.delivery?.fulfillmentProviderId,
|
||||||
|
order.fulfillmentWarehouse?.fulfillmentProviderId,
|
||||||
|
].filter((id): id is bigint => id != null);
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const id of ids) {
|
||||||
|
const key = String(id);
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
try {
|
||||||
|
return await this.fulfillmentProviderService.resolveXiaofeixiaConfig(id);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.fulfillmentProviderService.resolveDefaultXiaofeixiaConfig();
|
||||||
|
}
|
||||||
|
|
||||||
private sortTrackNodesOldestFirst(nodes: TrackNode[]): TrackNode[] {
|
private sortTrackNodesOldestFirst(nodes: TrackNode[]): TrackNode[] {
|
||||||
return [...nodes].sort((a, b) => {
|
return [...nodes].sort((a, b) => {
|
||||||
const ta = new Date(a.createTime).getTime();
|
const ta = new Date(a.createTime).getTime();
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Controller, Get, Query } from '@nestjs/common';
|
||||||
|
import { FulfillmentProviderService } from './fulfillment-provider.service';
|
||||||
|
|
||||||
|
@Controller('catalog')
|
||||||
|
export class LocalDeliveriesController {
|
||||||
|
constructor(private readonly providers: FulfillmentProviderService) {}
|
||||||
|
|
||||||
|
@Get('local-deliveries')
|
||||||
|
list(@Query('cityCode') cityCode?: string, @Query('cityName') cityName?: string) {
|
||||||
|
return this.providers.listLocalDeliveries({ cityCode, cityName });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { buildXfxGoodsPayload } from './xfx-goods.util';
|
||||||
|
|
||||||
|
describe('buildXfxGoodsPayload', () => {
|
||||||
|
it('瓶装:品名 + 酒精度,件数等于购买瓶数', () => {
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: '单瓶',
|
||||||
|
physicalSpec: '500ml | 53度',
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
goodsName: '杜康老窖 500ml | 53度 单瓶',
|
||||||
|
goodsNum: 2,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('箱装:追加包装规格,件数换算为瓶当量', () => {
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: '整箱',
|
||||||
|
physicalSpec: '500ml | 53度',
|
||||||
|
quantity: 2,
|
||||||
|
bottlesPerUnit: 6,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
goodsName: '杜康老窖 500ml | 53度 整箱',
|
||||||
|
goodsNum: 12,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无度数:回落 SKU 规格;再缺失则只用品名', () => {
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: '单瓶',
|
||||||
|
physicalSpec: null,
|
||||||
|
quantity: 3,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
goodsName: '杜康老窖 单瓶',
|
||||||
|
goodsNum: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: ' ',
|
||||||
|
physicalSpec: undefined,
|
||||||
|
quantity: 1,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
goodsName: '杜康老窖',
|
||||||
|
goodsNum: 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('规格重复:不把相同文案拼两次', () => {
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: '500ml | 53度',
|
||||||
|
physicalSpec: '500ml | 53度',
|
||||||
|
quantity: 1,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
goodsName: '杜康老窖 500ml | 53度',
|
||||||
|
goodsNum: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
buildXfxGoodsPayload({
|
||||||
|
productName: '杜康老窖',
|
||||||
|
productSpec: '53度',
|
||||||
|
physicalSpec: '500ml | 53度',
|
||||||
|
quantity: 1,
|
||||||
|
bottlesPerUnit: 1,
|
||||||
|
}).goodsName,
|
||||||
|
).toBe('杜康老窖 500ml | 53度');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { toBottleQuantity } from '@dukang/domain';
|
||||||
|
|
||||||
|
const GOODS_NAME_MAX_LEN = 128;
|
||||||
|
|
||||||
|
export type XfxGoodsInput = {
|
||||||
|
productName: string;
|
||||||
|
/** SKU 规格快照,如「单瓶 / 整箱」 */
|
||||||
|
productSpec?: string | null;
|
||||||
|
/** SPU 物理规格,如「500ml | 53度」 */
|
||||||
|
physicalSpec?: string | null;
|
||||||
|
quantity: number;
|
||||||
|
bottlesPerUnit: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type XfxGoodsPayload = {
|
||||||
|
goodsName: string;
|
||||||
|
goodsNum: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 小飞侠创建运单货品:品名+酒精度规格,件数用瓶当量 */
|
||||||
|
export function buildXfxGoodsPayload(input: XfxGoodsInput): XfxGoodsPayload {
|
||||||
|
const perUnit = input.bottlesPerUnit > 0 ? input.bottlesPerUnit : 1;
|
||||||
|
return {
|
||||||
|
goodsName: buildXfxGoodsName(input),
|
||||||
|
goodsNum: toBottleQuantity(input.quantity, perUnit),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildXfxGoodsName(input: XfxGoodsInput): string {
|
||||||
|
const name = trimSpec(input.productName);
|
||||||
|
const physical = trimSpec(input.physicalSpec);
|
||||||
|
const skuSpec = trimSpec(input.productSpec);
|
||||||
|
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (name) parts.push(name);
|
||||||
|
|
||||||
|
if (physical) {
|
||||||
|
parts.push(physical);
|
||||||
|
if (skuSpec && !isRedundantSpec(physical, skuSpec)) {
|
||||||
|
parts.push(skuSpec);
|
||||||
|
}
|
||||||
|
} else if (skuSpec) {
|
||||||
|
parts.push(skuSpec);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.join(' ').replace(/\s+/g, ' ').trim().slice(0, GOODS_NAME_MAX_LEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimSpec(raw?: string | null): string {
|
||||||
|
return (raw ?? '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRedundantSpec(physical: string, skuSpec: string): boolean {
|
||||||
|
const a = physical.replace(/\s+/g, '');
|
||||||
|
const b = skuSpec.replace(/\s+/g, '');
|
||||||
|
if (!b || a === b) return true;
|
||||||
|
return a.includes(b) || b.includes(a);
|
||||||
|
}
|
||||||
@@ -181,7 +181,12 @@ export class AdminDashboardService {
|
|||||||
: Promise.resolve(0),
|
: Promise.resolve(0),
|
||||||
can('deliveries')
|
can('deliveries')
|
||||||
? this.prisma.orderDelivery.count({
|
? this.prisma.orderDelivery.count({
|
||||||
where: cityFilter ? { order: { cityId: cityFilter } } : undefined,
|
where: {
|
||||||
|
order: {
|
||||||
|
deliveryType: { not: 'ON_SITE_PICKUP' },
|
||||||
|
...(cityFilter ? { cityId: cityFilter } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
})
|
})
|
||||||
: Promise.resolve(0),
|
: Promise.resolve(0),
|
||||||
can('finance')
|
can('finance')
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Body, Controller, Get, Param, Post, Put, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, Param, Post, Put, UseGuards } from '@nestjs/common';
|
||||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
@@ -47,6 +47,7 @@ export class AdminFulfillmentProvidersController {
|
|||||||
bankAccountNo: dto.bankAccountNo,
|
bankAccountNo: dto.bankAccountNo,
|
||||||
settlementMethod: dto.settlementMethod,
|
settlementMethod: dto.settlementMethod,
|
||||||
pricingRules: dto.pricingRules,
|
pricingRules: dto.pricingRules,
|
||||||
|
deliveryHintHtml: dto.deliveryHintHtml,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +77,7 @@ export class AdminFulfillmentProvidersController {
|
|||||||
bankAccountNo: dto.bankAccountNo,
|
bankAccountNo: dto.bankAccountNo,
|
||||||
settlementMethod: dto.settlementMethod,
|
settlementMethod: dto.settlementMethod,
|
||||||
pricingRules: dto.pricingRules,
|
pricingRules: dto.pricingRules,
|
||||||
|
deliveryHintHtml: dto.deliveryHintHtml,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,4 +91,14 @@ export class AdminFulfillmentProvidersController {
|
|||||||
recharge(@Param('id') id: string, @Body() dto: RechargeFulfillmentProviderDto) {
|
recharge(@Param('id') id: string, @Body() dto: RechargeFulfillmentProviderDto) {
|
||||||
return this.service.rechargePrepaid(BigInt(id), Number(dto.amount), dto.remark);
|
return this.service.rechargePrepaid(BigInt(id), Number(dto.amount), dto.remark);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.LOGISTICS_PROVIDER_DELETE,
|
||||||
|
refType: 'FULFILLMENT_PROVIDER',
|
||||||
|
refIdParam: 'id',
|
||||||
|
})
|
||||||
|
remove(@Param('id') id: string) {
|
||||||
|
return this.service.remove(BigInt(id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import type { AdminShipOrderDto, HqLogisticsShipDto } from './dto/admin-mutate.d
|
|||||||
import type { XiaofeixiaCreateShipmentDto } from './dto/admin-courier.dto';
|
import type { XiaofeixiaCreateShipmentDto } from './dto/admin-courier.dto';
|
||||||
import { FulfillmentService } from '../fulfillment/fulfillment.service';
|
import { FulfillmentService } from '../fulfillment/fulfillment.service';
|
||||||
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
||||||
|
import { buildXfxGoodsPayload } from '../fulfillment/xfx-goods.util';
|
||||||
|
import { calcDeliveryFreightAmount } from '../fulfillment/delivery-freight.util';
|
||||||
import { AdminRedeemService } from './admin-redeem.service';
|
import { AdminRedeemService } from './admin-redeem.service';
|
||||||
import {
|
import {
|
||||||
buildExportFilename,
|
buildExportFilename,
|
||||||
@@ -93,7 +95,16 @@ export class AdminOrdersService {
|
|||||||
take: pageSize,
|
take: pageSize,
|
||||||
include: {
|
include: {
|
||||||
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
|
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
|
||||||
delivery: { select: { provider: true, trackingNo: true, providerOrderNo: true } },
|
delivery: {
|
||||||
|
select: {
|
||||||
|
provider: true,
|
||||||
|
trackingNo: true,
|
||||||
|
providerOrderNo: true,
|
||||||
|
logisticsCompany: true,
|
||||||
|
manualQueryUrl: true,
|
||||||
|
fulfillmentProvider: { select: { code: true, pricingRulesJson: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
city: { select: { id: true, name: true, code: true } },
|
city: { select: { id: true, name: true, code: true } },
|
||||||
fulfillmentWarehouse: { select: { id: true, name: true } },
|
fulfillmentWarehouse: { select: { id: true, name: true } },
|
||||||
benefitCoupon: {
|
benefitCoupon: {
|
||||||
@@ -104,7 +115,12 @@ export class AdminOrdersService {
|
|||||||
this.prisma.order.count({ where }),
|
this.prisma.order.count({ where }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return serializeBigInt({ items, total, page, pageSize });
|
return serializeBigInt({
|
||||||
|
items: items.map((row) => this.withDeliveryLogisticsFee(row)),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async previewExport(dto: AdminOrdersExportDto) {
|
async previewExport(dto: AdminOrdersExportDto) {
|
||||||
@@ -240,7 +256,11 @@ export class AdminOrdersService {
|
|||||||
phoneVerifiedAt: true,
|
phoneVerifiedAt: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
delivery: true,
|
delivery: {
|
||||||
|
include: {
|
||||||
|
fulfillmentProvider: { select: { code: true, pricingRulesJson: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
benefitCoupon: {
|
benefitCoupon: {
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@@ -279,7 +299,8 @@ export class AdminOrdersService {
|
|||||||
? await this.adminRedeemService.buildCouponRedeemTrace(coupon)
|
? await this.adminRedeemService.buildCouponRedeemTrace(coupon)
|
||||||
: { redeemSummary: null, redeemRecords: [] };
|
: { redeemSummary: null, redeemRecords: [] };
|
||||||
|
|
||||||
const { benefitCoupon: _coupon, ...orderRest } = order;
|
const withFee = this.withDeliveryLogisticsFee(order);
|
||||||
|
const { benefitCoupon: _coupon, ...orderRest } = withFee;
|
||||||
|
|
||||||
return serializeBigInt(
|
return serializeBigInt(
|
||||||
mapOrderCompat({
|
mapOrderCompat({
|
||||||
@@ -320,6 +341,7 @@ export class AdminOrdersService {
|
|||||||
include: {
|
include: {
|
||||||
delivery: true,
|
delivery: true,
|
||||||
fulfillmentWarehouse: true,
|
fulfillmentWarehouse: true,
|
||||||
|
product: { select: { spec: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!order) throw new NotFoundException('订单不存在');
|
if (!order) throw new NotFoundException('订单不存在');
|
||||||
@@ -346,7 +368,7 @@ export class AdminOrdersService {
|
|||||||
});
|
});
|
||||||
order = await this.prisma.order.findUniqueOrThrow({
|
order = await this.prisma.order.findUniqueOrThrow({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: { delivery: true, fulfillmentWarehouse: true },
|
include: { delivery: true, fulfillmentWarehouse: true, product: { select: { spec: true } } },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -371,6 +393,13 @@ export class AdminOrdersService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const defaults = this.getShipDefaults(warehouse);
|
const defaults = this.getShipDefaults(warehouse);
|
||||||
|
const { goodsName, goodsNum } = buildXfxGoodsPayload({
|
||||||
|
productName: order.productName,
|
||||||
|
productSpec: order.productSpec,
|
||||||
|
physicalSpec: order.product?.spec,
|
||||||
|
quantity: order.quantity,
|
||||||
|
bottlesPerUnit: order.bottlesPerUnit,
|
||||||
|
});
|
||||||
const shipmentDto: XiaofeixiaCreateShipmentDto = {
|
const shipmentDto: XiaofeixiaCreateShipmentDto = {
|
||||||
outNumber: order.orderNo,
|
outNumber: order.orderNo,
|
||||||
fromName: dto.fromName || defaults.fromName,
|
fromName: dto.fromName || defaults.fromName,
|
||||||
@@ -383,8 +412,8 @@ export class AdminOrdersService {
|
|||||||
toMobile: order.receiverPhone,
|
toMobile: order.receiverPhone,
|
||||||
toAddress: `${order.receiverProvince}${order.receiverCity}${order.receiverDistrict}`,
|
toAddress: `${order.receiverProvince}${order.receiverCity}${order.receiverDistrict}`,
|
||||||
toAddressDetail: order.receiverAddress,
|
toAddressDetail: order.receiverAddress,
|
||||||
goodsName: order.productName,
|
goodsName,
|
||||||
goodsNum: order.quantity,
|
goodsNum,
|
||||||
weight: dto.weight ?? defaults.weight,
|
weight: dto.weight ?? defaults.weight,
|
||||||
payMode: dto.payMode || defaults.payMode,
|
payMode: dto.payMode || defaults.payMode,
|
||||||
remark: dto.remark || `HQ发货 ${order.orderNo}`,
|
remark: dto.remark || `HQ发货 ${order.orderNo}`,
|
||||||
@@ -433,6 +462,34 @@ export class AdminOrdersService {
|
|||||||
return this.detail(id);
|
return this.detail(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private withDeliveryLogisticsFee<
|
||||||
|
T extends {
|
||||||
|
quantity: number;
|
||||||
|
bottlesPerUnit: number;
|
||||||
|
deliveryType: string;
|
||||||
|
delivery?: {
|
||||||
|
provider: string;
|
||||||
|
fulfillmentProvider?: { code: string; pricingRulesJson: string | null } | null;
|
||||||
|
} | null;
|
||||||
|
},
|
||||||
|
>(order: T): T {
|
||||||
|
if (!order.delivery) return order;
|
||||||
|
const fp = order.delivery.fulfillmentProvider;
|
||||||
|
const logisticsFee = calcDeliveryFreightAmount({
|
||||||
|
quantity: order.quantity,
|
||||||
|
bottlesPerUnit: order.bottlesPerUnit,
|
||||||
|
deliveryType: order.deliveryType,
|
||||||
|
provider: order.delivery.provider,
|
||||||
|
providerCode: fp?.code,
|
||||||
|
pricing: this.fulfillmentProviderService.parsePricingRules(fp?.pricingRulesJson ?? null),
|
||||||
|
});
|
||||||
|
const { fulfillmentProvider: _fp, ...deliveryRest } = order.delivery;
|
||||||
|
return {
|
||||||
|
...order,
|
||||||
|
delivery: { ...deliveryRest, logisticsFee },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
getShipDefaults(warehouse?: {
|
getShipDefaults(warehouse?: {
|
||||||
contactName: string;
|
contactName: string;
|
||||||
contactPhone: string;
|
contactPhone: string;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { Prisma } from '@prisma/client';
|
|||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { loadStorePrimaryBank } from '../../common/store/store-bank.util';
|
import { loadStorePrimaryBank } from '../../common/store/store-bank.util';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
|
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
||||||
|
import { calcDeliveryFreightAmount } from '../fulfillment/delivery-freight.util';
|
||||||
import type { AdminDeliveriesQueryDto, AdminRedeemRecordsQueryDto } from './dto/admin-query.dto';
|
import type { AdminDeliveriesQueryDto, AdminRedeemRecordsQueryDto } from './dto/admin-query.dto';
|
||||||
import type { UpdateDeliveryDto } from './dto/admin-mutate.dto';
|
import type { UpdateDeliveryDto } from './dto/admin-mutate.dto';
|
||||||
|
|
||||||
@@ -334,18 +336,45 @@ export class AdminRedeemService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deliveryOrderSelect = {
|
||||||
|
id: true,
|
||||||
|
orderNo: true,
|
||||||
|
status: true,
|
||||||
|
deliveryType: true,
|
||||||
|
productName: true,
|
||||||
|
productSpec: true,
|
||||||
|
barcode69: true,
|
||||||
|
quantity: true,
|
||||||
|
saleUnit: true,
|
||||||
|
bottlesPerUnit: true,
|
||||||
|
payAmount: true,
|
||||||
|
receiverName: true,
|
||||||
|
receiverPhone: true,
|
||||||
|
receiverAddress: true,
|
||||||
|
receiverProvince: true,
|
||||||
|
receiverCity: true,
|
||||||
|
receiverDistrict: true,
|
||||||
|
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
|
||||||
|
imageResource: { select: { url: true } },
|
||||||
|
} satisfies Prisma.OrderSelect;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminDeliveriesService {
|
export class AdminDeliveriesService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
||||||
|
) {}
|
||||||
|
|
||||||
async list(query: AdminDeliveriesQueryDto) {
|
async list(query: AdminDeliveriesQueryDto) {
|
||||||
const page = query.page ?? 1;
|
const page = query.page ?? 1;
|
||||||
const pageSize = query.pageSize ?? 20;
|
const pageSize = query.pageSize ?? 20;
|
||||||
const where: Prisma.OrderDeliveryWhereInput = {};
|
const where: Prisma.OrderDeliveryWhereInput = {
|
||||||
|
order: { deliveryType: { not: 'ON_SITE_PICKUP' } },
|
||||||
|
};
|
||||||
if (query.provider) where.provider = query.provider as DeliveryProvider;
|
if (query.provider) where.provider = query.provider as DeliveryProvider;
|
||||||
if (query.trackingNo) where.trackingNo = { contains: query.trackingNo };
|
if (query.trackingNo) where.trackingNo = { contains: query.trackingNo };
|
||||||
if (query.orderNo) {
|
if (query.orderNo) {
|
||||||
where.order = { orderNo: { contains: query.orderNo } };
|
where.order = { deliveryType: { not: 'ON_SITE_PICKUP' }, orderNo: { contains: query.orderNo } };
|
||||||
}
|
}
|
||||||
|
|
||||||
const [items, total] = await Promise.all([
|
const [items, total] = await Promise.all([
|
||||||
@@ -355,39 +384,53 @@ export class AdminDeliveriesService {
|
|||||||
skip: (page - 1) * pageSize,
|
skip: (page - 1) * pageSize,
|
||||||
take: pageSize,
|
take: pageSize,
|
||||||
include: {
|
include: {
|
||||||
order: {
|
order: { select: deliveryOrderSelect },
|
||||||
select: {
|
fulfillmentProvider: { select: { code: true, pricingRulesJson: true } },
|
||||||
id: true,
|
|
||||||
orderNo: true,
|
|
||||||
status: true,
|
|
||||||
receiverName: true,
|
|
||||||
receiverPhone: true,
|
|
||||||
deliveryType: true,
|
|
||||||
productName: true,
|
|
||||||
quantity: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
this.prisma.orderDelivery.count({ where }),
|
this.prisma.orderDelivery.count({ where }),
|
||||||
]);
|
]);
|
||||||
return serializeBigInt({ items, total, page, pageSize });
|
return serializeBigInt({
|
||||||
|
items: items.map((row) => this.withLogisticsFee(row)),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async detail(id: bigint) {
|
async detail(id: bigint) {
|
||||||
const delivery = await this.prisma.orderDelivery.findUnique({
|
const delivery = await this.prisma.orderDelivery.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
order: {
|
order: { select: deliveryOrderSelect },
|
||||||
include: {
|
fulfillmentProvider: { select: { code: true, pricingRulesJson: true } },
|
||||||
user: { select: { id: true, userNo: true, phone: true } },
|
|
||||||
imageResource: { select: { url: true } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!delivery) throw new NotFoundException('配送单不存在');
|
if (!delivery) throw new NotFoundException('配送单不存在');
|
||||||
return serializeBigInt(delivery);
|
return serializeBigInt(this.withLogisticsFee(delivery));
|
||||||
|
}
|
||||||
|
|
||||||
|
private withLogisticsFee<
|
||||||
|
T extends {
|
||||||
|
provider: string;
|
||||||
|
order: { quantity: number; bottlesPerUnit: number; deliveryType: string };
|
||||||
|
fulfillmentProvider?: { code: string; pricingRulesJson: string | null } | null;
|
||||||
|
},
|
||||||
|
>(row: T) {
|
||||||
|
const { fulfillmentProvider, ...rest } = row;
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
logisticsFee: calcDeliveryFreightAmount({
|
||||||
|
quantity: row.order.quantity,
|
||||||
|
bottlesPerUnit: row.order.bottlesPerUnit,
|
||||||
|
deliveryType: row.order.deliveryType,
|
||||||
|
provider: row.provider,
|
||||||
|
providerCode: fulfillmentProvider?.code,
|
||||||
|
pricing: this.fulfillmentProviderService.parsePricingRules(
|
||||||
|
fulfillmentProvider?.pricingRulesJson ?? null,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(id: bigint, dto: UpdateDeliveryDto) {
|
async update(id: bigint, dto: UpdateDeliveryDto) {
|
||||||
|
|||||||
@@ -797,6 +797,11 @@ export class CreateFulfillmentProviderDto {
|
|||||||
boxBottles?: number;
|
boxBottles?: number;
|
||||||
boxFee?: number;
|
boxFee?: number;
|
||||||
} | null;
|
} | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateFulfillmentProviderDto {
|
export class UpdateFulfillmentProviderDto {
|
||||||
@@ -859,6 +864,11 @@ export class UpdateFulfillmentProviderDto {
|
|||||||
boxBottles?: number;
|
boxBottles?: number;
|
||||||
boxFee?: number;
|
boxFee?: number;
|
||||||
} | null;
|
} | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(2000)
|
||||||
|
deliveryHintHtml?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class RechargeFulfillmentProviderDto {
|
export class RechargeFulfillmentProviderDto {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
allocateBenefitCoupons,
|
allocateBenefitCoupons,
|
||||||
} from '@dukang/domain';
|
} from '@dukang/domain';
|
||||||
import {
|
import {
|
||||||
|
buildShopRedeemLandingUrl,
|
||||||
ClientApp,
|
ClientApp,
|
||||||
REDEEM_PENDING_SNAPSHOT_TTL_SECONDS,
|
REDEEM_PENDING_SNAPSHOT_TTL_SECONDS,
|
||||||
REDEEM_PHONE_SESSION_TTL_SECONDS,
|
REDEEM_PHONE_SESSION_TTL_SECONDS,
|
||||||
@@ -24,6 +25,7 @@ import {
|
|||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { RedisService } from '../../common/redis/redis.service';
|
import { RedisService } from '../../common/redis/redis.service';
|
||||||
|
import { SystemConfigService } from '../../common/system-config/system-config.service';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { AnalyticsService } from '../analytics/analytics.service';
|
import { AnalyticsService } from '../analytics/analytics.service';
|
||||||
import { SettlementService } from '../settlement/settlement.service';
|
import { SettlementService } from '../settlement/settlement.service';
|
||||||
@@ -84,6 +86,7 @@ export class RedeemService {
|
|||||||
private readonly authService: AuthService,
|
private readonly authService: AuthService,
|
||||||
private readonly payRedeemAnomaly: PayRedeemAnomalyService,
|
private readonly payRedeemAnomaly: PayRedeemAnomalyService,
|
||||||
private readonly wecomPush: WecomMessagePushService,
|
private readonly wecomPush: WecomMessagePushService,
|
||||||
|
private readonly systemConfig: SystemConfigService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private maskPhoneForStore(phone: string) {
|
private maskPhoneForStore(phone: string) {
|
||||||
@@ -576,7 +579,13 @@ export class RedeemService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return { token, expireAt, amount: body.amount, boundStoreId: body.storeId ?? null };
|
return {
|
||||||
|
token,
|
||||||
|
expireAt,
|
||||||
|
amount: body.amount,
|
||||||
|
boundStoreId: body.storeId ?? null,
|
||||||
|
landingUrl: buildShopRedeemLandingUrl(this.systemConfig.getAppConfig().shopH5Url, token),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async getToken(token: string) {
|
async getToken(token: string) {
|
||||||
|
|||||||
@@ -243,8 +243,7 @@ export class StorePackageService {
|
|||||||
await this.hqPermissions.assertStoreIdInScope(actorId, storeId);
|
await this.hqPermissions.assertStoreIdInScope(actorId, storeId);
|
||||||
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
const store = await this.prisma.store.findUnique({ where: { id: storeId } });
|
||||||
if (!store) throw new NotFoundException('门店不存在');
|
if (!store) throw new NotFoundException('门店不存在');
|
||||||
const live = await this.listLivePackages(storeId);
|
return this.getPackagesWithPending(storeId);
|
||||||
return serializeBigInt({ live });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async adminDirectSave(storeId: bigint, packages: StorePackageItemDto[], actorId: bigint) {
|
async adminDirectSave(storeId: bigint, packages: StorePackageItemDto[], actorId: bigint) {
|
||||||
|
|||||||
@@ -465,9 +465,11 @@ export class TradeService {
|
|||||||
operator: 'MOCK_PAY',
|
operator: 'MOCK_PAY',
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
if (order.deliveryType !== 'ON_SITE_PICKUP') {
|
||||||
await tx.orderDelivery.create({
|
await tx.orderDelivery.create({
|
||||||
data: { orderId: order.id, provider: 'MANUAL' },
|
data: { orderId: order.id, provider: 'MANUAL' },
|
||||||
});
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.afterOrderPaid(order.id);
|
await this.afterOrderPaid(order.id);
|
||||||
@@ -516,6 +518,12 @@ export class TradeService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (order.deliveryType === 'ON_SITE_PICKUP') {
|
||||||
|
// 现场取货:支付即完成,不建配送单、不推仓配
|
||||||
|
this.wechatOrderShipping.uploadForOrderSafe(orderId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const delivery = await this.prisma.orderDelivery.findUnique({ where: { orderId } });
|
const delivery = await this.prisma.orderDelivery.findUnique({ where: { orderId } });
|
||||||
if (!delivery) {
|
if (!delivery) {
|
||||||
await this.prisma.orderDelivery.create({
|
await this.prisma.orderDelivery.create({
|
||||||
@@ -523,12 +531,6 @@ export class TradeService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (order.deliveryType === 'ON_SITE_PICKUP') {
|
|
||||||
// 现场取货:支付后即向微信录入「用户自提」发货信息
|
|
||||||
this.wechatOrderShipping.uploadForOrderSafe(orderId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.fulfillmentService.dispatchAfterPay(orderId);
|
await this.fulfillmentService.dispatchAfterPay(orderId);
|
||||||
const refreshed = await this.prisma.order.findUnique({ where: { id: orderId } });
|
const refreshed = await this.prisma.order.findUnique({ where: { id: orderId } });
|
||||||
if (refreshed?.status === 'PENDING_SHIP') {
|
if (refreshed?.status === 'PENDING_SHIP') {
|
||||||
@@ -619,12 +621,14 @@ export class TradeService {
|
|||||||
operator: 'WECHAT_PAY',
|
operator: 'WECHAT_PAY',
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
if (order.deliveryType !== 'ON_SITE_PICKUP') {
|
||||||
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
||||||
if (!delivery) {
|
if (!delivery) {
|
||||||
await tx.orderDelivery.create({
|
await tx.orderDelivery.create({
|
||||||
data: { orderId: order.id, provider: 'MANUAL' },
|
data: { orderId: order.id, provider: 'MANUAL' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const refreshed = await this.prisma.order.findUnique({ where: { id: order.id } });
|
const refreshed = await this.prisma.order.findUnique({ where: { id: order.id } });
|
||||||
@@ -2625,12 +2629,14 @@ export class TradeService {
|
|||||||
operator,
|
operator,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
if (order.deliveryType !== 'ON_SITE_PICKUP') {
|
||||||
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
const delivery = await tx.orderDelivery.findUnique({ where: { orderId: order.id } });
|
||||||
if (!delivery) {
|
if (!delivery) {
|
||||||
await tx.orderDelivery.create({
|
await tx.orderDelivery.create({
|
||||||
data: { orderId: order.id, provider: 'MANUAL' },
|
data: { orderId: order.id, provider: 'MANUAL' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.afterOrderPaid(order.id);
|
await this.afterOrderPaid(order.id);
|
||||||
|
|||||||
@@ -19,5 +19,6 @@
|
|||||||
"forceConsistentCasingInFileNames": false,
|
"forceConsistentCasingInFileNames": false,
|
||||||
"noFallthroughCasesInSwitch": false
|
"noFallthroughCasesInSwitch": false
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"]
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["src/**/*.test.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user