Compare commits

...

3 Commits

Author SHA1 Message Date
jacy e0d3c840a2 feat(ops): show order redeem records including FIFO secondary coupons
CI / verify (pull_request) Has been cancelled
Persist redeem allocations and surface them on HQ order detail with backfill for history.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-22 23:38:51 +08:00
jacy f2303f7fb8 核销金额:最低 0.01 元;输入最多两位小数;低于该值会 toast 提示,无法生成核销码。
底部提示:左右留白 + 内边距,浅底圆角块,文案改为最低 0.01、余额上限、3 分钟到店出示。
新增地址:进入页会尝试定位,自动选中当前省市区(失败则保留默认郑州);编辑地址不重定位。
2026-07-22 23:11:34 +08:00
jacy fb530e2ff5 城市合伙人县区不做限制 2026-07-22 23:06:51 +08:00
15 changed files with 668 additions and 73 deletions
@@ -26,7 +26,7 @@ import {
type PartnerPermissionKey,
} from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api';
import { districtCodeLabel } from '../lib/china-region';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { fmtTime } from '../lib/constants';
import CityDistrictMultiSelect from './CityDistrictMultiSelect';
import PartnerSubAccountList from './PartnerSubAccountList';
@@ -37,6 +37,7 @@ type PartnerRow = {
phone: string;
name: string;
scopeType?: string;
districtCodes?: string[] | null;
orderCommissionRate?: number;
redeemCommissionRate?: number;
accountCount: number;
@@ -211,6 +212,14 @@ export default function CityPartnersPanel({
const columns: ColumnsType<PartnerRow> = [
{ title: '公司名', dataIndex: 'companyName', ellipsis: true },
{
title: '区县',
dataIndex: 'districtCodes',
width: 160,
ellipsis: true,
render: (codes: string[] | null | undefined, row) =>
row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes),
},
{ title: '主账号', dataIndex: 'phone', width: 120 },
{
title: '管辖',
@@ -287,7 +296,7 @@ export default function CityPartnersPanel({
<Form.Item
name="districtCodes"
label="区县"
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={cityCode} />
</Form.Item>
@@ -386,7 +395,7 @@ export default function CityPartnersPanel({
name="districtCodes"
label="区县"
rules={[{ required: true, message: '请选择至少一个区县' }]}
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={cityCode} />
</Form.Item>
+6
View File
@@ -106,6 +106,12 @@ export function districtCodeLabel(code: string): string {
return codeToText[code] || code;
}
/** 列表展示:区县码 → 中文名,顿号拼接 */
export function formatDistrictLabels(codes?: string[] | null): string {
if (!codes?.length) return '—';
return codes.map((c) => districtCodeLabel(String(c))).join('、');
}
export function parseRegionCodes(codes?: string[]): ParsedChinaRegion | null {
if (!codes || codes.length < 3) return null;
const [provinceCode, cityCode, districtCode] = codes;
+13 -4
View File
@@ -31,7 +31,7 @@ import {
type PartnerPermissionKey,
} from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api';
import { districtCodeLabel } from '../lib/china-region';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect';
@@ -48,6 +48,7 @@ type Row = {
cityId?: string | null;
cityName?: string | null;
scopeType?: string;
districtCodes?: string[] | null;
orderCommissionRate?: number;
redeemCommissionRate?: number;
bindingStatus?: string;
@@ -259,7 +260,15 @@ export default function CityPartnersPage() {
}
const columns: ColumnsType<Row> = [
{ title: '公司名', dataIndex: 'companyName', ellipsis: true },
{ title: '公司名', dataIndex: 'companyName', ellipsis: true, width: 140 },
{
title: '区县',
dataIndex: 'districtCodes',
width: 160,
ellipsis: true,
render: (codes: string[] | null | undefined, row) =>
row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes),
},
{ title: '城市', dataIndex: 'cityName', width: 90 },
{ title: '主账号姓名', dataIndex: 'name', width: 100, ellipsis: true },
{ title: '登录手机', dataIndex: 'phone', width: 120 },
@@ -476,7 +485,7 @@ export default function CityPartnersPage() {
<Form.Item
name="districtCodes"
label="区县"
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={editCityCode} />
</Form.Item>
@@ -591,7 +600,7 @@ export default function CityPartnersPage() {
name="districtCodes"
label="区县"
rules={[{ required: true, message: '请选择至少一个区县' }]}
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={createCityCode} />
</Form.Item>
+223 -1
View File
@@ -55,6 +55,28 @@ type WarehouseOption = {
lat?: number | null;
};
type OrderRedeemRecord = {
id: string;
redeemNo: string;
amount: number;
settleAmount: number;
/** 本单权益券在该核销单中的分摊额 */
couponAmount?: number;
role?: 'PRIMARY' | 'SECONDARY';
createdAt: string;
store?: { id: string; name: string; cityName?: string | null } | null;
};
type OrderRedeemSummary = {
couponNo: string;
totalAmount: number;
usedAmount: number;
balance: number;
status: string;
redeemCount: number;
redeemRecordSum: number;
};
type OrderDetail = AdminOrderRow & {
receiverAddress?: string;
receiverProvince?: string;
@@ -81,6 +103,8 @@ type OrderDetail = AdminOrderRow & {
payment?: Record<string, unknown> | null;
statusLogs?: Array<{ fromStatus: string | null; toStatus: string; createdAt: string }>;
benefitCoupons?: Array<Record<string, unknown>>;
redeemSummary?: OrderRedeemSummary | null;
redeemRecords?: OrderRedeemRecord[];
fulfillmentWarehouse?: {
id: string;
name: string;
@@ -135,6 +159,9 @@ export default function OrdersPage() {
const [pageSize, setPageSize] = useState(20);
const [detail, setDetail] = useState<OrderDetail | null>(null);
const [drawerOpen, setDrawerOpen] = useState(false);
const [redeemDetail, setRedeemDetail] = useState<Record<string, unknown> | null>(null);
const [redeemDrawerOpen, setRedeemDrawerOpen] = useState(false);
const [redeemDetailLoading, setRedeemDetailLoading] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
const [batchDeleteOpen, setBatchDeleteOpen] = useState(false);
const [batchDeleting, setBatchDeleting] = useState(false);
@@ -152,6 +179,20 @@ export default function OrdersPage() {
[data?.items, selectedRowKeys],
);
async function openRedeemDetail(redeemId: string) {
setRedeemDetailLoading(true);
setRedeemDrawerOpen(true);
try {
const res = await request<Record<string, unknown>>(`/admin/redeem-records/${redeemId}`);
setRedeemDetail(res);
} catch (e) {
message.error(e instanceof Error ? e.message : '加载核销详情失败');
setRedeemDrawerOpen(false);
} finally {
setRedeemDetailLoading(false);
}
}
const load = useCallback(async () => {
setLoading(true);
try {
@@ -468,7 +509,7 @@ export default function OrdersPage() {
<Drawer
title="订单详情"
width={640}
width={720}
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
extra={detail && (
@@ -570,6 +611,98 @@ export default function OrdersPage() {
<Descriptions.Item label="地址">{detail.receiverAddress}</Descriptions.Item>
</Descriptions>
<Typography.Title level={5} style={{ marginTop: 16, marginBottom: 8 }}>
</Typography.Title>
{detail.redeemSummary ? (
<>
<Descriptions column={2} bordered size="small" style={{ marginBottom: 12 }}>
<Descriptions.Item label="权益券号">{detail.redeemSummary.couponNo}</Descriptions.Item>
<Descriptions.Item label="券状态">{detail.redeemSummary.status}</Descriptions.Item>
<Descriptions.Item label="权益总额">
¥{Number(detail.redeemSummary.totalAmount).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="已核销">
<Typography.Text type="danger" strong>
¥{Number(detail.redeemSummary.usedAmount).toFixed(2)}
</Typography.Text>
<Typography.Text type="secondary" style={{ marginLeft: 8 }}>
{detail.redeemSummary.redeemCount}
</Typography.Text>
</Descriptions.Item>
<Descriptions.Item label="剩余余额">
¥{Number(detail.redeemSummary.balance).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="核销单合计额">
¥{Number(detail.redeemSummary.redeemRecordSum).toFixed(2)}
<Typography.Text type="secondary" style={{ marginLeft: 8 }}>
</Typography.Text>
</Descriptions.Item>
</Descriptions>
<Table
size="small"
rowKey="id"
pagination={false}
locale={{ emptyText: '暂无关联核销单' }}
dataSource={detail.redeemRecords ?? []}
columns={[
{ title: '核销号', dataIndex: 'redeemNo', width: 160, ellipsis: true },
{
title: '角色',
dataIndex: 'role',
width: 70,
render: (v: string | undefined) =>
v === 'SECONDARY' ? <Tag color="orange"></Tag> : <Tag color="blue"></Tag>,
},
{
title: '门店',
dataIndex: ['store', 'name'],
ellipsis: true,
render: (v: string | undefined, row) =>
v ? `${v}${row.store?.cityName ? `${row.store.cityName}` : ''}` : '—',
},
{
title: '本券分摊',
dataIndex: 'couponAmount',
width: 95,
render: (v: number | undefined, row) =>
`¥${Number(v ?? row.amount).toFixed(2)}`,
},
{
title: '核销总额',
dataIndex: 'amount',
width: 90,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '结算额',
dataIndex: 'settleAmount',
width: 90,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '时间',
dataIndex: 'createdAt',
width: 150,
render: (v: string) => fmtTime(v),
},
{
title: '操作',
width: 70,
render: (_, row) => (
<Button type="link" size="small" onClick={() => void openRedeemDetail(row.id)}>
</Button>
),
},
]}
/>
</>
) : (
<Typography.Text type="secondary"></Typography.Text>
)}
<Descriptions column={1} bordered size="small" title="位置快照(方案C" style={{ marginTop: 16 }}>
<Descriptions.Item label="clientIp">{detail.clientIp || '—'}</Descriptions.Item>
<Descriptions.Item label="IP解析">{[detail.ipProvince, detail.ipCity, detail.ipDistrict].filter(Boolean).join(' / ') || '—'}</Descriptions.Item>
@@ -618,6 +751,95 @@ export default function OrdersPage() {
)}
</Drawer>
<Drawer
title="核销单详情"
width={520}
open={redeemDrawerOpen}
onClose={() => {
setRedeemDrawerOpen(false);
setRedeemDetail(null);
}}
destroyOnClose
>
{redeemDetailLoading ? (
<Typography.Text type="secondary"></Typography.Text>
) : redeemDetail ? (
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="核销号">{String(redeemDetail.redeemNo ?? '—')}</Descriptions.Item>
<Descriptions.Item label="核销额">
¥{Number(redeemDetail.amount ?? 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="结算额">
¥{Number(redeemDetail.settleAmount ?? 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(String(redeemDetail.createdAt ?? ''))}</Descriptions.Item>
<Descriptions.Item label="用户">
{String((redeemDetail.user as { userNo?: string } | undefined)?.userNo ?? '—')}
{(redeemDetail.user as { phone?: string | null } | undefined)?.phone
? ` / ${(redeemDetail.user as { phone?: string | null }).phone}`
: ''}
</Descriptions.Item>
<Descriptions.Item label="门店">
{String((redeemDetail.store as { name?: string } | undefined)?.name ?? '—')}
{(redeemDetail.store as { cityName?: string } | undefined)?.cityName
? `${(redeemDetail.store as { cityName?: string }).cityName}`
: ''}
</Descriptions.Item>
<Descriptions.Item label="门店地址">
{String((redeemDetail.store as { address?: string } | undefined)?.address ?? '—')}
</Descriptions.Item>
<Descriptions.Item label="合伙人">
{String(
(redeemDetail.store as { partnerAccount?: { companyName?: string } } | undefined)
?.partnerAccount?.companyName ?? '—',
)}
</Descriptions.Item>
<Descriptions.Item label="权益券号">
{String((redeemDetail.coupon as { couponNo?: string } | undefined)?.couponNo ?? '—')}
</Descriptions.Item>
<Descriptions.Item label="关联订单">
{String(
(redeemDetail.coupon as { order?: { orderNo?: string } } | undefined)?.order?.orderNo ??
'—',
)}
</Descriptions.Item>
{Array.isArray(redeemDetail.allocations) &&
(redeemDetail.allocations as unknown[]).length > 0 ? (
<Descriptions.Item label="券分摊">
{(
redeemDetail.allocations as Array<{
couponNo?: string;
orderNo?: string | null;
amount?: number;
sortOrder?: number;
}>
)
.map((a, idx) => {
const role = idx === 0 ? '主' : '次';
return `${role} ${a.couponNo ?? '—'}¥${Number(a.amount ?? 0).toFixed(2)}${
a.orderNo ? `(订单 ${a.orderNo}` : ''
}`;
})
.join('')}
</Descriptions.Item>
) : null}
{redeemDetail.payout ? (
<Descriptions.Item label="门店结算单">
¥{Number((redeemDetail.payout as { settleAmount?: number }).settleAmount ?? 0).toFixed(2)}
{' / '}
{String((redeemDetail.payout as { status?: string }).status ?? '—')}
</Descriptions.Item>
) : null}
{redeemDetail.rating ? (
<Descriptions.Item label="评价">
{(redeemDetail.rating as { serviceScore?: number }).serviceScore ?? '—'} / {' '}
{(redeemDetail.rating as { envScore?: number }).envScore ?? '—'}
</Descriptions.Item>
) : null}
</Descriptions>
) : null}
</Drawer>
<Modal
title={shipTarget ? `配送发货 · ${shipTarget.orderNo}` : '配送发货'}
open={shipModalOpen}
+12 -3
View File
@@ -23,7 +23,7 @@ import {
type PartnerPermissionKey,
} from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api';
import { districtCodeLabel } from '../lib/china-region';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect';
@@ -37,6 +37,7 @@ type Row = {
cityId?: string | null;
cityName?: string | null;
scopeType?: string;
districtCodes?: string[] | null;
orderCommissionRate?: number;
redeemCommissionRate?: number;
storeCount: number;
@@ -174,6 +175,14 @@ export default function PartnersPage() {
const columns: ColumnsType<Row> = [
{ title: '公司名', dataIndex: 'companyName', ellipsis: true },
{
title: '区县',
dataIndex: 'districtCodes',
width: 160,
ellipsis: true,
render: (codes: string[] | null | undefined, row) =>
row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes),
},
{ title: '城市', dataIndex: 'cityName', width: 100 },
{ title: '主账号', dataIndex: 'phone', width: 130 },
{
@@ -251,7 +260,7 @@ export default function PartnersPage() {
<Form.Item
name="districtCodes"
label="区县"
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={editCityCode} />
</Form.Item>
@@ -351,7 +360,7 @@ export default function PartnersPage() {
name="districtCodes"
label="区县"
rules={[{ required: true, message: '请选择至少一个区县' }]}
extra="仅选当前开城城市下的区县;不可与其他区域合伙人重合"
extra="仅作标识,可多选当前城市下的区县(不做互斥)"
>
<CityDistrictMultiSelect cityCode={createCityCode} />
</Form.Item>
@@ -5,9 +5,15 @@ import PageShell from '../../components/PageShell';
import SubPageHeader from '../../components/SubPageHeader';
import RegionPicker from '../../components/RegionPicker';
import { buildAddressListUrl, readCheckoutContext } from '../../lib/checkout-nav';
import { DEFAULT_REGION, formatRegion, type RegionSelection } from '../../lib/region-data';
import {
DEFAULT_REGION,
REGION_ALL,
formatRegion,
type RegionSelection,
} from '../../lib/region-data';
import { normalizePhoneInput, validateMobilePhone } from '../../lib/phone';
import { getStoredUserPhone, resolveDefaultUserPhone } from '../../lib/user-phone';
import { resolveUserCity } from '../../lib/user-location';
import { request, toast, type UserProfile } from '../../lib/api';
type AddressForm = {
@@ -27,6 +33,7 @@ export default function AddressEditPage() {
const checkoutCtx = readCheckoutContext(router.params);
const [pickerOpen, setPickerOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [locating, setLocating] = useState(false);
const [error, setError] = useState('');
const [form, setForm] = useState<AddressForm>(() => ({
receiverName: '',
@@ -49,6 +56,35 @@ export default function AddressEditPage() {
.catch(() => {});
}, [id]);
useEffect(() => {
if (id) return;
let cancelled = false;
setLocating(true);
void resolveUserCity(true)
.then((resolved) => {
if (cancelled) return;
const district =
resolved.region.district && resolved.region.district !== REGION_ALL
? resolved.region.district
: resolved.district && resolved.district !== REGION_ALL
? resolved.district
: DEFAULT_REGION.district;
setForm((prev) => ({
...prev,
province: resolved.region.province || prev.province,
city: resolved.region.city || prev.city,
district: district || prev.district,
}));
})
.catch(() => {})
.finally(() => {
if (!cancelled) setLocating(false);
});
return () => {
cancelled = true;
};
}, [id]);
useEffect(() => {
if (!id) return;
request<Array<Record<string, unknown>>>('/user/addresses').then((list) => {
@@ -161,7 +197,11 @@ export default function AddressEditPage() {
style={{ display: 'flex', alignItems: 'center' }}
onClick={() => setPickerOpen(true)}
>
<Text>{regionText || '请选择省市区'}</Text>
<Text>
{locating && !isEdit
? '定位中…'
: regionText || '请选择省市区'}
</Text>
</View>
</View>
<View className="address-form-field">
+27 -9
View File
@@ -11,10 +11,26 @@ type BenefitSummary = {
maxRedeemAmount: number;
};
const MIN_REDEEM_AMOUNT = 0.01;
function formatMoney(amount: number) {
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
/** 核销金额输入:最多两位小数,禁止非法字符 */
function sanitizeRedeemAmountInput(raw: string): string {
let next = raw.replace(/[^\d.]/g, '');
const firstDot = next.indexOf('.');
if (firstDot >= 0) {
next =
next.slice(0, firstDot + 1) + next.slice(firstDot + 1).replace(/\./g, '');
const [intPart, decPart = ''] = next.split('.');
next = `${intPart}.${decPart.slice(0, 2)}`;
}
if (next.startsWith('.')) next = `0${next}`;
return next;
}
export default function RedeemPage() {
const router = useRouter();
const couponId = router.params.couponId;
@@ -50,14 +66,14 @@ export default function RedeemPage() {
}, [couponId]);
function fillMaxAmount() {
if (redeemableMax <= 0) return;
if (redeemableMax < MIN_REDEEM_AMOUNT) return;
setAmount(String(redeemableMax));
}
async function submit() {
const value = Math.round(Number(amount) * 100) / 100;
if (!(value > 0)) {
toast('请输入核销金额');
if (!Number.isFinite(value) || value < MIN_REDEEM_AMOUNT) {
toast(`核销金额不能低于 ${MIN_REDEEM_AMOUNT.toFixed(2)}`);
return;
}
if (value > redeemableMax) {
@@ -103,7 +119,7 @@ export default function RedeemPage() {
placeholder="输入核销金额"
placeholderClass="redeem-input-placeholder"
value={amount}
onInput={(e) => setAmount(e.detail.value)}
onInput={(e) => setAmount(sanitizeRedeemAmountInput(e.detail.value))}
style={{ textAlign: 'center' }}
/>
</View>
@@ -115,12 +131,14 @@ export default function RedeemPage() {
</Text>
</View>
<Text className="redeem-tips">
0 3
</Text>
<View className="redeem-tips">
<Text className="redeem-tips-text">
0.01 3
</Text>
</View>
<View
className={`redeem-submit${loading || redeemableMax <= 0 ? ' redeem-submit--disabled' : ''}`}
onClick={loading || redeemableMax <= 0 ? undefined : submit}
className={`redeem-submit${loading || redeemableMax < MIN_REDEEM_AMOUNT ? ' redeem-submit--disabled' : ''}`}
onClick={loading || redeemableMax < MIN_REDEEM_AMOUNT ? undefined : submit}
>
<Text>{loading ? '生成中...' : '生成核销码'}</Text>
</View>
+10 -4
View File
@@ -77,12 +77,18 @@
.redeem-tips {
display: block;
box-sizing: border-box;
width: 100%;
margin: 0;
padding: 0 var(--space-page);
margin: 8px var(--space-page) 0;
padding: 12px 16px;
border-radius: var(--radius-md);
background: rgba(0, 0, 0, 0.03);
}
.redeem-tips-text {
display: block;
font-size: 12px;
color: var(--color-subtle-gray);
line-height: 1.6;
line-height: 1.7;
word-break: break-word;
}
.redeem-amount-hint {
+2 -5
View File
@@ -61,7 +61,7 @@ describe('validatePartnerCityBinding', () => {
expect(result.ok).toBe(false);
});
it('rejects overlapping district codes', () => {
it('allows overlapping district codes as labels', () => {
const result = validatePartnerCityBinding(
[
{
@@ -74,10 +74,7 @@ describe('validatePartnerCityBinding', () => {
],
{ partnerAccountId: '11', scopeType: 'DISTRICT', districtCodes: ['410105'] },
);
expect(result.ok).toBe(false);
expect(result.message).toContain('区域重合');
expect(result.message).toContain('甲公司');
expect(result.occupiedCodes).toEqual(['410105']);
expect(result.ok).toBe(true);
});
it('allows valid district binding', () => {
+1 -22
View File
@@ -22,7 +22,6 @@ export interface PartnerCityResolveRef {
export interface PartnerCityValidationResult {
ok: boolean;
message?: string;
occupiedCodes?: string[];
}
function normalizeDistrictCodes(codes?: string[] | null): string[] {
@@ -101,27 +100,7 @@ export function validatePartnerCityBinding(
return { ok: false, message: '区域合伙人须至少选择一个区县' };
}
const occupiedBy = new Map<string, string>();
for (const row of others) {
if (row.scopeType !== 'DISTRICT') continue;
const owner = row.companyName?.trim() || '其他区域合伙人';
for (const code of normalizeDistrictCodes(row.districtCodes)) {
if (!occupiedBy.has(code)) occupiedBy.set(code, owner);
}
}
const overlaps = districts.filter((code) => occupiedBy.has(code));
if (overlaps.length) {
const detail = overlaps
.map((code) => `${code}${occupiedBy.get(code)}`)
.join('、');
return {
ok: false,
message: `区域重合:以下区县已被占用,请改选其他区县 — ${detail}`,
occupiedCodes: overlaps,
};
}
// 区县仅为标识,允许多个区域合伙人选择相同区县
return { ok: true };
}
+28 -8
View File
@@ -1038,9 +1038,10 @@ model BenefitCoupon {
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
order Order? @relation(fields: [orderId], references: [id], onDelete: Restrict)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
order Order? @relation(fields: [orderId], references: [id], onDelete: Restrict)
redeemRecords RedeemRecord[]
redeemAllocations RedeemRecordAllocation[]
@@index([userId, status])
@@map("user_benefit_coupon")
@@ -1056,17 +1057,36 @@ model RedeemRecord {
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
rating StoreRating?
payout StorePayout?
pending RedeemPendingRecord?
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
rating StoreRating?
payout StorePayout?
pending RedeemPendingRecord?
allocations RedeemRecordAllocation[]
@@index([storeId, createdAt])
@@map("user_redeem_record")
}
// 核销单跨券 FIFO 分摊明细(含次券可追溯)
model RedeemRecordAllocation {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
redeemRecordId BigInt @map("redeem_record_id") @db.UnsignedBigInt
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
amount Decimal @db.Decimal(10, 2)
sortOrder Int @default(0) @map("sort_order")
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
redeemRecord RedeemRecord @relation(fields: [redeemRecordId], references: [id], onDelete: Cascade)
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
@@unique([redeemRecordId, couponId])
@@index([couponId])
@@index([redeemRecordId])
@@map("user_redeem_record_allocation")
}
model RedeemPendingRecord {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
pendingNo String @unique @map("pending_no") @db.VarChar(32)
@@ -73,11 +73,18 @@ export class AdminOrdersService {
},
delivery: true,
benefitCoupon: {
select: { id: true, couponNo: true, balance: true, status: true },
select: {
id: true,
couponNo: true,
totalAmount: true,
usedAmount: true,
balance: true,
status: true,
},
},
city: { select: { id: true, name: true, code: true } },
product: { select: { id: true, name: true, skuCode: true, barcode69: true } },
imageResource: { select: { id: true, url: true } },
imageResource: { select: { url: true } },
fulfillmentWarehouse: {
select: {
id: true,
@@ -97,11 +104,84 @@ export class AdminOrdersService {
where: orderStatusLogWhere(id),
orderBy: { createdAt: 'asc' },
});
return serializeBigInt(mapOrderCompat({
...order,
statusLogs: mapStatusLogCompat(statusLogs),
benefitCoupons: order.benefitCoupon ? [order.benefitCoupon] : [],
}));
const coupon = order.benefitCoupon;
if (coupon) {
await this.ensureRedeemAllocationsForCoupon(coupon.id);
}
const redeemRows = coupon
? await this.prisma.redeemRecord.findMany({
where: {
OR: [
{ couponId: coupon.id },
{ allocations: { some: { couponId: coupon.id } } },
],
},
orderBy: { createdAt: 'desc' },
include: {
store: { select: { id: true, name: true, cityName: true } },
allocations: {
where: { couponId: coupon.id },
select: { amount: true, sortOrder: true },
},
},
})
: [];
const redeemRecords = redeemRows.map((r) => {
const couponAmount =
r.allocations[0] != null
? Number(r.allocations[0].amount)
: r.couponId === coupon!.id
? Number(r.amount)
: 0;
const isPrimary = r.couponId === coupon!.id;
return {
id: r.id,
redeemNo: r.redeemNo,
amount: Number(r.amount),
settleAmount: Number(r.settleAmount),
couponAmount,
role: isPrimary ? 'PRIMARY' : 'SECONDARY',
createdAt: r.createdAt,
store: r.store,
};
});
const redeemRecordSum = redeemRecords.reduce((sum, r) => sum + r.couponAmount, 0);
const { benefitCoupon: _coupon, ...orderRest } = order;
return serializeBigInt(
mapOrderCompat({
...orderRest,
statusLogs: mapStatusLogCompat(statusLogs),
benefitCoupons: coupon
? [
{
id: coupon.id,
couponNo: coupon.couponNo,
totalAmount: Number(coupon.totalAmount),
usedAmount: Number(coupon.usedAmount),
balance: Number(coupon.balance),
status: coupon.status,
},
]
: [],
redeemSummary: coupon
? {
couponNo: coupon.couponNo,
totalAmount: Number(coupon.totalAmount),
usedAmount: Number(coupon.usedAmount),
balance: Number(coupon.balance),
status: coupon.status,
redeemCount: redeemRecords.length,
redeemRecordSum,
}
: null,
redeemRecords,
}),
);
}
async updateStatusDebug(id: bigint, status: string) {
@@ -309,7 +389,12 @@ export class AdminOrdersService {
if (couponIds.length) {
const redeemIds = (
await tx.redeemRecord.findMany({
where: { couponId: { in: couponIds } },
where: {
OR: [
{ couponId: { in: couponIds } },
{ allocations: { some: { couponId: { in: couponIds } } } },
],
},
select: { id: true },
})
).map((r) => r.id);
@@ -317,6 +402,7 @@ export class AdminOrdersService {
if (redeemIds.length) {
await tx.storePayout.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
await tx.storeRating.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
await tx.redeemRecordAllocation.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
await tx.redeemRecord.deleteMany({ where: { id: { in: redeemIds } } });
}
@@ -332,4 +418,148 @@ export class AdminOrdersService {
});
await tx.order.deleteMany({ where: { id: { in: orderIds } } });
}
/**
* 补齐历史核销分摊:
* 1) 待审核销 pending.allocationsJson → allocation 表
* 2) 权益流水 REDEEM(次券)→ 按用户/门店/时间窗匹配核销单
* 3) 仅主券、尚无分摊行的核销单 → 写入单行分摊(全额)
*/
private async ensureRedeemAllocationsForCoupon(couponId: bigint) {
const coupon = await this.prisma.benefitCoupon.findUnique({
where: { id: couponId },
select: { id: true, userId: true },
});
if (!coupon) return;
const pendings = await this.prisma.redeemPendingRecord.findMany({
where: { userId: coupon.userId, redeemRecordId: { not: null } },
select: { redeemRecordId: true, allocationsJson: true },
});
for (const pending of pendings) {
if (!pending.redeemRecordId) continue;
const allocs = this.parseAllocationsJson(pending.allocationsJson);
if (!allocs.some((a) => a.couponId === couponId.toString())) continue;
const existing = await this.prisma.redeemRecordAllocation.count({
where: { redeemRecordId: pending.redeemRecordId },
});
if (existing > 0) continue;
await this.prisma.redeemRecordAllocation.createMany({
data: allocs.map((a, index) => ({
redeemRecordId: pending.redeemRecordId!,
couponId: BigInt(a.couponId),
amount: a.amount,
sortOrder: index,
})),
skipDuplicates: true,
});
}
const ledgers = await this.prisma.commonEvent.findMany({
where: {
eventType: 'BENEFIT_LEDGER',
param1: 'REDEEM',
param2: couponId.toString(),
actorType: 'USER',
actorId: coupon.userId,
refType: 'STORE',
},
select: { id: true, refId: true, amount1: true, createdAt: true },
orderBy: { createdAt: 'asc' },
});
for (const ledger of ledgers) {
if (ledger.refId == null || ledger.amount1 == null) continue;
const allocAmount = Math.abs(Number(ledger.amount1));
if (!(allocAmount > 0)) continue;
const already = await this.prisma.redeemRecordAllocation.findFirst({
where: {
couponId,
amount: allocAmount,
redeemRecord: {
userId: coupon.userId,
storeId: ledger.refId,
createdAt: {
gte: new Date(ledger.createdAt.getTime() - 8000),
lte: new Date(ledger.createdAt.getTime() + 8000),
},
},
},
select: { id: true },
});
if (already) continue;
const candidates = await this.prisma.redeemRecord.findMany({
where: {
userId: coupon.userId,
storeId: ledger.refId,
createdAt: {
gte: new Date(ledger.createdAt.getTime() - 8000),
lte: new Date(ledger.createdAt.getTime() + 8000),
},
amount: { gte: allocAmount },
allocations: { none: { couponId } },
},
orderBy: { createdAt: 'asc' },
take: 5,
});
if (!candidates.length) continue;
// 优先挂到主券不是本券的核销单(跨券 FIFO 次券场景)
const target =
candidates.find((r) => r.couponId !== couponId) ??
(candidates.length === 1 ? candidates[0] : null);
if (!target) continue;
await this.prisma.redeemRecordAllocation.create({
data: {
redeemRecordId: target.id,
couponId,
amount: allocAmount,
sortOrder: target.couponId === couponId ? 0 : 1,
},
}).catch(() => {
/* unique 冲突忽略 */
});
}
const primaryWithoutAlloc = await this.prisma.redeemRecord.findMany({
where: {
couponId,
allocations: { none: {} },
},
select: { id: true, amount: true },
});
if (primaryWithoutAlloc.length) {
await this.prisma.redeemRecordAllocation.createMany({
data: primaryWithoutAlloc.map((r) => ({
redeemRecordId: r.id,
couponId,
amount: r.amount,
sortOrder: 0,
})),
skipDuplicates: true,
});
}
}
private parseAllocationsJson(
value: Prisma.JsonValue,
): Array<{ couponId: string; amount: number }> {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (!item || typeof item !== 'object') return null;
const row = item as { couponId?: unknown; amount?: unknown };
const id = row.couponId != null ? String(row.couponId) : '';
const amount = Number(row.amount);
if (!id || !Number.isFinite(amount) || amount <= 0) return null;
return { couponId: id, amount };
})
.filter((item): item is { couponId: string; amount: number } => !!item);
}
}
@@ -80,6 +80,7 @@ export class AdminPartnersService {
maxPartnerCommissionRate:
p.city?.maxPartnerCommissionRate != null ? Number(p.city.maxPartnerCommissionRate) : null,
scopeType: p.scopeType,
districtCodes: this.partnerCityService.parseDistrictCodes(p.districtCodes),
orderCommissionRate: Number(p.orderCommissionRate ?? 0),
redeemCommissionRate: Number(p.redeemCommissionRate ?? 0.03),
bindingStatus: p.bindingStatus,
@@ -39,14 +39,56 @@ export class AdminRedeemService {
const record = await this.prisma.redeemRecord.findUnique({
where: { id },
include: {
user: true,
store: { include: { partnerAccount: { select: { id: true, companyName: true } } } },
coupon: true,
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
store: {
select: {
id: true,
name: true,
cityName: true,
address: true,
partnerAccount: { select: { id: true, companyName: true } },
},
},
coupon: {
select: {
id: true,
couponNo: true,
totalAmount: true,
usedAmount: true,
balance: true,
status: true,
orderId: true,
order: { select: { id: true, orderNo: true } },
},
},
allocations: {
orderBy: { sortOrder: 'asc' },
include: {
coupon: {
select: {
id: true,
couponNo: true,
order: { select: { id: true, orderNo: true } },
},
},
},
},
payout: true,
rating: true,
},
});
if (!record) throw new NotFoundException('核销记录不存在');
return serializeBigInt(record);
return serializeBigInt({
...record,
allocations: record.allocations.map((a) => ({
couponId: a.couponId,
amount: Number(a.amount),
sortOrder: a.sortOrder,
couponNo: a.coupon.couponNo,
orderId: a.coupon.order?.id ?? null,
orderNo: a.coupon.order?.orderNo ?? null,
})),
});
}
}
@@ -181,6 +181,13 @@ export class RedeemService {
storeId: account.storeId,
amount,
settleAmount,
allocations: {
create: normalizedAllocations.map((item, index) => ({
couponId: BigInt(item.couponId),
amount: item.amount,
sortOrder: index,
})),
},
},
});