Compare commits
48 Commits
87c4af7364
...
v3.4.9
| Author | SHA1 | Date | |
|---|---|---|---|
| a7d55b7293 | |||
| 7e3dc131ad | |||
| f09e00e16f | |||
| ff462bca9a | |||
| aa0e140fec | |||
| dc30932012 | |||
| f8d8e2d6d5 | |||
| 54fca99208 | |||
| 9859abba7e | |||
| 26472f8678 | |||
| c89560e4f8 | |||
| f3353bbce5 | |||
| 666bcb8633 | |||
| ffed560d43 | |||
| a7a0a54688 | |||
| 5199b495e0 | |||
| 04fd4d50d0 | |||
| 82b98aa4e3 | |||
| 2088a1ee19 | |||
| 7dffd40f3f | |||
| 021b9e0329 | |||
| 0304201e80 | |||
| fd05621660 | |||
| dd4362c397 | |||
| 2ebdb08a2f | |||
| 87515decb3 | |||
| 4a5b9eaffa | |||
| e06d9f4711 | |||
| 28ef916a22 | |||
| fa3484041e | |||
| 06cbcdeb9c | |||
| ebd8c07147 | |||
| 39e38aac7e | |||
| daf534b4db | |||
| 118993a01f | |||
| 8f361981bf | |||
| 4bb6ae20cd | |||
| ad757e9ba8 | |||
| e63b57db19 | |||
| fb4432b307 | |||
| ab44515e8b | |||
| 78365d648c | |||
| e9eddbb26e | |||
| c00ca3620d | |||
| 4d76ee6d0e | |||
| 2dbe665bdc | |||
| 1bc3bec977 | |||
| 81a6e3674b |
@@ -30,4 +30,4 @@ chore(shared-types): add OrderStatus enum
|
||||
|
||||
- **仅用户明确要求时** 才执行 git commit / push
|
||||
- 不 amend 已推送的 commit,不 force push main/master/dev
|
||||
- 发版:`dev`→测试(staging),`main`→生产;用户只说「发布」默认发测试(见 dukang-release skill)
|
||||
- 发版:`dev`→测试(staging),`main`→生产;用户只说「发布/发版」默认发**生产**(见 dukang-release skill);明确说「发测试」才发 staging
|
||||
|
||||
@@ -18,11 +18,13 @@ description: >-
|
||||
| `dev` | **staging 测试** | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||
| `main` | **production 生产** | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||
|
||||
默认:`dev_jacy` → merge → `dev` → **发测试**。
|
||||
生产:`dev` 验收通过 → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
||||
默认:`dev_jacy` → merge → `dev` → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
||||
|
||||
用户只说「发布」且未指明生产时 → **发测试(staging)**。
|
||||
用户说「发生产 / 上线生产」→ 用 `deploy-prod.sh`。
|
||||
> **团队约定(2026-08)**:用户说「发布 / 发版 / 直接发版」且**未特别强调**时 → **发生产(production)**。
|
||||
> 仅当用户明确说「发测试 / staging / 测试环境」时 → 发 staging。
|
||||
|
||||
用户说「发生产 / 上线生产 / 发版」→ 用 `deploy-prod.sh`。
|
||||
用户说「发测试」→ 用 `deploy-staging.sh`。
|
||||
|
||||
## 标准流程(Windows)
|
||||
|
||||
|
||||
@@ -96,11 +96,19 @@ export default function App() {
|
||||
<Route path="/redeem-pending" element={<PendingRedeemPage />} />
|
||||
<Route path="/redeem/debug" element={<RedeemDebugPage />} />
|
||||
<Route path="/finance/store-bills" element={<StoreBillsPage />} />
|
||||
<Route
|
||||
path="/finance/store-withdrawals"
|
||||
element={<Navigate to="/finance/store-bills?kind=WITHDRAW" replace />}
|
||||
/>
|
||||
<Route path="/finance/partner-bills" element={<PartnerBillsPage />} />
|
||||
<Route path="/finance/winery-bills" element={<WineryBillsPage />} />
|
||||
<Route path="/finance/logistics-bills" element={<LogisticsBillsPage />} />
|
||||
<Route path="/store-bills" element={<Navigate to="/finance/store-bills" replace />} />
|
||||
<Route path="/store-payouts" element={<Navigate to="/finance/store-bills" replace />} />
|
||||
<Route
|
||||
path="/store-withdrawals"
|
||||
element={<Navigate to="/finance/store-bills?kind=WITHDRAW" replace />}
|
||||
/>
|
||||
<Route path="/partner-bills" element={<Navigate to="/finance/partner-bills" replace />} />
|
||||
<Route path="/tickets" element={<TicketsPage />} />
|
||||
<Route path="/tickets/support" element={<SupportTicketsPage />} />
|
||||
|
||||
@@ -157,6 +157,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/fulfillment-providers': 'partners',
|
||||
'finance-group': 'finance',
|
||||
'/finance/store-bills': 'finance',
|
||||
'/finance/store-withdrawals': 'finance',
|
||||
'/finance/partner-bills': 'finance',
|
||||
'/finance/winery-bills': 'finance',
|
||||
'/finance/logistics-bills': 'finance',
|
||||
|
||||
@@ -85,6 +85,8 @@ export type DashboardStats = {
|
||||
pendingBills?: number;
|
||||
pendingPartnerDraftBills?: number;
|
||||
openTickets?: number;
|
||||
pendingStoreWithdrawals?: number;
|
||||
overdueStoreWithdrawals?: number;
|
||||
ordersByStatus: Array<{ status: string; count: number }>;
|
||||
};
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ export type StoreCreateForm = {
|
||||
bankAccountNo: string;
|
||||
bankBranch: string;
|
||||
settlementRate?: number;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
};
|
||||
|
||||
const PHONE_RE = /^1\d{10}$/;
|
||||
|
||||
@@ -717,6 +717,26 @@ export default function DashboardPage() {
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card
|
||||
loading={loading}
|
||||
title="待审门店提现"
|
||||
extra={<Link to="/finance/store-bills?kind=WITHDRAW">去处理</Link>}
|
||||
>
|
||||
<Statistic
|
||||
value={stats?.pendingStoreWithdrawals ?? 0}
|
||||
suffix="笔"
|
||||
valueStyle={{
|
||||
color: (stats?.overdueStoreWithdrawals ?? 0) > 0 ? '#cf1322' : (stats?.pendingStoreWithdrawals ?? 0) > 0 ? '#fa8c16' : undefined,
|
||||
}}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{(stats?.overdueStoreWithdrawals ?? 0) > 0
|
||||
? `超时未审 ${stats?.overdueStoreWithdrawals} 笔(FIN-003)`
|
||||
: '工作日 T+0 审完'}
|
||||
</Typography.Text>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card loading={loading} title="待处理工单">
|
||||
<Statistic value={stats?.openTickets ?? 0} suffix="个" />
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Descriptions, Drawer, Form, Input, Table, Typography } from 'antd';
|
||||
import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string; redeemNo: string; amount: number; settleAmount: number; createdAt: string;
|
||||
id: string;
|
||||
redeemNo: string;
|
||||
amount: number;
|
||||
settleAmount: number;
|
||||
channel?: RedeemChannel;
|
||||
createdAt: string;
|
||||
user?: { userNo: string; phone: string | null };
|
||||
store?: { name: string; cityName: string };
|
||||
coupon?: { couponNo: string };
|
||||
@@ -21,6 +27,7 @@ export default function RedeemRecordsPage() {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.channel) qs.set('channel', filters.channel);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
@@ -30,6 +37,19 @@ export default function RedeemRecordsPage() {
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||
{
|
||||
title: '方式',
|
||||
dataIndex: 'channel',
|
||||
width: 110,
|
||||
render: (v: RedeemChannel | undefined) => {
|
||||
const channel = v === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||
return (
|
||||
<Tag color={channel === 'PHONE' ? 'purple' : 'blue'}>
|
||||
{REDEEM_CHANNEL_LABELS[channel]}
|
||||
</Tag>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ title: '用户', dataIndex: ['user', 'userNo'], width: 110 },
|
||||
{ title: '门店', dataIndex: ['store', 'name'] },
|
||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||
@@ -37,12 +57,19 @@ export default function RedeemRecordsPage() {
|
||||
{ title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 },
|
||||
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
{
|
||||
title: '操作', width: 80,
|
||||
title: '操作',
|
||||
width: 80,
|
||||
render: (_, row) => (
|
||||
<Button type="link" size="small" onClick={async () => {
|
||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
||||
setDrawerOpen(true);
|
||||
}}>详情</Button>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={async () => {
|
||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
||||
setDrawerOpen(true);
|
||||
}}
|
||||
>
|
||||
详情
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -50,16 +77,65 @@ export default function RedeemRecordsPage() {
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4}>核销记录</Typography.Title>
|
||||
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
|
||||
<Form.Item name="redeemNo" label="核销号"><Input allowClear /></Form.Item>
|
||||
<Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
onFinish={(v) => {
|
||||
setFilters(v);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="redeemNo" label="核销号">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店ID">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item name="channel" label="方式">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={[
|
||||
{ value: 'SCAN', label: '扫码核销' },
|
||||
{ value: 'PHONE', label: '手机号核销' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1000 }}
|
||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1100 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
|
||||
{detail && (
|
||||
<Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="方式">
|
||||
{
|
||||
REDEEM_CHANNEL_LABELS[
|
||||
(detail.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel
|
||||
]
|
||||
}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -6,6 +7,7 @@ import {
|
||||
Descriptions,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
@@ -17,44 +19,61 @@ import {
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import {
|
||||
STORE_SETTLEMENT_KIND_LABELS,
|
||||
STORE_SETTLEMENT_STATUS_LABELS,
|
||||
storeSettlementStatusLabel,
|
||||
type StoreSettlementKind,
|
||||
type StoreSettlementStatus,
|
||||
} from '@dukang/shared-types';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
kind: StoreSettlementKind;
|
||||
id: string;
|
||||
billNo: string;
|
||||
billDate: string;
|
||||
redeemCount: number;
|
||||
redeemAmount: number;
|
||||
settlementRate: number;
|
||||
payoutAmount: number;
|
||||
status: string;
|
||||
paidAt?: string | null;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string };
|
||||
amount: number;
|
||||
status: StoreSettlementStatus;
|
||||
date: string;
|
||||
overdue?: boolean;
|
||||
redeemCount?: number | null;
|
||||
redeemAmount?: number | null;
|
||||
settlementRate?: number | null;
|
||||
payoutCount?: number | null;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string | null };
|
||||
};
|
||||
|
||||
type StoreOption = { id: string; name: string; phone: string };
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
UNPAID: '未打款',
|
||||
PAID: '已打款',
|
||||
};
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
UNPAID: 'red',
|
||||
PAID: 'green',
|
||||
PENDING_REVIEW: 'orange',
|
||||
REJECTED: 'red',
|
||||
};
|
||||
|
||||
const KIND_COLORS: Record<StoreSettlementKind, string> = {
|
||||
T1_BILL: 'blue',
|
||||
WITHDRAW: 'purple',
|
||||
};
|
||||
|
||||
export default function StoreBillsPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : '';
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||
const [filters, setFilters] = useState<Record<string, string>>({
|
||||
kind: initialKind,
|
||||
status: initialKind === 'WITHDRAW' ? 'PENDING_REVIEW' : '',
|
||||
});
|
||||
const [stores, setStores] = useState<StoreOption[]>([]);
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||
'/admin/store-bills',
|
||||
'/admin/store-settlements',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.kind) qs.set('kind', filters.kind);
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
@@ -64,21 +83,38 @@ export default function StoreBillsPage() {
|
||||
[filters],
|
||||
);
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [detailKind, setDetailKind] = useState<StoreSettlementKind | null>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
const [overdueSummary, setOverdueSummary] = useState<{
|
||||
pendingCount: number;
|
||||
overdueCount: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
form.setFieldsValue({
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
});
|
||||
}, [filters.kind, filters.status, form]);
|
||||
|
||||
useEffect(() => {
|
||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setStores(res.items))
|
||||
.catch(() => {});
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
function confirmPay(ids: string[], amountHint?: number) {
|
||||
Modal.confirm({
|
||||
title: '确认打款?',
|
||||
content: `将确认 ${ids.length} 笔门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
||||
content: `将确认 ${ids.length} 笔 T+1 门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
||||
okText: '确认打款',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
@@ -102,9 +138,75 @@ export default function StoreBillsPage() {
|
||||
});
|
||||
}
|
||||
|
||||
async function openDetail(id: string) {
|
||||
const d = await request<Record<string, unknown>>(`/admin/store-bills/${id}`);
|
||||
function approveWithdraw(id: string) {
|
||||
let paymentRef = '';
|
||||
Modal.confirm({
|
||||
title: '审核通过并标记已结算?',
|
||||
content: (
|
||||
<Input
|
||||
placeholder="打款凭证号(可选)"
|
||||
onChange={(e) => {
|
||||
paymentRef = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '通过并结算',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await request(`/admin/store-withdrawals/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
|
||||
});
|
||||
message.success('已通过并标记已结算');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function rejectWithdraw(id: string) {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '驳回提现申请?',
|
||||
content: (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
placeholder="请填写驳回理由"
|
||||
onChange={(e) => {
|
||||
reason = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '确认驳回',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) {
|
||||
message.error('请填写驳回理由');
|
||||
throw new Error('reason required');
|
||||
}
|
||||
await request(`/admin/store-withdrawals/${id}/reject`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: reason.trim() }),
|
||||
});
|
||||
message.success('已驳回');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function openDetail(row: Row) {
|
||||
const path =
|
||||
row.kind === 'WITHDRAW' ? `/admin/store-withdrawals/${row.id}` : `/admin/store-bills/${row.id}`;
|
||||
const d = await request<Record<string, unknown>>(path);
|
||||
setDetail(d);
|
||||
setDetailKind(row.kind);
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
|
||||
@@ -118,88 +220,134 @@ export default function StoreBillsPage() {
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
||||
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
||||
message.success(`已导出 ${result.count} 条`);
|
||||
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const summary = data?.summary;
|
||||
const selectedRows = (data?.items ?? []).filter((r) => selectedKeys.includes(r.id));
|
||||
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.payoutAmount), 0);
|
||||
const selectedRows = (data?.items ?? []).filter(
|
||||
(r) =>
|
||||
selectedKeys.includes(`${r.kind}-${r.id}`) &&
|
||||
r.kind === 'T1_BILL' &&
|
||||
r.status === 'UNPAID',
|
||||
);
|
||||
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.amount), 0);
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '账单号', dataIndex: 'billNo', width: 170, ellipsis: true },
|
||||
{
|
||||
title: '账单日',
|
||||
dataIndex: 'billDate',
|
||||
width: 110,
|
||||
render: (v) => String(v || '').slice(0, 10),
|
||||
title: '类型',
|
||||
dataIndex: 'kind',
|
||||
width: 100,
|
||||
render: (k: StoreSettlementKind) => (
|
||||
<Tag color={KIND_COLORS[k]}>{STORE_SETTLEMENT_KIND_LABELS[k] ?? k}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
render: (v, row) => (
|
||||
<Space>
|
||||
<span>{v}</span>
|
||||
{row.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '日期',
|
||||
dataIndex: 'date',
|
||||
width: 160,
|
||||
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
|
||||
},
|
||||
{ title: '门店', dataIndex: ['store', 'name'], width: 140, ellipsis: true },
|
||||
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||
{ title: '核销笔数', dataIndex: 'redeemCount', width: 90 },
|
||||
{
|
||||
title: '核销金额',
|
||||
dataIndex: 'redeemAmount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '结算比例',
|
||||
dataIndex: 'settlementRate',
|
||||
width: 90,
|
||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
||||
title: '笔数',
|
||||
width: 80,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
||||
},
|
||||
{
|
||||
title: '应付金额',
|
||||
dataIndex: 'payoutAmount',
|
||||
dataIndex: 'amount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
||||
width: 100,
|
||||
render: (s: string, row) => (
|
||||
<Tag color={STATUS_COLORS[s] || 'default'}>{storeSettlementStatusLabel(row.kind, s)}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 160,
|
||||
width: 200,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space size={0}>
|
||||
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
||||
<Button type="link" size="small" onClick={() => void openDetail(row)}>
|
||||
明细
|
||||
</Button>
|
||||
{row.status === 'UNPAID' && (
|
||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.payoutAmount))}>
|
||||
{row.kind === 'T1_BILL' && row.status === 'UNPAID' && (
|
||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.amount))}>
|
||||
确认打款
|
||||
</Button>
|
||||
)}
|
||||
{row.kind === 'WITHDRAW' && row.status === 'PENDING_REVIEW' && (
|
||||
<>
|
||||
<Button type="link" size="small" onClick={() => approveWithdraw(row.id)}>
|
||||
通过
|
||||
</Button>
|
||||
<Button type="link" size="small" danger onClick={() => rejectWithdraw(row.id)}>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const withdrawDetailItems =
|
||||
(detail?.items as Array<Record<string, unknown>> | undefined) ?? [];
|
||||
const storeAccount = detail?.storeAccount as
|
||||
| {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
bankAccountName?: string;
|
||||
bankAccountNo?: string;
|
||||
bankBranch?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
门店对账单
|
||||
门店账单
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
按核销日汇总(每日 8:00 自动出账);未打款红色、已打款绿色
|
||||
含 T+1 自动出账与门店手动提现;按类型筛选,详情与审核动作沿用原接口
|
||||
</Typography.Text>
|
||||
{overdueSummary && overdueSummary.overdueCount > 0 ? (
|
||||
<Typography.Text type="danger">
|
||||
手动提现超时未审 {overdueSummary.overdueCount} 笔(待审共 {overdueSummary.pendingCount})
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
</Space>
|
||||
|
||||
{summary && (
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space size="large" wrap>
|
||||
<Statistic title="账单数" value={summary.count} />
|
||||
<Statistic title="记录数" value={summary.count} />
|
||||
<Statistic title="核销金额合计" value={summary.redeemAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.payoutAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.payoutAmount ?? summary.totalAmount ?? 0} prefix="¥" precision={2} />
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
@@ -208,16 +356,37 @@ export default function StoreBillsPage() {
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
onFinish={(v: { storeId?: string; status?: string; range?: [Dayjs, Dayjs] }) => {
|
||||
initialValues={{
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
}}
|
||||
onFinish={(v: {
|
||||
kind?: string;
|
||||
storeId?: string;
|
||||
status?: string;
|
||||
range?: [Dayjs, Dayjs];
|
||||
}) => {
|
||||
setFilters({
|
||||
kind: v.kind || '',
|
||||
storeId: v.storeId || '',
|
||||
status: v.status || '',
|
||||
dateFrom: v.range?.[0] ? v.range[0].format('YYYY-MM-DD') : '',
|
||||
dateTo: v.range?.[1] ? v.range[1].format('YYYY-MM-DD') : '',
|
||||
});
|
||||
setPage(1);
|
||||
setSelectedKeys([]);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="kind" label="类型">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={Object.entries(STORE_SETTLEMENT_KIND_LABELS).map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店">
|
||||
<Select
|
||||
allowClear
|
||||
@@ -232,10 +401,16 @@ export default function StoreBillsPage() {
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({ value, label }))}
|
||||
options={Object.entries(STORE_SETTLEMENT_STATUS_LABELS).map(([value, label]) => ({
|
||||
value,
|
||||
label:
|
||||
value === 'PAID'
|
||||
? '已打款/已结算'
|
||||
: label,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="range" label="账单日">
|
||||
<Form.Item name="range" label="日期">
|
||||
<DatePicker.RangePicker />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
@@ -249,6 +424,7 @@ export default function StoreBillsPage() {
|
||||
form.resetFields();
|
||||
setFilters({});
|
||||
setPage(1);
|
||||
setSelectedKeys([]);
|
||||
}}
|
||||
>
|
||||
重置
|
||||
@@ -256,33 +432,36 @@ export default function StoreBillsPage() {
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button loading={exporting} onClick={() => void exportExcel()}>
|
||||
导出 Excel
|
||||
导出 T+1 Excel
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button
|
||||
type="primary"
|
||||
disabled={!selectedKeys.length}
|
||||
disabled={!selectedRows.length}
|
||||
loading={batchLoading}
|
||||
onClick={() => confirmPay(selectedKeys.map(String), selectedAmount)}
|
||||
onClick={() => confirmPay(selectedRows.map((r) => r.id), selectedAmount)}
|
||||
>
|
||||
批量确认打款 ({selectedKeys.length})
|
||||
批量确认打款 ({selectedRows.length})
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<Table
|
||||
rowKey="id"
|
||||
rowKey={(r) => `${r.kind}-${r.id}`}
|
||||
className="admin-table-nowrap"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
rowClassName={(row) => (row.overdue ? 'ant-table-row-selected' : '')}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedKeys,
|
||||
onChange: setSelectedKeys,
|
||||
getCheckboxProps: (r) => ({ disabled: r.status !== 'UNPAID' }),
|
||||
getCheckboxProps: (r) => ({
|
||||
disabled: !(r.kind === 'T1_BILL' && r.status === 'UNPAID'),
|
||||
}),
|
||||
}}
|
||||
scroll={{ x: 1200 }}
|
||||
scroll={{ x: 1300 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
@@ -295,14 +474,25 @@ export default function StoreBillsPage() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer title="门店对账单明细" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}>
|
||||
{detail && (
|
||||
<Drawer
|
||||
title={detailKind === 'WITHDRAW' ? '手动提现明细' : 'T+1 对账单明细'}
|
||||
open={drawerOpen}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
width={detailKind === 'WITHDRAW' ? 640 : 520}
|
||||
>
|
||||
{detail && detailKind === 'T1_BILL' && (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">{String(detail.billDate || '').slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">¥{Number(detail.payoutAmount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">{STATUS_LABELS[String(detail.status)] || String(detail.status)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">
|
||||
{String(detail.billDate || '').slice(0, 10)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">
|
||||
¥{Number(detail.payoutAmount ?? 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{storeSettlementStatusLabel('T1_BILL', String(detail.status))}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="打款时间">
|
||||
{detail.paidAt ? fmtTime(String(detail.paidAt)) : '—'}
|
||||
</Descriptions.Item>
|
||||
@@ -318,7 +508,8 @@ export default function StoreBillsPage() {
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
||||
render: (_, r) =>
|
||||
String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
@@ -334,6 +525,83 @@ export default function StoreBillsPage() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{detail && detailKind === 'WITHDRAW' && (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="提现单号">{String(detail.withdrawNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="金额">
|
||||
¥{Number(detail.amount ?? 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{storeSettlementStatusLabel('WITHDRAW', String(detail.status))}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="申请时间">
|
||||
{detail.appliedAt ? fmtTime(String(detail.appliedAt)) : '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="驳回理由">
|
||||
{detail.rejectReason ? String(detail.rejectReason) : '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="打款凭证">
|
||||
{detail.paymentRef ? String(detail.paymentRef) : '—'}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{storeAccount ? (
|
||||
<>
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
收款账户
|
||||
</Typography.Title>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="户名">
|
||||
{storeAccount.bankAccountName || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="账号">
|
||||
{storeAccount.bankAccountNo || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="开户行">
|
||||
{storeAccount.bankBranch || '—'}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</>
|
||||
) : null}
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
提现明细
|
||||
</Typography.Title>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey="id"
|
||||
pagination={false}
|
||||
dataSource={withdrawDetailItems}
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => {
|
||||
const payout = r.storePayout as
|
||||
| { redeemRecord?: { redeemNo?: string }; payoutAmount?: number }
|
||||
| undefined;
|
||||
return String(payout?.redeemRecord?.redeemNo || '—');
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '应付',
|
||||
render: (_, r) => {
|
||||
const payout = r.storePayout as { payoutAmount?: number } | undefined;
|
||||
return `¥${Number(payout?.payoutAmount ?? 0).toFixed(2)}`;
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{String(detail.status) === 'PENDING_REVIEW' ? (
|
||||
<Space style={{ marginTop: 16 }}>
|
||||
<Button type="primary" onClick={() => approveWithdraw(String(detail.id))}>
|
||||
通过
|
||||
</Button>
|
||||
<Button danger onClick={() => rejectWithdraw(String(detail.id))}>
|
||||
驳回
|
||||
</Button>
|
||||
</Space>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
DatePicker,
|
||||
Descriptions,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import { STORE_WITHDRAW_STATUS_LABELS, type StoreWithdrawStatus } from '@dukang/shared-types';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
withdrawNo: string;
|
||||
amount: number;
|
||||
payoutCount: number;
|
||||
status: StoreWithdrawStatus;
|
||||
appliedAt: string;
|
||||
reviewedAt?: string | null;
|
||||
paidAt?: string | null;
|
||||
paymentRef?: string | null;
|
||||
rejectReason?: string | null;
|
||||
overdue?: boolean;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string };
|
||||
};
|
||||
|
||||
type StoreOption = { id: string; name: string; phone: string };
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
PENDING_REVIEW: 'orange',
|
||||
REJECTED: 'red',
|
||||
PAID: 'green',
|
||||
};
|
||||
|
||||
export default function StoreWithdrawalsPage() {
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({ status: 'PENDING_REVIEW' });
|
||||
const [stores, setStores] = useState<StoreOption[]>([]);
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||
'/admin/store-withdrawals',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
);
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [overdueSummary, setOverdueSummary] = useState<{
|
||||
pendingCount: number;
|
||||
overdueCount: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setStores(res.items))
|
||||
.catch(() => {});
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function openDetail(id: string) {
|
||||
const d = await request<Record<string, unknown>>(`/admin/store-withdrawals/${id}`);
|
||||
setDetail(d);
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
|
||||
function approve(id: string) {
|
||||
let paymentRef = '';
|
||||
Modal.confirm({
|
||||
title: '审核通过并标记已结算?',
|
||||
content: (
|
||||
<Input
|
||||
placeholder="打款凭证号(可选)"
|
||||
onChange={(e) => {
|
||||
paymentRef = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '通过并结算',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await request(`/admin/store-withdrawals/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
|
||||
});
|
||||
message.success('已通过并标记已结算');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function reject(id: string) {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '驳回提现申请?',
|
||||
content: (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
placeholder="请填写驳回理由"
|
||||
onChange={(e) => {
|
||||
reason = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '确认驳回',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) {
|
||||
message.error('请填写驳回理由');
|
||||
throw new Error('reason required');
|
||||
}
|
||||
await request(`/admin/store-withdrawals/${id}/reject`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: reason.trim() }),
|
||||
});
|
||||
message.success('已驳回');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{
|
||||
title: '提现单号',
|
||||
dataIndex: 'withdrawNo',
|
||||
width: 180,
|
||||
render: (v, row) => (
|
||||
<Space>
|
||||
<Typography.Link onClick={() => void openDetail(row.id)}>{v}</Typography.Link>
|
||||
{row.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '门店',
|
||||
dataIndex: ['store', 'name'],
|
||||
width: 160,
|
||||
render: (_, row) => (
|
||||
<div>
|
||||
<div>{row.store?.name || '—'}</div>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{row.store?.cityName} {row.store?.phone}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{ title: '明细笔数', dataIndex: 'payoutCount', width: 90 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (v: StoreWithdrawStatus) => (
|
||||
<Tag color={STATUS_COLORS[v]}>{STORE_WITHDRAW_STATUS_LABELS[v] ?? v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '申请时间',
|
||||
dataIndex: 'appliedAt',
|
||||
width: 170,
|
||||
render: (v) => fmtTime(v),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => void openDetail(row.id)}>
|
||||
详情
|
||||
</Button>
|
||||
{row.status === 'PENDING_REVIEW' ? (
|
||||
<>
|
||||
<Button size="small" type="primary" onClick={() => approve(row.id)}>
|
||||
通过
|
||||
</Button>
|
||||
<Button size="small" danger onClick={() => reject(row.id)}>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const detailItems = (detail?.items as Array<Record<string, unknown>> | undefined) ?? [];
|
||||
const storeAccount = detail?.storeAccount as
|
||||
| {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
bankAccountName?: string;
|
||||
bankAccountNo?: string;
|
||||
bankBranch?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4} style={{ marginTop: 0 }}>
|
||||
门店提现审
|
||||
</Typography.Title>
|
||||
{overdueSummary ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
待审 {overdueSummary.pendingCount} 笔
|
||||
{overdueSummary.overdueCount > 0 ? (
|
||||
<Typography.Text type="danger">
|
||||
{' '}
|
||||
· 超时未审 {overdueSummary.overdueCount} 笔(FIN-003)
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16, gap: 8 }}
|
||||
initialValues={{ status: 'PENDING_REVIEW' }}
|
||||
onFinish={(v) => {
|
||||
const range = v.range as [Dayjs, Dayjs] | undefined;
|
||||
setFilters({
|
||||
status: v.status || '',
|
||||
storeId: v.storeId || '',
|
||||
dateFrom: range?.[0]?.format('YYYY-MM-DD') || '',
|
||||
dateTo: range?.[1]?.format('YYYY-MM-DD') || '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={[
|
||||
{ value: 'PENDING_REVIEW', label: '待审核' },
|
||||
{ value: 'PAID', label: '已结算' },
|
||||
{ value: 'REJECTED', label: '已驳回' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店">
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: 220 }}
|
||||
options={stores.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name} (${s.phone})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="range" label="申请日">
|
||||
<DatePicker.RangePicker />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1100 }}
|
||||
rowClassName={(row) => (row.overdue ? 'ant-table-row-selected' : '')}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer
|
||||
title="提现详情"
|
||||
width={640}
|
||||
open={drawerOpen}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
extra={
|
||||
detail?.status === 'PENDING_REVIEW' ? (
|
||||
<Space>
|
||||
<Button type="primary" onClick={() => approve(String(detail.id))}>
|
||||
通过
|
||||
</Button>
|
||||
<Button danger onClick={() => reject(String(detail.id))}>
|
||||
驳回
|
||||
</Button>
|
||||
</Space>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detail ? (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="提现单号">{String(detail.withdrawNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={STATUS_COLORS[String(detail.status)]}>
|
||||
{STORE_WITHDRAW_STATUS_LABELS[detail.status as StoreWithdrawStatus] ??
|
||||
String(detail.status)}
|
||||
</Tag>
|
||||
{detail.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="金额">¥{Number(detail.amount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="明细笔数">{String(detail.payoutCount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="申请时间">{fmtTime(String(detail.appliedAt))}</Descriptions.Item>
|
||||
{detail.rejectReason ? (
|
||||
<Descriptions.Item label="驳回理由">{String(detail.rejectReason)}</Descriptions.Item>
|
||||
) : null}
|
||||
{detail.paymentRef ? (
|
||||
<Descriptions.Item label="打款凭证">{String(detail.paymentRef)}</Descriptions.Item>
|
||||
) : null}
|
||||
<Descriptions.Item label="收款户名">
|
||||
{storeAccount?.bankAccountName || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="收款账号">
|
||||
{storeAccount?.bankAccountNo || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="开户行">{storeAccount?.bankBranch || '—'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Typography.Title level={5} style={{ marginTop: 24 }}>
|
||||
关联结算明细
|
||||
</Typography.Title>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey={(r) => String((r as { id?: string }).id)}
|
||||
pagination={false}
|
||||
dataSource={detailItems}
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => {
|
||||
const payout = (r as { storePayout?: { redeemRecord?: { redeemNo?: string } } })
|
||||
.storePayout;
|
||||
return payout?.redeemRecord?.redeemNo || '—';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '结算额',
|
||||
render: (_, r) => {
|
||||
const payout = (r as { storePayout?: { payoutAmount?: number } }).storePayout;
|
||||
return `¥${Number(payout?.payoutAmount ?? 0).toFixed(2)}`;
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Alert,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Select,
|
||||
Space,
|
||||
Steps,
|
||||
Switch,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { FormInstance } from 'antd/es/form';
|
||||
import { FilePdfOutlined, LinkOutlined, EnvironmentOutlined } from '@ant-design/icons';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import {
|
||||
@@ -274,6 +276,89 @@ function StoreAuditMediaSection({ detail }: { detail: Record<string, unknown> })
|
||||
);
|
||||
}
|
||||
|
||||
type UserPickRow = { id: string; phone?: string | null; nickname?: string | null; userNo?: string | null };
|
||||
|
||||
function StoreVisibilityWhitelistFields({ form }: { form: FormInstance }) {
|
||||
const [userOptions, setUserOptions] = useState<UserPickRow[]>([]);
|
||||
const [userSearching, setUserSearching] = useState(false);
|
||||
const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
async function searchUsers(keyword: string) {
|
||||
const q = keyword.trim();
|
||||
if (searchTimer.current) clearTimeout(searchTimer.current);
|
||||
if (!q) {
|
||||
setUserOptions([]);
|
||||
return;
|
||||
}
|
||||
searchTimer.current = setTimeout(() => {
|
||||
void (async () => {
|
||||
setUserSearching(true);
|
||||
try {
|
||||
const qs = new URLSearchParams({ page: '1', pageSize: '20', phone: q });
|
||||
const res = await request<{ items: UserPickRow[] }>(`/admin/users?${qs}`);
|
||||
setUserOptions((res.items ?? []).filter((u) => !!u.phone));
|
||||
} catch {
|
||||
setUserOptions([]);
|
||||
} finally {
|
||||
setUserSearching(false);
|
||||
}
|
||||
})();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
const enabled = Form.useWatch('visibilityWhitelistEnabled', form);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form.Item
|
||||
name="visibilityWhitelistEnabled"
|
||||
label="可见白名单"
|
||||
valuePropName="checked"
|
||||
extra="开启后仅名单内手机号在 C 端可见,用于在线测试"
|
||||
>
|
||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||
</Form.Item>
|
||||
{enabled ? (
|
||||
<>
|
||||
<Form.Item
|
||||
name="visibilityPhones"
|
||||
label="白名单手机号"
|
||||
rules={[{ required: true, message: '请至少添加一个手机号' }]}
|
||||
extra="可直接输入多个手机号回车添加,或从下方用户库选择"
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
tokenSeparators={[',', ' ', ',', ';', ';']}
|
||||
placeholder="输入手机号后回车"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="从用户库添加">
|
||||
<Select
|
||||
showSearch
|
||||
filterOption={false}
|
||||
placeholder="按手机号搜索用户"
|
||||
loading={userSearching}
|
||||
options={userOptions.map((u) => ({
|
||||
value: u.phone!,
|
||||
label: `${u.phone}${u.nickname ? ` · ${u.nickname}` : ''}${u.userNo ? `(${u.userNo})` : ''}`,
|
||||
}))}
|
||||
onSearch={searchUsers}
|
||||
onSelect={(phone: string) => {
|
||||
const cur = (form.getFieldValue('visibilityPhones') as string[] | undefined) ?? [];
|
||||
if (!cur.includes(phone)) {
|
||||
form.setFieldsValue({ visibilityPhones: [...cur, phone] });
|
||||
}
|
||||
}}
|
||||
notFoundContent={userSearching ? '搜索中…' : '输入手机号搜索'}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type StoreRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -287,6 +372,8 @@ type StoreRow = {
|
||||
intro: string | null;
|
||||
coverUrl: string | null;
|
||||
createdAt: string;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
cityRef?: { name: string; code: string };
|
||||
partner?: { companyName: string };
|
||||
account?: {
|
||||
@@ -504,6 +591,10 @@ export default function StoresPage() {
|
||||
bankAccountName: account?.bankAccountName || undefined,
|
||||
bankAccountNo: account?.bankAccountNo || undefined,
|
||||
bankBranch: account?.bankBranch || undefined,
|
||||
visibilityWhitelistEnabled: !!d.visibilityWhitelistEnabled,
|
||||
visibilityPhones: Array.isArray(d.visibilityPhones)
|
||||
? (d.visibilityPhones as string[])
|
||||
: [],
|
||||
});
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
@@ -543,6 +634,10 @@ export default function StoresPage() {
|
||||
bankAccountName: v.bankAccountName ?? null,
|
||||
bankAccountNo: v.bankAccountNo ?? null,
|
||||
bankBranch: v.bankBranch ?? null,
|
||||
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||
visibilityPhones: ((v.visibilityPhones as string[] | undefined) ?? [])
|
||||
.map((p) => String(p || '').replace(/\D/g, '').trim())
|
||||
.filter(Boolean),
|
||||
...(hasCoords
|
||||
? { latitude: Number(v.latitude), longitude: Number(v.longitude) }
|
||||
: {}),
|
||||
@@ -632,6 +727,8 @@ export default function StoresPage() {
|
||||
openTime2: undefined,
|
||||
closeTime2: undefined,
|
||||
avgPrice: undefined,
|
||||
visibilityWhitelistEnabled: false,
|
||||
visibilityPhones: [],
|
||||
});
|
||||
setCreateStep(0);
|
||||
setCreateError('');
|
||||
@@ -713,6 +810,10 @@ export default function StoresPage() {
|
||||
bankAccountNo: values.bankAccountNo.replace(/\s/g, ''),
|
||||
bankBranch: values.bankBranch.trim(),
|
||||
settlementRate: Number(values.settlementRate ?? 60) / 100,
|
||||
visibilityWhitelistEnabled: !!values.visibilityWhitelistEnabled,
|
||||
visibilityPhones: (values.visibilityPhones ?? [])
|
||||
.map((p: string) => String(p || '').replace(/\D/g, '').trim())
|
||||
.filter(Boolean),
|
||||
}),
|
||||
});
|
||||
message.success('门店已创建');
|
||||
@@ -766,6 +867,13 @@ export default function StoresPage() {
|
||||
},
|
||||
},
|
||||
{ title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 120 },
|
||||
{
|
||||
title: '可见',
|
||||
dataIndex: 'visibilityWhitelistEnabled',
|
||||
width: 90,
|
||||
render: (v, row) =>
|
||||
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||
},
|
||||
{ title: '介绍', dataIndex: 'intro', width: 160, ellipsis: true, render: (v) => v || '—' },
|
||||
{ title: '店长', dataIndex: ['account', 'name'], width: 90, render: (v) => v || '—' },
|
||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
@@ -1059,6 +1167,7 @@ export default function StoresPage() {
|
||||
<Input type="time" style={{ width: 140 }} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<StoreVisibilityWhitelistFields form={editForm} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1279,6 +1388,7 @@ export default function StoresPage() {
|
||||
>
|
||||
<Input.TextArea rows={3} placeholder="选填,最多1000字" showCount maxLength={1000} />
|
||||
</Form.Item>
|
||||
<StoreVisibilityWhitelistFields form={createForm} />
|
||||
</div>
|
||||
<div style={{ display: createStep === 1 ? 'block' : 'none' }}>
|
||||
<Typography.Paragraph type="secondary">
|
||||
|
||||
@@ -12,6 +12,7 @@ import RecordsPage from './pages/RecordsPage';
|
||||
import StatusPage from './pages/StatusPage';
|
||||
import MinePage from './pages/MinePage';
|
||||
import StaffPage from './pages/StaffPage';
|
||||
import WithdrawPage from './pages/WithdrawPage';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -22,6 +23,7 @@ export default function App() {
|
||||
<Route path="/legal/privacy-policy" element={<LegalPage docId="privacy-policy" />} />
|
||||
<Route path="/select-store" element={<SelectStorePage />} />
|
||||
<Route path="/staff" element={<StaffPage />} />
|
||||
<Route path="/withdraw" element={<WithdrawPage />} />
|
||||
<Route path="/redeem" element={<RedeemConfirmPage />} />
|
||||
<Route path="/redeem/phone" element={<PhoneRedeemPage />} />
|
||||
<Route path="/redeem/success" element={<RedeemSuccessPage />} />
|
||||
|
||||
@@ -190,6 +190,9 @@ export default function HomePage() {
|
||||
<div className="shop-home-stat">
|
||||
<p className="shop-home-stat-label">今日核销笔数</p>
|
||||
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
||||
<p className="shop-home-stat-sub">
|
||||
扫码 {Number(dash?.todayScanCount || 0)} · 手机号 {Number(dash?.todayPhoneCount || 0)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="shop-home-stat">
|
||||
<p className="shop-home-stat-label">今日到账金额</p>
|
||||
|
||||
@@ -141,6 +141,10 @@ export default function MinePage() {
|
||||
切换门店
|
||||
</button>
|
||||
) : null}
|
||||
<button type="button" className="shop-mine-action" onClick={() => navigate('/withdraw')}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>account_balance_wallet</span>
|
||||
结算提现
|
||||
</button>
|
||||
{profile?.isPrimary ? (
|
||||
<button type="button" className="shop-mine-action" onClick={() => navigate('/staff')}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>group</span>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel, type RedeemStatsDto } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
type RangeKey = 'today' | '7d' | '30d';
|
||||
@@ -23,32 +24,59 @@ function inRange(dateStr: string, range: RangeKey) {
|
||||
return d >= start;
|
||||
}
|
||||
|
||||
function channelLabel(channel: unknown): string {
|
||||
const key = channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||
return REDEEM_CHANNEL_LABELS[key];
|
||||
}
|
||||
|
||||
export default function RecordsPage() {
|
||||
const [records, setRecords] = useState<Array<Record<string, unknown>>>([]);
|
||||
const [range, setRange] = useState<RangeKey>('today');
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
const [storeName, setStoreName] = useState('');
|
||||
const [statsOpen, setStatsOpen] = useState(false);
|
||||
const [statsLoading, setStatsLoading] = useState(false);
|
||||
const [stats, setStats] = useState<RedeemStatsDto | null>(null);
|
||||
|
||||
const loadRecords = useCallback(() => {
|
||||
return Promise.all([
|
||||
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records').then((d) => {
|
||||
setRecords(d.list || []);
|
||||
}),
|
||||
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records?pageSize=200').then(
|
||||
(d) => {
|
||||
setRecords(d.list || []);
|
||||
},
|
||||
),
|
||||
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
||||
.then((s) => setStoreName(String(s.name || '')))
|
||||
.catch(() => {}),
|
||||
]);
|
||||
}, []);
|
||||
|
||||
const loadStats = useCallback(async (r: RangeKey) => {
|
||||
setStatsLoading(true);
|
||||
try {
|
||||
const data = await request<RedeemStatsDto>('SHOP_H5', `/shop/redeem/stats?range=${r}`);
|
||||
setStats(data);
|
||||
} catch {
|
||||
setStats(null);
|
||||
} finally {
|
||||
setStatsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadRecords();
|
||||
}, [loadRecords]);
|
||||
|
||||
useEffect(() => {
|
||||
if (statsOpen) void loadStats(range);
|
||||
}, [statsOpen, range, loadStats]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return records.filter((r) => {
|
||||
if (!inRange(String(r.createdAt), range)) return false;
|
||||
if (statusFilter === 'all') return true;
|
||||
const isPaid = Boolean(r.paidAt);
|
||||
const payout = r.payout as { paidAt?: string | null; status?: string } | undefined;
|
||||
const isPaid = Boolean(payout?.paidAt) || payout?.status === 'PAID' || Boolean(r.paidAt);
|
||||
if (statusFilter === 'paid') return isPaid;
|
||||
return !isPaid;
|
||||
});
|
||||
@@ -70,11 +98,13 @@ export default function RecordsPage() {
|
||||
<div className="shop-records-main">
|
||||
<nav className="shop-records-filters">
|
||||
<div className="shop-records-range-tabs">
|
||||
{([
|
||||
['today', '今日'],
|
||||
['7d', '近7日'],
|
||||
['30d', '近30日'],
|
||||
] as const).map(([key, label]) => (
|
||||
{(
|
||||
[
|
||||
['today', '今日'],
|
||||
['7d', '近7日'],
|
||||
['30d', '近30日'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
@@ -85,21 +115,35 @@ export default function RecordsPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="shop-records-status-chips">
|
||||
{([
|
||||
['all', '全部'],
|
||||
['pending', '待打款'],
|
||||
['paid', '已打款'],
|
||||
] as const).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
||||
onClick={() => setStatusFilter(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
<div className="shop-records-status-row">
|
||||
<div className="shop-records-status-chips">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['pending', '待打款'],
|
||||
['paid', '已打款'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
||||
onClick={() => setStatusFilter(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-records-stats-btn"
|
||||
onClick={() => setStatsOpen(true)}
|
||||
>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>
|
||||
bar_chart
|
||||
</span>
|
||||
统计
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
@@ -115,7 +159,10 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<p className="shop-records-summary-note">
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 16, color: 'var(--color-success-green)' }}>
|
||||
<span
|
||||
className="material-symbols-outlined shop-fill-icon"
|
||||
style={{ fontSize: 16, color: 'var(--color-success-green)' }}
|
||||
>
|
||||
check_circle
|
||||
</span>
|
||||
结算比例: {summary.rate}% (按{summary.rate / 10}折结算)
|
||||
@@ -134,17 +181,32 @@ export default function RecordsPage() {
|
||||
{filtered.map((r) => {
|
||||
const amount = Number(r.amount || 0);
|
||||
const settle = Number(r.settleAmount || 0);
|
||||
const paid = Boolean(r.paidAt);
|
||||
const payout = r.payout as { paidAt?: string | null; status?: string } | undefined;
|
||||
const paid = Boolean(payout?.paidAt) || payout?.status === 'PAID' || Boolean(r.paidAt);
|
||||
const paidAt = payout?.paidAt || (typeof r.paidAt === 'string' ? r.paidAt : null);
|
||||
const channel = (r.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel;
|
||||
return (
|
||||
<article key={String(r.id)} className="shop-record-card">
|
||||
<div className="shop-record-card-top">
|
||||
<div>
|
||||
<div className="shop-record-order">
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>订单号</span>
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>
|
||||
订单号
|
||||
</span>
|
||||
<span>{r.redeemNo ? String(r.redeemNo) : '—'}</span>
|
||||
</div>
|
||||
<p className="shop-record-time">
|
||||
核销时间: {new Date(String(r.createdAt)).toLocaleString('zh-CN', { hour12: false }).slice(0, 16)}
|
||||
核销时间:{' '}
|
||||
{new Date(String(r.createdAt))
|
||||
.toLocaleString('zh-CN', { hour12: false })
|
||||
.slice(0, 16)}
|
||||
</p>
|
||||
<p className="shop-record-channel">
|
||||
<span
|
||||
className={`shop-record-channel-tag${channel === 'PHONE' ? ' phone' : ''}`}
|
||||
>
|
||||
{channelLabel(channel)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<span className={`shop-record-badge ${paid ? 'paid' : 'pending'}`}>
|
||||
@@ -162,10 +224,16 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="shop-record-footer">
|
||||
<p>{paid ? `打款时间: ${new Date(String(r.createdAt)).toLocaleDateString('zh-CN')}` : '预计打款: T+1工作日'}</p>
|
||||
<p>
|
||||
{paid
|
||||
? `打款时间: ${paidAt ? new Date(String(paidAt)).toLocaleDateString('zh-CN') : '—'}`
|
||||
: '预计打款: T+1工作日'}
|
||||
</p>
|
||||
{storeName && (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 12 }}>restaurant</span>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 12 }}>
|
||||
restaurant
|
||||
</span>
|
||||
{storeName}
|
||||
</span>
|
||||
)}
|
||||
@@ -183,6 +251,80 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{statsOpen && (
|
||||
<div className="shop-stats-overlay" role="dialog" aria-modal="true" aria-label="核销方式统计">
|
||||
<button
|
||||
type="button"
|
||||
className="shop-stats-backdrop"
|
||||
aria-label="关闭"
|
||||
onClick={() => setStatsOpen(false)}
|
||||
/>
|
||||
<div className="shop-stats-sheet">
|
||||
<div className="shop-stats-sheet-head">
|
||||
<h2>核销方式统计</h2>
|
||||
<button type="button" className="shop-stats-close" onClick={() => setStatsOpen(false)}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<p className="shop-stats-range-hint">
|
||||
统计区间:{range === 'today' ? '今日' : range === '7d' ? '近7日' : '近30日'}(与上方筛选同步)
|
||||
</p>
|
||||
{statsLoading ? (
|
||||
<p className="shop-records-empty">加载中…</p>
|
||||
) : !stats ? (
|
||||
<p className="shop-records-empty">统计加载失败</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="shop-stats-total">
|
||||
<div>
|
||||
<p className="shop-records-summary-label">合计笔数</p>
|
||||
<p className="shop-stats-total-value">{stats.totalCount}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">核销总额</p>
|
||||
<p className="shop-stats-total-value">¥{formatMoney(stats.totalAmount)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">到账总额</p>
|
||||
<p className="shop-stats-total-value">¥{formatMoney(stats.totalSettleAmount)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="shop-stats-channel-list">
|
||||
{stats.byChannel.map((b) => (
|
||||
<div key={b.channel} className="shop-stats-channel-card">
|
||||
<div className="shop-stats-channel-title">
|
||||
<span
|
||||
className={`shop-record-channel-tag${b.channel === 'PHONE' ? ' phone' : ''}`}
|
||||
>
|
||||
{REDEEM_CHANNEL_LABELS[b.channel]}
|
||||
</span>
|
||||
<strong>{b.count} 笔</strong>
|
||||
</div>
|
||||
<div className="shop-stats-channel-row">
|
||||
<span>核销额</span>
|
||||
<span>¥{formatMoney(b.amount)}</span>
|
||||
</div>
|
||||
<div className="shop-stats-channel-row">
|
||||
<span>到账额</span>
|
||||
<span>¥{formatMoney(b.settleAmount)}</span>
|
||||
</div>
|
||||
<div className="shop-stats-bar">
|
||||
<div
|
||||
className={`shop-stats-bar-fill${b.channel === 'PHONE' ? ' phone' : ''}`}
|
||||
style={{
|
||||
width: `${stats.totalCount > 0 ? Math.round((b.count / stats.totalCount) * 100) : 0}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
STORE_WITHDRAW_STATUS_LABELS,
|
||||
type StoreWithdrawRequestDto,
|
||||
type StoreWithdrawStatus,
|
||||
type StoreWithdrawSummaryDto,
|
||||
} from '@dukang/shared-types';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
type StatusFilter = 'all' | StoreWithdrawStatus;
|
||||
|
||||
function formatMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export default function WithdrawPage() {
|
||||
const navigate = useNavigate();
|
||||
const [summary, setSummary] = useState<StoreWithdrawSummaryDto | null>(null);
|
||||
const [items, setItems] = useState<StoreWithdrawRequestDto[]>([]);
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [summaryRes, listRes] = await Promise.all([
|
||||
request<StoreWithdrawSummaryDto>('SHOP_H5', '/shop/withdraw/summary'),
|
||||
request<{ items: StoreWithdrawRequestDto[] }>('SHOP_H5', '/shop/withdraw/requests?pageSize=50'),
|
||||
]);
|
||||
setSummary(summaryRes);
|
||||
setItems(listRes.items || []);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '加载失败');
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (statusFilter === 'all') return items;
|
||||
return items.filter((r) => r.status === statusFilter);
|
||||
}, [items, statusFilter]);
|
||||
|
||||
async function applyWithdraw() {
|
||||
if (!summary || submitting) return;
|
||||
if (!summary.isPrimary) {
|
||||
setMsg('仅主账号可申请提现');
|
||||
return;
|
||||
}
|
||||
if (!(summary.availableAmount > 0)) {
|
||||
setMsg('暂无可提未出账余额');
|
||||
return;
|
||||
}
|
||||
const ok = window.confirm(
|
||||
`确认申请提现 ¥${formatMoney(summary.availableAmount)}?\n审核通过后将打款至入驻收款账户。`,
|
||||
);
|
||||
if (!ok) return;
|
||||
setSubmitting(true);
|
||||
setMsg('');
|
||||
try {
|
||||
await request('SHOP_H5', '/shop/withdraw', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
setMsg('提现申请已提交,请等待总部审核');
|
||||
await load();
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '提现申请失败');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const canApply =
|
||||
!!summary?.isPrimary &&
|
||||
summary.availableAmount > 0 &&
|
||||
!summary.hasPendingRequest &&
|
||||
summary.hasBankAccount &&
|
||||
!submitting;
|
||||
|
||||
return (
|
||||
<PullToRefresh onRefresh={load} className="shop-records-page shop-withdraw-page">
|
||||
<header className="shop-records-header" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-withdraw-back"
|
||||
onClick={() => navigate(-1)}
|
||||
aria-label="返回"
|
||||
>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 22 }}>
|
||||
arrow_back
|
||||
</span>
|
||||
</button>
|
||||
<h1 className="app-page-title" style={{ margin: 0 }}>
|
||||
结算提现
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<div className="shop-records-main">
|
||||
<section className="shop-records-summary">
|
||||
<div className="shop-records-summary-grid">
|
||||
<div>
|
||||
<p className="shop-records-summary-label">可提未出账余额</p>
|
||||
<p className="shop-records-summary-value">
|
||||
¥ {formatMoney(summary?.availableAmount ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">今日剩余额度</p>
|
||||
<p className="shop-records-summary-value">
|
||||
¥ {formatMoney(summary?.remainingDailyLimit ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="shop-records-summary-note">
|
||||
<span
|
||||
className="material-symbols-outlined shop-fill-icon"
|
||||
style={{ fontSize: 16, color: 'var(--color-success-green)' }}
|
||||
>
|
||||
info
|
||||
</span>
|
||||
单日上限 ¥{formatMoney(summary?.dailyLimit ?? 5000)}
|
||||
{summary?.hasPendingRequest ? ' · 已有待审核申请' : ''}
|
||||
{!summary?.hasBankAccount ? ' · 请先完善收款账户' : ''}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{summary && !summary.isPrimary ? (
|
||||
<p className="shop-records-empty">仅主账号可申请提现,店员可查看记录</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="shop-withdraw-btn"
|
||||
disabled={!canApply}
|
||||
onClick={() => void applyWithdraw()}
|
||||
>
|
||||
{submitting ? '提交中…' : '申请提现'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{msg ? <p className="shop-withdraw-msg">{msg}</p> : null}
|
||||
|
||||
<nav className="shop-records-filters" style={{ marginTop: 16 }}>
|
||||
<div className="shop-records-status-chips">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['PENDING_REVIEW', '待审核'],
|
||||
['PAID', '已结算'],
|
||||
['REJECTED', '已驳回'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
||||
onClick={() => setStatusFilter(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="shop-records-list-head">
|
||||
<h3 className="shop-records-list-title">提现记录</h3>
|
||||
<span className="shop-records-list-count">共 {filtered.length} 笔</span>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<p className="shop-records-empty">暂无提现记录</p>
|
||||
) : (
|
||||
<div className="shop-records-list">
|
||||
{filtered.map((r) => {
|
||||
const status = r.status as StoreWithdrawStatus;
|
||||
const badgeClass =
|
||||
status === 'PAID' ? 'paid' : status === 'REJECTED' ? 'rejected' : 'pending';
|
||||
return (
|
||||
<article key={r.id} className="shop-record-card">
|
||||
<div className="shop-record-card-top">
|
||||
<div>
|
||||
<div className="shop-record-order">
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>
|
||||
单号
|
||||
</span>
|
||||
<span>{r.withdrawNo}</span>
|
||||
</div>
|
||||
<p className="shop-record-time">
|
||||
申请时间:{' '}
|
||||
{new Date(r.appliedAt)
|
||||
.toLocaleString('zh-CN', { hour12: false })
|
||||
.slice(0, 16)}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`shop-record-badge ${badgeClass}`}>
|
||||
{STORE_WITHDRAW_STATUS_LABELS[status] ?? status}
|
||||
</span>
|
||||
</div>
|
||||
<div className="shop-record-amounts">
|
||||
<div>
|
||||
<p className="shop-record-amount-label">提现金额</p>
|
||||
<p className="shop-record-amount-value red">¥{formatMoney(Number(r.amount))}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-record-amount-label">明细笔数</p>
|
||||
<p className="shop-record-amount-value">{r.payoutCount} 笔</p>
|
||||
</div>
|
||||
</div>
|
||||
{status === 'REJECTED' && r.rejectReason ? (
|
||||
<div className="shop-record-footer">
|
||||
<p>驳回原因: {r.rejectReason}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{status === 'PAID' && r.paidAt ? (
|
||||
<div className="shop-record-footer">
|
||||
<p>
|
||||
结算时间:{' '}
|
||||
{new Date(r.paidAt).toLocaleString('zh-CN', { hour12: false }).slice(0, 16)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
+207
-1
@@ -587,6 +587,12 @@
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.shop-home-stat-sub {
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
|
||||
.shop-home-scan {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1549,18 +1555,42 @@
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.shop-records-status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.shop-records-status-chips {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shop-records-status-chips::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.shop-records-stats-btn {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border: 1px solid var(--color-primary);
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
border-radius: var(--radius-full);
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-records-chip {
|
||||
flex-shrink: 0;
|
||||
border: none;
|
||||
@@ -1578,6 +1608,142 @@
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
|
||||
.shop-record-channel {
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
|
||||
.shop-record-channel-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.shop-record-channel-tag.phone {
|
||||
background: rgba(168, 85, 247, 0.12);
|
||||
color: #7e22ce;
|
||||
}
|
||||
|
||||
.shop-stats-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.shop-stats-backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.shop-stats-sheet {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
max-height: 78vh;
|
||||
overflow: auto;
|
||||
background: var(--color-surface);
|
||||
border-radius: 16px 16px 0 0;
|
||||
padding: 16px 16px calc(16px + env(safe-area-inset-bottom, 0px));
|
||||
box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.shop-stats-sheet-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.shop-stats-sheet-head h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.shop-stats-close {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-stats-range-hint {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.shop-stats-total {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--color-surface-container-low, #f5f5f4);
|
||||
}
|
||||
|
||||
.shop-stats-total-value {
|
||||
margin: 4px 0 0;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.shop-stats-channel-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-card {
|
||||
border: 1px solid var(--color-surface-container-highest);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
color: var(--color-on-surface-variant);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.shop-stats-bar {
|
||||
margin-top: 8px;
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-surface-container-highest);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.shop-stats-bar-fill {
|
||||
height: 100%;
|
||||
background: #3b82f6;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.shop-stats-bar-fill.phone {
|
||||
background: #a855f7;
|
||||
}
|
||||
|
||||
.shop-records-main {
|
||||
padding-top: 0;
|
||||
}
|
||||
@@ -1714,6 +1880,46 @@
|
||||
color: var(--color-aged-amber);
|
||||
}
|
||||
|
||||
.shop-record-badge.rejected {
|
||||
background: rgba(180, 35, 24, 0.1);
|
||||
color: var(--color-error-red, #b42318);
|
||||
}
|
||||
|
||||
.shop-withdraw-back {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-withdraw-btn {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
height: 44px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: var(--color-primary, #8b1a1a);
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-withdraw-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.shop-withdraw-msg {
|
||||
margin-top: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--color-aged-amber);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.shop-record-amounts {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import './lib/intl-polyfill';
|
||||
import './lib/text-encoding-polyfill';
|
||||
import { PropsWithChildren, useRef } from 'react';
|
||||
import Taro, { useDidShow } from '@tarojs/taro';
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
type StoreRedeemMarqueeProps = {
|
||||
lines: string[];
|
||||
};
|
||||
|
||||
const FLY_SPEED = 56;
|
||||
const MIN_FLY_MS = 2400;
|
||||
const PAUSE_MIN_MS = 1000;
|
||||
const PAUSE_MAX_MS = 5000;
|
||||
const TICK_MS = 16;
|
||||
/** 全文滚出视口后,再向左多走 10px */
|
||||
const EXTRA_AFTER_EXIT_PX = 10;
|
||||
|
||||
function estimateTextWidth(text: string): number {
|
||||
let w = 0;
|
||||
for (const ch of text) {
|
||||
w += /[^\x00-\xff]/.test(ch) ? 12 : 7;
|
||||
}
|
||||
return Math.max(Math.ceil(w), 80);
|
||||
}
|
||||
|
||||
function randomPauseMs() {
|
||||
return PAUSE_MIN_MS + Math.floor(Math.random() * (PAUSE_MAX_MS - PAUSE_MIN_MS + 1));
|
||||
}
|
||||
|
||||
/** 容器宽兜底(不依赖 DOM 测量,小程序首帧即可用) */
|
||||
function getBoxWidthFallback(): number {
|
||||
try {
|
||||
const sys = Taro.getSystemInfoSync();
|
||||
const screenW = Number(sys.windowWidth || sys.screenWidth || 375);
|
||||
// 与 section 同宽:左右 var(--space-page)
|
||||
return Math.max(220, Math.floor(screenW - 32));
|
||||
} catch {
|
||||
return 300;
|
||||
}
|
||||
}
|
||||
|
||||
function measureBoxWidth(selector: string, fallback: number): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
Taro.nextTick(() => {
|
||||
try {
|
||||
const page = Taro.getCurrentInstance().page;
|
||||
const query = page ? Taro.createSelectorQuery().in(page) : Taro.createSelectorQuery();
|
||||
query
|
||||
.select(selector)
|
||||
.boundingClientRect()
|
||||
.exec((res) => {
|
||||
const w = Number(res?.[0]?.width || 0);
|
||||
resolve(w > 8 ? Math.ceil(w) : fallback);
|
||||
});
|
||||
} catch {
|
||||
resolve(fallback);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function measureTextWidth(selector: string, text: string): Promise<number> {
|
||||
const fallback = estimateTextWidth(text);
|
||||
return new Promise((resolve) => {
|
||||
Taro.nextTick(() => {
|
||||
try {
|
||||
const page = Taro.getCurrentInstance().page;
|
||||
const query = page ? Taro.createSelectorQuery().in(page) : Taro.createSelectorQuery();
|
||||
query
|
||||
.select(selector)
|
||||
.boundingClientRect()
|
||||
.exec((res) => {
|
||||
const w = Number(res?.[0]?.width || 0);
|
||||
if (w > 8 && w < fallback * 3) resolve(Math.ceil(w));
|
||||
else resolve(fallback);
|
||||
});
|
||||
} catch {
|
||||
resolve(fallback);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 核销走马灯:单条从右向左位移飞出,间隔 1~5 秒随机再播下一条。
|
||||
*
|
||||
* 小程序注意:
|
||||
* - 不用 useReady(子组件内不触发 → opacity 永远 0)
|
||||
* - 不用 Text + transform(支持差),改用 View + left
|
||||
* - 字宽用估算,避免屏外元素测宽失败
|
||||
*/
|
||||
export default function StoreRedeemMarquee({ lines }: StoreRedeemMarqueeProps) {
|
||||
const items = useMemo(
|
||||
() =>
|
||||
lines
|
||||
.map((s) => String(s || '').trim())
|
||||
.filter(Boolean),
|
||||
[lines],
|
||||
);
|
||||
|
||||
const rootIdRef = useRef(`smr${Math.random().toString(36).slice(2, 10)}`);
|
||||
const textIdRef = useRef(`smt${Math.random().toString(36).slice(2, 10)}`);
|
||||
const indexRef = useRef(0);
|
||||
const boxWidthRef = useRef(getBoxWidthFallback());
|
||||
const itemsKey = items.join('\n');
|
||||
|
||||
const [displayIndex, setDisplayIndex] = useState(0);
|
||||
const [leftPx, setLeftPx] = useState(() => boxWidthRef.current);
|
||||
|
||||
useEffect(() => {
|
||||
if (!items.length) return;
|
||||
|
||||
let cancelled = false;
|
||||
const waiters = new Set<ReturnType<typeof setTimeout>>();
|
||||
let tickTimer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
new Promise<void>((resolve) => {
|
||||
const id = setTimeout(() => {
|
||||
waiters.delete(id);
|
||||
resolve();
|
||||
}, ms);
|
||||
waiters.add(id);
|
||||
});
|
||||
|
||||
const clearTick = () => {
|
||||
if (tickTimer) {
|
||||
clearInterval(tickTimer);
|
||||
tickTimer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const fly = (from: number, to: number, durationMs: number) =>
|
||||
new Promise<void>((resolve) => {
|
||||
const began = Date.now();
|
||||
setLeftPx(from);
|
||||
clearTick();
|
||||
tickTimer = setInterval(() => {
|
||||
if (cancelled) {
|
||||
clearTick();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const t = Math.min(1, (Date.now() - began) / durationMs);
|
||||
setLeftPx(from + (to - from) * t);
|
||||
if (t >= 1) {
|
||||
clearTick();
|
||||
resolve();
|
||||
}
|
||||
}, TICK_MS);
|
||||
});
|
||||
|
||||
const loop = async () => {
|
||||
indexRef.current = 0;
|
||||
setDisplayIndex(0);
|
||||
|
||||
const measured = await measureBoxWidth(`#${rootIdRef.current}`, boxWidthRef.current);
|
||||
boxWidthRef.current = measured;
|
||||
if (cancelled) return;
|
||||
|
||||
while (!cancelled && items.length) {
|
||||
const idx = indexRef.current % items.length;
|
||||
const text = items[idx];
|
||||
const box = boxWidthRef.current;
|
||||
|
||||
setDisplayIndex(idx);
|
||||
|
||||
const from = box;
|
||||
setLeftPx(from);
|
||||
await sleep(48);
|
||||
if (cancelled) break;
|
||||
|
||||
const textW = await measureTextWidth(`#${textIdRef.current}`, text);
|
||||
// 全文 left 边缘移出容器左边界后再走 10px
|
||||
const to = -(textW + EXTRA_AFTER_EXIT_PX);
|
||||
const distance = from - to;
|
||||
const durationMs = Math.max(MIN_FLY_MS, Math.round((distance / FLY_SPEED) * 1000));
|
||||
|
||||
await sleep(32);
|
||||
if (cancelled) break;
|
||||
|
||||
await fly(from, to, durationMs);
|
||||
if (cancelled) break;
|
||||
|
||||
await sleep(randomPauseMs());
|
||||
if (cancelled) break;
|
||||
|
||||
indexRef.current = (idx + 1) % items.length;
|
||||
}
|
||||
};
|
||||
|
||||
void loop();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTick();
|
||||
waiters.forEach(clearTimeout);
|
||||
waiters.clear();
|
||||
};
|
||||
}, [itemsKey, items]);
|
||||
|
||||
if (!items.length) return null;
|
||||
|
||||
const current = items[displayIndex] || items[0];
|
||||
const innerStyle: CSSProperties = { left: `${leftPx}px` };
|
||||
|
||||
return (
|
||||
<View id={rootIdRef.current} className="store-detail-marquee">
|
||||
<View className="store-detail-marquee-inner" style={innerStyle}>
|
||||
<Text id={textIdRef.current} className="store-detail-marquee-text">
|
||||
{current}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Taro from '@tarojs/taro';
|
||||
import { ClientApp } from '@dukang/shared-types';
|
||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||
import { resetStoresSessionBootstrap } from './stores-session';
|
||||
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||
|
||||
function resolveApiBase(): string {
|
||||
const origin =
|
||||
@@ -57,8 +58,9 @@ export function isLoggedIn(): boolean {
|
||||
|
||||
export function logout() {
|
||||
clearAuth();
|
||||
// 主动退出才重置门店「当次登录」会话;401 清 token 不要打断门店筛选
|
||||
// 主动退出才重置门店/首页「当次登录」会话;401 清 token 不要打断筛选
|
||||
resetStoresSessionBootstrap();
|
||||
resetHomeCatalogBootstrap();
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** 格式化为 Asia/Shanghai:2026-08-03 15:14:30(不依赖 Intl,兼容微信小程序) */
|
||||
export function formatShanghaiDateTime(input?: string | Date | null): string {
|
||||
if (input == null || input === '') return '—';
|
||||
if (typeof input === 'string') {
|
||||
const s = input.trim();
|
||||
if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(s)) {
|
||||
return s.slice(0, 19).replace('T', ' ');
|
||||
}
|
||||
}
|
||||
const d = input instanceof Date ? input : new Date(input);
|
||||
if (Number.isNaN(d.getTime())) return '—';
|
||||
// 用 UTC 读数 + 固定东八区偏移,避免依赖 Intl / 设备时区 API 差异
|
||||
const sh = new Date(d.getTime() + 8 * 60 * 60 * 1000);
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${sh.getUTCFullYear()}-${p(sh.getUTCMonth() + 1)}-${p(sh.getUTCDate())} ${p(sh.getUTCHours())}:${p(sh.getUTCMinutes())}:${p(sh.getUTCSeconds())}`;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 首页商品列表「当次登录」会话 —— 切 tab 不重复拉商品;
|
||||
* 城市 / 登录态变化或下拉刷新时再请求。logout 时 clear。
|
||||
*/
|
||||
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
export type HomeCatalogCache = {
|
||||
cityCode: string;
|
||||
authKey: string;
|
||||
products: unknown[];
|
||||
};
|
||||
|
||||
type HomeSession = {
|
||||
bootstrapped: boolean;
|
||||
cache: HomeCatalogCache | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'dukang_home_catalog_session_v1';
|
||||
|
||||
let memory: HomeSession | null = null;
|
||||
|
||||
function emptySession(): HomeSession {
|
||||
return { bootstrapped: false, cache: null };
|
||||
}
|
||||
|
||||
function readSession(): HomeSession {
|
||||
if (memory) return memory;
|
||||
try {
|
||||
const raw = Taro.getStorageSync(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
memory = emptySession();
|
||||
return memory;
|
||||
}
|
||||
const parsed = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Partial<HomeSession>;
|
||||
memory = {
|
||||
bootstrapped: !!parsed.bootstrapped,
|
||||
cache: (parsed.cache as HomeCatalogCache | null) ?? null,
|
||||
};
|
||||
return memory;
|
||||
} catch {
|
||||
memory = emptySession();
|
||||
return memory;
|
||||
}
|
||||
}
|
||||
|
||||
function writeSession(next: HomeSession) {
|
||||
memory = next;
|
||||
try {
|
||||
Taro.setStorageSync(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* ignore quota */
|
||||
}
|
||||
}
|
||||
|
||||
export function isHomeCatalogBootstrapped(): boolean {
|
||||
return readSession().bootstrapped;
|
||||
}
|
||||
|
||||
export function getHomeCatalogCache(): HomeCatalogCache | null {
|
||||
return readSession().cache;
|
||||
}
|
||||
|
||||
export function setHomeCatalogCache(cache: HomeCatalogCache): void {
|
||||
writeSession({ bootstrapped: true, cache });
|
||||
}
|
||||
|
||||
export function resetHomeCatalogBootstrap(): void {
|
||||
memory = emptySession();
|
||||
try {
|
||||
Taro.removeStorageSync(STORAGE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 微信小程序基础库无 Intl。业务代码已避免依赖,此处仅作兜底,
|
||||
* 防止旧包 / 依赖偶发 `new Intl.DateTimeFormat` 直接白屏。
|
||||
*/
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
function shanghaiParts(date: Date) {
|
||||
const sh = new Date(date.getTime() + 8 * 60 * 60 * 1000);
|
||||
return {
|
||||
year: String(sh.getUTCFullYear()),
|
||||
month: pad(sh.getUTCMonth() + 1),
|
||||
day: pad(sh.getUTCDate()),
|
||||
hour: pad(sh.getUTCHours()),
|
||||
minute: pad(sh.getUTCMinutes()),
|
||||
second: pad(sh.getUTCSeconds()),
|
||||
};
|
||||
}
|
||||
|
||||
function installIntlStub() {
|
||||
const root = (typeof globalThis !== 'undefined'
|
||||
? globalThis
|
||||
: typeof global !== 'undefined'
|
||||
? global
|
||||
: typeof wx !== 'undefined'
|
||||
? wx
|
||||
: {}) as typeof globalThis & { Intl?: typeof Intl };
|
||||
|
||||
if (typeof root.Intl !== 'undefined' && typeof root.Intl.DateTimeFormat === 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
class MiniDateTimeFormat {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
constructor(_locales?: string | string[], _options?: Record<string, unknown>) {}
|
||||
|
||||
format(date?: Date | number) {
|
||||
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const p = shanghaiParts(d);
|
||||
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
|
||||
}
|
||||
|
||||
formatToParts(date?: Date | number) {
|
||||
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
||||
if (Number.isNaN(d.getTime())) return [];
|
||||
const p = shanghaiParts(d);
|
||||
return [
|
||||
{ type: 'year', value: p.year },
|
||||
{ type: 'literal', value: '-' },
|
||||
{ type: 'month', value: p.month },
|
||||
{ type: 'literal', value: '-' },
|
||||
{ type: 'day', value: p.day },
|
||||
{ type: 'literal', value: ' ' },
|
||||
{ type: 'hour', value: p.hour },
|
||||
{ type: 'literal', value: ':' },
|
||||
{ type: 'minute', value: p.minute },
|
||||
{ type: 'literal', value: ':' },
|
||||
{ type: 'second', value: p.second },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
root.Intl = {
|
||||
DateTimeFormat: MiniDateTimeFormat,
|
||||
} as unknown as typeof Intl;
|
||||
}
|
||||
|
||||
installIntlStub();
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,9 @@
|
||||
/** 金额展示(不依赖 Intl / toLocaleString,兼容微信小程序) */
|
||||
export function formatMoney(amount: number | string): string {
|
||||
const n = typeof amount === 'number' ? amount : Number(amount);
|
||||
if (!Number.isFinite(n)) return '0.00';
|
||||
const fixed = n.toFixed(2);
|
||||
const [intPart, dec] = fixed.split('.');
|
||||
const withComma = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
return `${withComma}.${dec}`;
|
||||
}
|
||||
@@ -106,6 +106,8 @@ export function tabNavContentStyle(metrics: NavBarMetrics): Record<string, strin
|
||||
/** 子页/内页顶栏:标题全屏居中,内容区单独留白 */
|
||||
export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, string | number> {
|
||||
const pagePad = 20;
|
||||
// 标题两侧取「右侧避让胶囊」宽度,保证相对屏幕视觉居中
|
||||
const titlePad = Math.max(metrics.navBarPaddingRight, 72);
|
||||
return {
|
||||
paddingTop: `${metrics.statusBarHeight}px`,
|
||||
height: `${metrics.navBarHeight}px`,
|
||||
@@ -113,7 +115,7 @@ export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, strin
|
||||
'--nav-content-height': `${metrics.navContentHeight}px`,
|
||||
'--nav-status-bar-height': `${metrics.statusBarHeight}px`,
|
||||
'--nav-padding-left': `${pagePad}px`,
|
||||
'--nav-padding-right': `${metrics.navBarPaddingRight}px`,
|
||||
'--nav-padding-right': `${titlePad}px`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ export type StoresSessionCategory = {
|
||||
export type StoresListCache = {
|
||||
cityKey: string;
|
||||
cityCode: string;
|
||||
/** 登录态指纹:token 变化时需重新拉取(白名单) */
|
||||
authKey: string;
|
||||
listRegion: StoresSessionRegion;
|
||||
items: unknown[];
|
||||
filterRegion: StoresSessionRegion;
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
||||
|
||||
type BenefitSummary = {
|
||||
@@ -38,10 +39,6 @@ type RedeemHistoryItem = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function usagePercent(coupon: CouponItem) {
|
||||
const total = Number(coupon.totalAmount);
|
||||
if (total <= 0) return 0;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
@@ -13,7 +13,12 @@ import CouponBadge from '../../components/CouponBadge';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||
import { getToken, isLoggedIn, request, toast } from '../../lib/api';
|
||||
import {
|
||||
getHomeCatalogCache,
|
||||
isHomeCatalogBootstrapped,
|
||||
setHomeCatalogCache,
|
||||
} from '../../lib/home-catalog-session';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { capturePromoSceneAndTouchScan } from '../../lib/promo';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
@@ -29,7 +34,6 @@ import {
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
|
||||
type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -110,35 +114,60 @@ export default function HomePage() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadProducts = useCallback(() => {
|
||||
setLoading(true);
|
||||
return request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(cityCode)}`)
|
||||
.then((list) =>
|
||||
setProducts(Array.isArray(list) ? list.map((p) => normalizeFulfillmentFlags(p)) : []),
|
||||
)
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [cityCode]);
|
||||
const applyProductList = useCallback((list: Product[], nextCode: string, authKey: string) => {
|
||||
const normalized = Array.isArray(list) ? list.map((p) => normalizeFulfillmentFlags(p)) : [];
|
||||
setProducts(normalized);
|
||||
setHomeCatalogCache({ cityCode: nextCode, authKey, products: normalized });
|
||||
}, []);
|
||||
|
||||
const fetchProducts = useCallback(
|
||||
(nextCode: string, authKey: string) => {
|
||||
setLoading(true);
|
||||
return request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`)
|
||||
.then((list) => applyProductList(list, nextCode, authKey))
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[applyProductList],
|
||||
);
|
||||
|
||||
/**
|
||||
* 首次进入 / 城市或登录态变化:拉商品。
|
||||
* 同次再切 tab:只同步选中态,不重复请求(对齐门店页)。
|
||||
*/
|
||||
useDidShow(() => {
|
||||
syncTabBarSelected(0);
|
||||
void capturePromoSceneAndTouchScan();
|
||||
void loadMiniHome();
|
||||
// 白名单商品按登录手机号过滤;登录后 switchTab 回首页不会卸载页面,须重新拉列表
|
||||
void loadProducts();
|
||||
void resolveUserCity().then((resolved) => {
|
||||
setDisplayCity(resolved.displayCity);
|
||||
setCityCode(getCityCodeForCatalog(resolved));
|
||||
});
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
void loadProducts();
|
||||
}, [loadProducts]);
|
||||
const authKey = getToken() || '';
|
||||
void (async () => {
|
||||
const resolved = await resolveUserCity();
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
setDisplayCity(resolved.displayCity);
|
||||
setCityCode(nextCode);
|
||||
|
||||
const cache = getHomeCatalogCache();
|
||||
if (
|
||||
isHomeCatalogBootstrapped() &&
|
||||
cache &&
|
||||
cache.cityCode === nextCode &&
|
||||
cache.authKey === authKey &&
|
||||
Array.isArray(cache.products)
|
||||
) {
|
||||
setProducts(cache.products as Product[]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await fetchProducts(nextCode, authKey);
|
||||
})();
|
||||
});
|
||||
|
||||
usePullDownRefresh(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const authKey = getToken() || '';
|
||||
const resolved = await resolveUserCity();
|
||||
setDisplayCity(resolved.displayCity);
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
@@ -148,7 +177,11 @@ export default function HomePage() {
|
||||
request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
|
||||
loadMiniHome(),
|
||||
]);
|
||||
setProducts(Array.isArray(list) ? list.map((p) => normalizeFulfillmentFlags(p)) : []);
|
||||
applyProductList(
|
||||
Array.isArray(list) ? list : [],
|
||||
nextCode,
|
||||
authKey,
|
||||
);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
@@ -157,7 +190,6 @@ export default function HomePage() {
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
function openProductDetail(id: string) {
|
||||
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ import iconStores from '../../assets/icons/可用门店.png';
|
||||
import iconCs from '../../assets/icons/联系客服.png';
|
||||
import iconQualification from '../../assets/icons/资质公示.png';
|
||||
import iconAbout from '../../assets/icons/关于我们.png';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const ORDER_SHORTCUTS = [
|
||||
{ tab: 'pending_pay', icon: iconPendingPay, label: '待付款' },
|
||||
@@ -54,10 +55,6 @@ const SERVICES = [
|
||||
|
||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export default function MinePage() {
|
||||
const [authed, setAuthed] = useState(() => isLoggedIn());
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||
|
||||
@@ -75,11 +75,12 @@ export default function OrderConfirmPickupPage() {
|
||||
const canSubmit = !!preview && quantityOk && !loading && !previewLoading;
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < 1) return;
|
||||
if (next < minQty) {
|
||||
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
@@ -101,8 +102,12 @@ export default function OrderConfirmPickupPage() {
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit) {
|
||||
if (!quantityOk) setMsg(`现场提货至少购买 ${minQty} 瓶`);
|
||||
return;
|
||||
if (!quantityOk) {
|
||||
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=${quantity}`;
|
||||
@@ -191,8 +196,8 @@ export default function OrderConfirmPickupPage() {
|
||||
<Text>购买数量</Text>
|
||||
<View className="order-qty-controls">
|
||||
<View
|
||||
className={`order-qty-btn${quantity <= minQty ? ' order-qty-btn--disabled' : ''}`}
|
||||
onClick={() => updateQuantity(Math.max(minQty, quantity - 1))}
|
||||
className="order-qty-btn"
|
||||
onClick={() => updateQuantity(quantity - 1)}
|
||||
>
|
||||
<Text>−</Text>
|
||||
</View>
|
||||
|
||||
@@ -167,14 +167,14 @@ export default function OrderConfirmPage() {
|
||||
: '';
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < 1) return;
|
||||
if (next < minQty) {
|
||||
const tip = isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
setQuantity(Math.max(1, next));
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
@@ -352,7 +352,7 @@ export default function OrderConfirmPage() {
|
||||
<Text>购买数量</Text>
|
||||
<View className="order-qty-controls">
|
||||
<View
|
||||
className={`order-qty-btn${quantity <= 1 ? ' order-qty-btn--disabled' : ''}`}
|
||||
className="order-qty-btn"
|
||||
onClick={() => updateQuantity(quantity - 1)}
|
||||
>
|
||||
<Text>−</Text>
|
||||
|
||||
@@ -181,12 +181,15 @@ export default function OrderDetailPage() {
|
||||
<SubPageHeader
|
||||
title="订单详情"
|
||||
onBack={() => {
|
||||
const pages = Taro.getCurrentPages();
|
||||
if (pages.length > 1) {
|
||||
Taro.navigateBack();
|
||||
// 支付完成后 reLaunch 进详情:栈仅一页时 navigateBack 会退出小程序,统一回首页
|
||||
const fromPay = String(router.params.from || '') === 'pay';
|
||||
if (fromPay || Taro.getCurrentPages().length <= 1) {
|
||||
Taro.switchTab({ url: '/pages/home/index' }).catch(() => {
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
});
|
||||
return;
|
||||
}
|
||||
Taro.switchTab({ url: '/pages/home/index' });
|
||||
Taro.navigateBack();
|
||||
}}
|
||||
right={<ShareNavButton payload={sharePayload} />}
|
||||
/>
|
||||
|
||||
@@ -95,7 +95,11 @@ export default function OrdersPage() {
|
||||
<PageShell variant="sub" className="orders-page">
|
||||
<SubPageHeader
|
||||
title="我的订单"
|
||||
onBack={() => Taro.switchTab({ url: '/pages/home/index' })}
|
||||
onBack={() => {
|
||||
Taro.switchTab({ url: '/pages/home/index' }).catch(() => {
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<View className="order-tabs">
|
||||
{TABS.map((t) => (
|
||||
|
||||
@@ -144,10 +144,10 @@ export default function PayPage() {
|
||||
toast('支付成功', 'success');
|
||||
}
|
||||
if (deliveryType === 'ON_SITE_PICKUP') {
|
||||
// 现场提货支付即完成 → 订单详情(已完成);reLaunch 清掉商品详情栈
|
||||
Taro.reLaunch({ url: `/pages/order-detail/index?id=${orderId}` });
|
||||
// 现场提货支付即完成 → 订单详情;from=pay 返回强制回首页,避免 navigateBack 退出小程序
|
||||
Taro.reLaunch({ url: `/pages/order-detail/index?id=${orderId}&from=pay` });
|
||||
} else {
|
||||
Taro.reLaunch({ url: '/pages/orders/index?tab=paid' });
|
||||
Taro.reLaunch({ url: '/pages/orders/index?tab=paid&from=pay' });
|
||||
}
|
||||
} catch (e) {
|
||||
if (isWechatAuthRequiredError(e)) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import PageShell from '../../components/PageShell';
|
||||
import RedeemQrCode from '../../components/RedeemQrCode';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const POLL_INTERVAL_MS = 2500;
|
||||
const LAST_REDEEM_RECORD_KEY = 'lastRedeemRecordId';
|
||||
@@ -26,10 +27,6 @@ type RedeemTokenStatus =
|
||||
}
|
||||
| { status: 'EXPIRED' };
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function formatTimer(seconds: number) {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
@@ -44,6 +41,20 @@ export default function RedeemCodePage() {
|
||||
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const successHandled = useRef(false);
|
||||
const lastTokenTapAt = useRef(0);
|
||||
|
||||
function onTokenTap() {
|
||||
if (!token) return;
|
||||
const now = Date.now();
|
||||
if (now - lastTokenTapAt.current < 350) {
|
||||
lastTokenTapAt.current = 0;
|
||||
void Taro.setClipboardData({ data: token })
|
||||
.then(() => toast('核销码编号已复制', 'success'))
|
||||
.catch(() => toast('复制失败'));
|
||||
return;
|
||||
}
|
||||
lastTokenTapAt.current = now;
|
||||
}
|
||||
|
||||
const stopTimer = useCallback(() => {
|
||||
if (timerRef.current != null) {
|
||||
@@ -144,9 +155,10 @@ export default function RedeemCodePage() {
|
||||
<Text className="u-muted">待核销金额</Text>
|
||||
<Text className="redeem-code-amount">¥ {formatMoney(amount)}</Text>
|
||||
{token ? (
|
||||
<View className="redeem-code-token-wrap">
|
||||
<View className="redeem-code-token-wrap" onClick={onTokenTap}>
|
||||
<Text className="redeem-code-token-label">核销码编号(供追查)</Text>
|
||||
<Text className="redeem-code-token">{token}</Text>
|
||||
<Text className="redeem-code-token-hint">双击复制</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -4,6 +4,8 @@ import Taro, { useRouter } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const LAST_REDEEM_RESULT_KEY = 'lastRedeemResult';
|
||||
|
||||
@@ -16,8 +18,9 @@ type RedeemRecord = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
/** 与权益「历史记录」一致:2026-08-03 13:53:03(Asia/Shanghai) */
|
||||
function formatChinaDateTime(input?: string | null) {
|
||||
return formatShanghaiDateTime(input ?? new Date());
|
||||
}
|
||||
|
||||
function StarRating({
|
||||
@@ -65,9 +68,7 @@ export default function RedeemSuccessPage() {
|
||||
const amount = Number(record?.amount ?? router.params.amount ?? 0);
|
||||
const storeName = record?.storeName || '门店';
|
||||
const redeemNo = record?.redeemNo || '—';
|
||||
const redeemedAt = record?.createdAt
|
||||
? new Date(record.createdAt).toLocaleString('zh-CN')
|
||||
: new Date().toLocaleString('zh-CN');
|
||||
const redeemedAt = formatChinaDateTime(record?.createdAt);
|
||||
|
||||
function clearCache() {
|
||||
try {
|
||||
|
||||
@@ -5,6 +5,7 @@ import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
type BenefitSummary = {
|
||||
totalBalance: number;
|
||||
@@ -13,10 +14,6 @@ type BenefitSummary = {
|
||||
|
||||
const MIN_REDEEM_AMOUNT = 0.01;
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 核销金额输入清洗:
|
||||
* - 只保留数字与一个小数点
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { usePageScroll, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
useLoad,
|
||||
usePageScroll,
|
||||
useRouter,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import PageNavBar from '../../components/PageNavBar';
|
||||
import ProductCarousel from '../../components/ProductCarousel';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -43,6 +52,13 @@ type Store = {
|
||||
category?: { name: string } | null;
|
||||
};
|
||||
|
||||
type RecentRedeem = {
|
||||
userLabel: string;
|
||||
amount: number | string;
|
||||
createdAt: string;
|
||||
text?: string;
|
||||
};
|
||||
|
||||
function uniqueUrls(urls: Array<string | null | undefined>) {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
@@ -68,30 +84,145 @@ function fullAddress(store: Store) {
|
||||
return `${store.province || ''}${city}${store.district || ''}${store.address || ''}`.trim();
|
||||
}
|
||||
|
||||
function pickStoreId(raw?: string | null) {
|
||||
return String(raw || '')
|
||||
.trim()
|
||||
.replace(/[^\d]/g, '');
|
||||
}
|
||||
|
||||
/** 与历史记录一致:2026-08-03 15:14:30(Asia/Shanghai) */
|
||||
function formatRedeemTime(input?: string | null) {
|
||||
return formatShanghaiDateTime(input);
|
||||
}
|
||||
|
||||
function formatRedeemAmountYuan(amount: number | string) {
|
||||
const n = typeof amount === 'number' ? amount : Number(amount);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
if (Math.abs(n - Math.round(n)) < 1e-9) return String(Math.round(n));
|
||||
return n.toFixed(2).replace(/\.?0+$/, '');
|
||||
}
|
||||
|
||||
function formatRecentRedeemLine(row: RecentRedeem) {
|
||||
try {
|
||||
// 优先用服务端拼好的 text,避免客户端时区 / Intl 差异
|
||||
if (row.text?.trim()) return row.text.trim();
|
||||
const label = String(row.userLabel || '用户***').trim() || '用户***';
|
||||
const rawTime = String(row.createdAt || '').trim();
|
||||
const time =
|
||||
/^\d{4}-\d{2}-\d{2}/.test(rawTime)
|
||||
? rawTime.slice(0, 19).replace('T', ' ')
|
||||
: formatRedeemTime(row.createdAt);
|
||||
const amount = formatRedeemAmountYuan(row.amount);
|
||||
return `${label} ${time} 核销${amount}元`;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRecentRedeems(payload: unknown): RecentRedeem[] {
|
||||
try {
|
||||
if (Array.isArray(payload)) return payload as RecentRedeem[];
|
||||
if (payload && typeof payload === 'object') {
|
||||
const list =
|
||||
(payload as { list?: unknown; items?: unknown; data?: unknown }).list ??
|
||||
(payload as { items?: unknown }).items ??
|
||||
(payload as { data?: unknown }).data;
|
||||
if (Array.isArray(list)) return list as RecentRedeem[];
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export default function StoreDetailPage() {
|
||||
const router = useRouter();
|
||||
const storeId = router.params.id ?? '';
|
||||
const [storeId, setStoreId] = useState(() => pickStoreId(router.params.id));
|
||||
const [store, setStore] = useState<Store | null>(null);
|
||||
const [recentRedeems, setRecentRedeems] = useState<RecentRedeem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [headerSolid, setHeaderSolid] = useState(false);
|
||||
const storeRef = useRef<Store | null>(null);
|
||||
storeRef.current = store;
|
||||
|
||||
usePageScroll(({ scrollTop }) => {
|
||||
setHeaderSolid(scrollTop > 100);
|
||||
});
|
||||
|
||||
const loadStore = useCallback(async (id: string) => {
|
||||
if (!id) {
|
||||
setLoading(false);
|
||||
setLoadError('缺少门店参数');
|
||||
return;
|
||||
}
|
||||
setLoadError('');
|
||||
if (!storeRef.current) setLoading(true);
|
||||
try {
|
||||
const data = await request<Store>(`/stores/${id}`);
|
||||
if (!data || !data.id) {
|
||||
setStore(null);
|
||||
setLoadError('门店不存在或暂不可见');
|
||||
toast('门店不存在或暂不可见');
|
||||
return;
|
||||
}
|
||||
setStore(data);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '加载失败';
|
||||
setLoadError(msg);
|
||||
if (!storeRef.current) toast(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadRecentRedeems = useCallback(async (id: string) => {
|
||||
if (!id) {
|
||||
setRecentRedeems([]);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const list = await request<unknown>(`/stores/${id}/recent-redeems?limit=20`);
|
||||
setRecentRedeems(normalizeRecentRedeems(list));
|
||||
} catch {
|
||||
setRecentRedeems([]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const bootstrap = useCallback(
|
||||
(id: string) => {
|
||||
const nextId = pickStoreId(id);
|
||||
if (!nextId) {
|
||||
setLoading(false);
|
||||
setLoadError('缺少门店参数');
|
||||
return;
|
||||
}
|
||||
setStoreId(nextId);
|
||||
void loadStore(nextId);
|
||||
void loadRecentRedeems(nextId);
|
||||
},
|
||||
[loadStore, loadRecentRedeems],
|
||||
);
|
||||
|
||||
// 首屏:useLoad 带 options.id,比仅用 useDidShow 更稳(H5/小程序都覆盖)
|
||||
useLoad((options) => {
|
||||
bootstrap(options?.id || router.params.id || '');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!storeId) return;
|
||||
request<Store>(`/stores/${storeId}`)
|
||||
.then(setStore)
|
||||
.catch(() => {
|
||||
request<Store[]>('/stores')
|
||||
.then((list) => {
|
||||
const found = (Array.isArray(list) ? list : []).find((s) => s.id === storeId);
|
||||
if (found) setStore(found);
|
||||
else toast('门店不存在');
|
||||
})
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
});
|
||||
}, [storeId]);
|
||||
const fromRouter = pickStoreId(router.params.id);
|
||||
if (fromRouter && fromRouter !== storeId) {
|
||||
bootstrap(fromRouter);
|
||||
}
|
||||
}, [router.params.id, storeId, bootstrap]);
|
||||
|
||||
// 登录态变化后回到本页:重拉详情与走马灯
|
||||
useDidShow(() => {
|
||||
const id = pickStoreId(storeId || router.params.id);
|
||||
if (!id) return;
|
||||
void loadStore(id);
|
||||
void loadRecentRedeems(id);
|
||||
});
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => {
|
||||
@@ -106,6 +237,11 @@ export default function StoreDetailPage() {
|
||||
[store, storeId],
|
||||
);
|
||||
|
||||
const marqueeLines = useMemo(
|
||||
() => recentRedeems.map(formatRecentRedeemLine).filter(Boolean),
|
||||
[recentRedeems],
|
||||
);
|
||||
|
||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||
useShareTimeline(() => ({
|
||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
||||
@@ -161,7 +297,9 @@ export default function StoreDetailPage() {
|
||||
return (
|
||||
<PageShell variant="scroll" className="store-detail-page">
|
||||
<PageNavBar title="门店详情" solid onBack={goBack} />
|
||||
<View className="page-with-nav-bar u-empty">加载中…</View>
|
||||
<View className="page-with-nav-bar u-empty">
|
||||
{loading ? '加载中…' : loadError || '门店不存在或暂不可见'}
|
||||
</View>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -245,6 +383,12 @@ export default function StoreDetailPage() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{marqueeLines.length > 0 ? (
|
||||
<View className="store-detail-marquee-wrap">
|
||||
<StoreRedeemMarquee key={marqueeLines.join('|')} lines={marqueeLines} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{intro ? (
|
||||
<View className="store-detail-section">
|
||||
<Text className="store-detail-section-title">门店详情</Text>
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
} from '../../lib/user-location';
|
||||
import { FALLBACK_CITY_CODE } from '../../lib/product-images';
|
||||
import { formatDistanceMeters } from '../../lib/geo';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { getToken, request, toast } from '../../lib/api';
|
||||
import {
|
||||
getStoresListCache,
|
||||
isStoresSessionBootstrapped,
|
||||
@@ -143,6 +143,7 @@ export default function StoresPage() {
|
||||
setStoresListCache({
|
||||
cityKey,
|
||||
cityCode: nextCode,
|
||||
authKey: getToken() || '',
|
||||
listRegion: toCityWideRegion(listRegion),
|
||||
items,
|
||||
filterRegion,
|
||||
@@ -160,12 +161,38 @@ export default function StoresPage() {
|
||||
|
||||
/**
|
||||
* 首次进入:弹窗 + 定位 + 拉列表。
|
||||
* 同次再切回:只同步 tab 选中态,不改筛选、不拉接口、不 setState。
|
||||
* 同次再切回:只同步 tab 选中态(登录态未变)。
|
||||
* 登录/退出后 token 变化:按缓存失效重新拉列表(白名单)。
|
||||
*/
|
||||
useDidShow(() => {
|
||||
syncTabBarSelected(1);
|
||||
|
||||
const authKey = getToken() || '';
|
||||
const cache = getStoresListCache();
|
||||
if (isStoresSessionBootstrapped()) {
|
||||
if (cache && (cache.authKey ?? '') === authKey) {
|
||||
return;
|
||||
}
|
||||
// 登录态变了:保留筛选,重新拉列表
|
||||
void (async () => {
|
||||
setLoading(true);
|
||||
const nextCode = cache?.cityCode || FALLBACK_CITY_CODE;
|
||||
const listRegion = cache?.listRegion
|
||||
? {
|
||||
province: cache.listRegion.province,
|
||||
city: cache.listRegion.city,
|
||||
district: cache.listRegion.district || '全部',
|
||||
}
|
||||
: regionRef.current;
|
||||
const nextCityKey = cache?.cityKey || makeCityKey(listRegion);
|
||||
await fetchStores(
|
||||
nextCode,
|
||||
readCachedUserCoords(),
|
||||
nextCityKey,
|
||||
listRegion,
|
||||
regionRef.current,
|
||||
);
|
||||
})();
|
||||
return;
|
||||
}
|
||||
markStoresSessionBootstrapped();
|
||||
|
||||
@@ -203,7 +203,8 @@
|
||||
height: var(--nav-content-height);
|
||||
line-height: var(--nav-content-height);
|
||||
text-align: center;
|
||||
padding: 0 88px 0 56px;
|
||||
/* 左右等宽留白,避免右侧分享/胶囊导致标题视觉偏左 */
|
||||
padding: 0 max(72px, var(--nav-padding-right, 96px));
|
||||
box-sizing: border-box;
|
||||
opacity: 0;
|
||||
font-family: var(--font-headline);
|
||||
|
||||
@@ -304,9 +304,19 @@
|
||||
display: block;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 11px;
|
||||
word-break: break-all;
|
||||
color: var(--color-on-surface);
|
||||
line-height: 1.5;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.redeem-code-token-hint {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--color-subtle-gray);
|
||||
}
|
||||
|
||||
.redeem-success-icon {
|
||||
|
||||
@@ -127,6 +127,36 @@
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.store-detail-marquee-wrap {
|
||||
margin: 0 var(--space-page) 12px;
|
||||
}
|
||||
|
||||
.store-detail-marquee {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-radius: 8px;
|
||||
background: #fff7f6;
|
||||
border: 1px solid rgba(166, 29, 36, 0.12);
|
||||
overflow: hidden;
|
||||
height: 40px;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.store-detail-marquee-inner {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
margin-top: -10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-detail-marquee-text {
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
color: #a61d24;
|
||||
}
|
||||
|
||||
.store-detail-section {
|
||||
background: var(--color-card);
|
||||
margin: 0 var(--space-page) 16px;
|
||||
|
||||
@@ -15,6 +15,9 @@ import {
|
||||
classifyRedeemClientError,
|
||||
generateRedeemPendingNo,
|
||||
REDEEM_WEAKNET_FAIL_THRESHOLD,
|
||||
sumUnbilledPayoutAmount,
|
||||
validateStoreWithdraw,
|
||||
pickPayoutsForWithdrawAmount,
|
||||
} from './index';
|
||||
|
||||
describe('calcBenefitAmount', () => {
|
||||
@@ -235,3 +238,53 @@ describe('generateRedeemPendingNo', () => {
|
||||
expect(REDEEM_WEAKNET_FAIL_THRESHOLD).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sumUnbilledPayoutAmount', () => {
|
||||
it('sums payout amounts', () => {
|
||||
expect(sumUnbilledPayoutAmount([{ payoutAmount: 60 }, { payoutAmount: 40.5 }])).toBe(100.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateStoreWithdraw', () => {
|
||||
const base = {
|
||||
availableAmount: 1000,
|
||||
requestAmount: 200,
|
||||
todayApplied: 0,
|
||||
dailyLimit: 5000,
|
||||
hasPendingRequest: false,
|
||||
hasBankAccount: true,
|
||||
};
|
||||
|
||||
it('rejects when daily limit exceeded', () => {
|
||||
expect(
|
||||
validateStoreWithdraw({ ...base, todayApplied: 4900, requestAmount: 200, dailyLimit: 5000 }).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects pending request / missing bank / over available', () => {
|
||||
expect(validateStoreWithdraw({ ...base, hasPendingRequest: true }).ok).toBe(false);
|
||||
expect(validateStoreWithdraw({ ...base, hasBankAccount: false }).ok).toBe(false);
|
||||
expect(validateStoreWithdraw({ ...base, requestAmount: 1001 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts valid request', () => {
|
||||
expect(validateStoreWithdraw(base).ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pickPayoutsForWithdrawAmount', () => {
|
||||
it('picks FIFO exact match', () => {
|
||||
const rows = [{ payoutAmount: 60 }, { payoutAmount: 40 }, { payoutAmount: 30 }];
|
||||
const r = pickPayoutsForWithdrawAmount(rows, 100);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.selected).toHaveLength(2);
|
||||
expect(r.amount).toBe(100);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects non-exact match', () => {
|
||||
const rows = [{ payoutAmount: 60 }, { payoutAmount: 40 }];
|
||||
expect(pickPayoutsForWithdrawAmount(rows, 50).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,6 +96,81 @@ export function calcRedeemSettleAmount(amount: number, settlementRate: number):
|
||||
return Math.round(amount * settlementRate * 100) / 100;
|
||||
}
|
||||
|
||||
export function sumUnbilledPayoutAmount(payouts: Array<{ payoutAmount: number }>): number {
|
||||
return Math.round(payouts.reduce((sum, p) => sum + Number(p.payoutAmount || 0), 0) * 100) / 100;
|
||||
}
|
||||
|
||||
export type ValidateStoreWithdrawInput = {
|
||||
availableAmount: number;
|
||||
requestAmount: number;
|
||||
todayApplied: number;
|
||||
dailyLimit: number;
|
||||
hasPendingRequest: boolean;
|
||||
hasBankAccount: boolean;
|
||||
};
|
||||
|
||||
/** 门店未出账提现护栏(FIN-002 单日上限 + 幂等/账户) */
|
||||
export function validateStoreWithdraw(
|
||||
input: ValidateStoreWithdrawInput,
|
||||
): { ok: boolean; message?: string } {
|
||||
if (!input.hasBankAccount) {
|
||||
return { ok: false, message: '请先完善入驻收款账户后再提现' };
|
||||
}
|
||||
if (input.hasPendingRequest) {
|
||||
return { ok: false, message: '已有待审核提现申请,请等待处理完成' };
|
||||
}
|
||||
if (!(input.requestAmount > 0)) {
|
||||
return { ok: false, message: '提现金额必须大于 0' };
|
||||
}
|
||||
if (input.requestAmount > input.availableAmount + 1e-9) {
|
||||
return { ok: false, message: '提现金额不能超过可提未出账余额' };
|
||||
}
|
||||
const remaining = Math.round((input.dailyLimit - input.todayApplied) * 100) / 100;
|
||||
if (remaining <= 0) {
|
||||
return { ok: false, message: `已达单店单日提现上限 ¥${input.dailyLimit.toFixed(2)}` };
|
||||
}
|
||||
if (input.requestAmount > remaining + 1e-9) {
|
||||
return {
|
||||
ok: false,
|
||||
message: `超过单日剩余额度 ¥${remaining.toFixed(2)}(上限 ¥${input.dailyLimit.toFixed(2)})`,
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 FIFO 选取未出账 payout,使合计尽量等于 targetAmount(不超过目标)。
|
||||
* 若无法精确凑齐,返回合计 ≤ target 的最长前缀子集。
|
||||
*/
|
||||
export function pickPayoutsForWithdrawAmount<T extends { payoutAmount: number }>(
|
||||
payoutsAsc: T[],
|
||||
targetAmount: number,
|
||||
): { ok: true; selected: T[]; amount: number } | { ok: false; message: string } {
|
||||
if (!(targetAmount > 0)) return { ok: false, message: '提现金额必须大于 0' };
|
||||
const selected: T[] = [];
|
||||
let sum = 0;
|
||||
for (const p of payoutsAsc) {
|
||||
const next = Math.round((sum + Number(p.payoutAmount)) * 100) / 100;
|
||||
if (next <= targetAmount + 1e-9) {
|
||||
selected.push(p);
|
||||
sum = next;
|
||||
if (Math.abs(sum - targetAmount) < 1e-9) break;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!selected.length) {
|
||||
return { ok: false, message: '无可匹配的未出账结算明细,请调整提现金额' };
|
||||
}
|
||||
if (Math.abs(sum - targetAmount) > 1e-9) {
|
||||
return {
|
||||
ok: false,
|
||||
message: `无法按 ¥${targetAmount.toFixed(2)} 精确匹配明细,请按可提总额全额提现或调整金额`,
|
||||
};
|
||||
}
|
||||
return { ok: true, selected, amount: sum };
|
||||
}
|
||||
|
||||
const TIME_HM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
||||
|
||||
export type BusinessHoursSegment = { open: string; close: string };
|
||||
|
||||
@@ -32,6 +32,7 @@ export const HQ_PERMISSION_CATALOG = [
|
||||
{ key: 'system_settings_app', label: '应用链接', group: '系统设置' },
|
||||
{ key: 'system_settings_deploy', label: '发布部署', group: '系统设置' },
|
||||
{ key: 'system_settings_winery_bank', label: '酒厂银行账户', group: '系统设置' },
|
||||
{ key: 'system_settings_finance', label: '财务结算', group: '系统设置' },
|
||||
] as const;
|
||||
|
||||
export type HqPermissionKey = (typeof HQ_PERMISSION_CATALOG)[number]['key'];
|
||||
@@ -61,6 +62,7 @@ export const SYSTEM_CONFIG_GROUP_PERMISSION: Record<string, HqPermissionKey> = {
|
||||
app: 'system_settings_app',
|
||||
deploy: 'system_settings_deploy',
|
||||
winery_bank: 'system_settings_winery_bank',
|
||||
finance: 'system_settings_finance',
|
||||
};
|
||||
|
||||
export const SYSTEM_SETTINGS_PERMISSION_KEYS = Object.values(
|
||||
@@ -127,6 +129,7 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
|
||||
'invoices',
|
||||
'logs',
|
||||
'system_settings_winery_bank',
|
||||
'system_settings_finance',
|
||||
],
|
||||
CUSTOMER_SERVICE: [
|
||||
'dashboard',
|
||||
|
||||
@@ -19,14 +19,39 @@ export interface RedeemPreviewDto {
|
||||
boundStoreId?: string | null;
|
||||
}
|
||||
|
||||
/** 门店核销方式 */
|
||||
export type RedeemChannel = 'SCAN' | 'PHONE';
|
||||
|
||||
export const REDEEM_CHANNEL_LABELS: Record<RedeemChannel, string> = {
|
||||
SCAN: '扫码核销',
|
||||
PHONE: '手机号核销',
|
||||
};
|
||||
|
||||
export interface RedeemRecordDto {
|
||||
id: string;
|
||||
redeemNo: string;
|
||||
amount: number;
|
||||
settleAmount: number;
|
||||
/** 核销方式:扫码 SCAN / 手机号 PHONE */
|
||||
channel?: RedeemChannel;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface RedeemChannelStatsBucket {
|
||||
channel: RedeemChannel;
|
||||
count: number;
|
||||
amount: number;
|
||||
settleAmount: number;
|
||||
}
|
||||
|
||||
export interface RedeemStatsDto {
|
||||
range: 'today' | '7d' | '30d';
|
||||
totalCount: number;
|
||||
totalAmount: number;
|
||||
totalSettleAmount: number;
|
||||
byChannel: RedeemChannelStatsBucket[];
|
||||
}
|
||||
|
||||
export interface RedeemPhoneBalanceDto {
|
||||
sessionId: string;
|
||||
totalBalance: number;
|
||||
|
||||
@@ -1,5 +1,86 @@
|
||||
export type FinancePayStatus = 'UNPAID' | 'PAID';
|
||||
|
||||
/** 门店未出账提现单日上限默认值(FIN-002,可配置) */
|
||||
export const DEFAULT_STORE_WITHDRAW_DAILY_LIMIT = 5000;
|
||||
|
||||
export type StoreWithdrawStatus = 'PENDING_REVIEW' | 'REJECTED' | 'PAID';
|
||||
|
||||
export const STORE_WITHDRAW_STATUS_LABELS: Record<StoreWithdrawStatus, string> = {
|
||||
PENDING_REVIEW: '待审核',
|
||||
REJECTED: '已驳回',
|
||||
PAID: '已结算',
|
||||
};
|
||||
|
||||
/** 总部「门店账单」统一列表:T+1 出账 / 手动提现 */
|
||||
export type StoreSettlementKind = 'T1_BILL' | 'WITHDRAW';
|
||||
|
||||
export const STORE_SETTLEMENT_KIND_LABELS: Record<StoreSettlementKind, string> = {
|
||||
T1_BILL: 'T+1出账',
|
||||
WITHDRAW: '手动提现',
|
||||
};
|
||||
|
||||
export type StoreSettlementStatus = FinancePayStatus | StoreWithdrawStatus;
|
||||
|
||||
export const STORE_SETTLEMENT_STATUS_LABELS: Record<StoreSettlementStatus, string> = {
|
||||
UNPAID: '未打款',
|
||||
PAID: '已打款',
|
||||
PENDING_REVIEW: '待审核',
|
||||
REJECTED: '已驳回',
|
||||
};
|
||||
|
||||
export interface StoreSettlementRowDto {
|
||||
kind: StoreSettlementKind;
|
||||
id: string;
|
||||
billNo: string;
|
||||
storeId: string;
|
||||
amount: number;
|
||||
status: StoreSettlementStatus;
|
||||
date: string;
|
||||
overdue?: boolean;
|
||||
redeemCount?: number | null;
|
||||
redeemAmount?: number | null;
|
||||
settlementRate?: number | null;
|
||||
payoutCount?: number | null;
|
||||
store?: {
|
||||
id: string;
|
||||
name: string;
|
||||
cityName: string;
|
||||
phone?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface StoreWithdrawBankAccountDto {
|
||||
bankAccountName?: string | null;
|
||||
bankAccountNo?: string | null;
|
||||
bankBranch?: string | null;
|
||||
}
|
||||
|
||||
export interface StoreWithdrawSummaryDto {
|
||||
availableAmount: number;
|
||||
pendingReviewAmount: number;
|
||||
todayAppliedAmount: number;
|
||||
dailyLimit: number;
|
||||
remainingDailyLimit: number;
|
||||
isPrimary: boolean;
|
||||
hasBankAccount: boolean;
|
||||
hasPendingRequest: boolean;
|
||||
bankAccount?: StoreWithdrawBankAccountDto | null;
|
||||
}
|
||||
|
||||
export interface StoreWithdrawRequestDto {
|
||||
id: string;
|
||||
withdrawNo: string;
|
||||
storeId: string;
|
||||
amount: number;
|
||||
payoutCount: number;
|
||||
status: StoreWithdrawStatus;
|
||||
rejectReason?: string | null;
|
||||
appliedAt: string;
|
||||
reviewedAt?: string | null;
|
||||
paidAt?: string | null;
|
||||
paymentRef?: string | null;
|
||||
}
|
||||
|
||||
export interface StorePayoutDto {
|
||||
id: string;
|
||||
redeemAmount: number;
|
||||
@@ -30,6 +111,19 @@ export const FINANCE_PAY_STATUS_LABELS: Record<FinancePayStatus, string> = {
|
||||
PAID: '已打款',
|
||||
};
|
||||
|
||||
export function storeSettlementStatusLabel(
|
||||
kind: StoreSettlementKind,
|
||||
status: string,
|
||||
): string {
|
||||
if (kind === 'WITHDRAW' && status in STORE_WITHDRAW_STATUS_LABELS) {
|
||||
return STORE_WITHDRAW_STATUS_LABELS[status as StoreWithdrawStatus];
|
||||
}
|
||||
if (status in FINANCE_PAY_STATUS_LABELS) {
|
||||
return FINANCE_PAY_STATUS_LABELS[status as FinancePayStatus];
|
||||
}
|
||||
return STORE_SETTLEMENT_STATUS_LABELS[status as StoreSettlementStatus] ?? status;
|
||||
}
|
||||
|
||||
export interface PartnerBillDto {
|
||||
id: string;
|
||||
billNo: string;
|
||||
|
||||
+69
-10
@@ -135,38 +135,97 @@ async function main() {
|
||||
'/shop/auth/login/sms',
|
||||
'/shop/auth/sms/send',
|
||||
);
|
||||
const shopMe = await req('SHOP_H5', '/shop/auth/me', { token: shopLogin.accessToken });
|
||||
let shopToken = shopLogin.accessToken;
|
||||
let shopMe = await req('SHOP_H5', '/shop/auth/me', { token: shopToken });
|
||||
if (!shopMe?.phone) throw new Error('Shop /shop/auth/me failed');
|
||||
const refreshed = await req('SHOP_H5', '/shop/auth/token/refresh', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ refreshToken: shopLogin.refreshToken }),
|
||||
});
|
||||
if (!refreshed?.accessToken) throw new Error('Shop token refresh failed');
|
||||
shopToken = refreshed.accessToken;
|
||||
shopMe = await req('SHOP_H5', '/shop/auth/me', { token: shopToken });
|
||||
if (!shopMe.storeId && shopMe.stores?.[0]?.storeId) {
|
||||
const selected = await req('SHOP_H5', '/shop/auth/select-store', {
|
||||
method: 'POST',
|
||||
token: shopToken,
|
||||
body: JSON.stringify({ storeId: shopMe.stores[0].storeId }),
|
||||
});
|
||||
shopToken = selected.accessToken || shopToken;
|
||||
shopMe = await req('SHOP_H5', '/shop/auth/me', { token: shopToken });
|
||||
}
|
||||
if (!shopMe.storeId) throw new Error('Shop storeId missing after select-store');
|
||||
const preview = await req('SHOP_H5', '/shop/redeem/preview', {
|
||||
method: 'POST',
|
||||
token: shopLogin.accessToken,
|
||||
token: shopToken,
|
||||
body: JSON.stringify({ token: directToken.token }),
|
||||
});
|
||||
if (!preview.amount) throw new Error('Redeem preview failed');
|
||||
await req('SHOP_H5', '/shop/redeem/confirm', {
|
||||
method: 'POST',
|
||||
token: shopLogin.accessToken,
|
||||
token: shopToken,
|
||||
body: JSON.stringify({ token: directToken.token }),
|
||||
});
|
||||
|
||||
console.log('9. Admin login + store payout');
|
||||
console.log('9. Store withdraw (OPT-010)');
|
||||
const admin = await adminLogin();
|
||||
const payouts = await req('HQ_WEB', '/admin/store-payouts?status=PENDING', {
|
||||
token: admin.accessToken,
|
||||
const shopStoreId = shopMe.storeId || shopMe.stores?.[0]?.storeId;
|
||||
if (!shopStoreId) throw new Error('Shop storeId missing after login');
|
||||
|
||||
const withdrawSummary = await req('SHOP_H5', '/shop/withdraw/summary', {
|
||||
token: shopToken,
|
||||
});
|
||||
if (!payouts.items?.length) throw new Error('Expected pending store payout');
|
||||
const payoutId = payouts.items[0].id;
|
||||
await req('HQ_WEB', `/admin/store-payouts/${payoutId}/confirm`, {
|
||||
if (!(withdrawSummary.availableAmount > 0)) {
|
||||
throw new Error('Expected available withdraw amount after redeem');
|
||||
}
|
||||
|
||||
const applied = await req('SHOP_H5', '/shop/withdraw', {
|
||||
method: 'POST',
|
||||
token: shopToken,
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
if (applied.status !== 'PENDING_REVIEW') {
|
||||
throw new Error(`Expected PENDING_REVIEW withdraw, got ${applied.status}`);
|
||||
}
|
||||
|
||||
const pendingDup = await expectFail('SHOP_H5', '/shop/withdraw', {
|
||||
method: 'POST',
|
||||
token: shopToken,
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
if (!String(pendingDup).includes('待审核')) {
|
||||
throw new Error(`Expected pending-request reject, got: ${pendingDup}`);
|
||||
}
|
||||
|
||||
// 锁定中的明细不可再出账(T+1 排除 withdrawItem)
|
||||
const summaryAfter = await req('SHOP_H5', '/shop/withdraw/summary', {
|
||||
token: shopToken,
|
||||
});
|
||||
if (summaryAfter.availableAmount !== 0) {
|
||||
throw new Error('Expected availableAmount=0 while withdraw pending');
|
||||
}
|
||||
|
||||
await req('HQ_WEB', `/admin/store-withdrawals/${applied.id}/approve`, {
|
||||
method: 'POST',
|
||||
token: admin.accessToken,
|
||||
body: JSON.stringify({ remark: 'smoke confirm' }),
|
||||
body: JSON.stringify({ paymentRef: 'smoke-withdraw' }),
|
||||
});
|
||||
|
||||
const withdrawList = await req('SHOP_H5', '/shop/withdraw/requests?status=PAID', {
|
||||
token: shopToken,
|
||||
});
|
||||
const settled = withdrawList.items?.find((w) => w.id === applied.id);
|
||||
if (!settled || settled.status !== 'PAID') {
|
||||
throw new Error('Expected settled withdraw request on shop side');
|
||||
}
|
||||
|
||||
const overdue = await req('HQ_WEB', '/admin/store-withdrawals/overdue-summary', {
|
||||
token: admin.accessToken,
|
||||
});
|
||||
if (typeof overdue.pendingCount !== 'number') {
|
||||
throw new Error('overdue-summary missing pendingCount');
|
||||
}
|
||||
|
||||
console.log('10. Refund ticket flow');
|
||||
const order2 = await req('USER_H5', '/trade/orders', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -52,6 +52,12 @@ enum RedeemPendingStatus {
|
||||
REJECTED
|
||||
}
|
||||
|
||||
/// Redeem channel: SCAN or PHONE
|
||||
enum RedeemChannel {
|
||||
SCAN
|
||||
PHONE
|
||||
}
|
||||
|
||||
enum ResourceMediaType {
|
||||
IMAGE
|
||||
VIDEO
|
||||
@@ -314,6 +320,12 @@ enum StorePayoutStatus {
|
||||
PAID
|
||||
}
|
||||
|
||||
enum StoreWithdrawStatus {
|
||||
PENDING_REVIEW
|
||||
REJECTED
|
||||
PAID
|
||||
}
|
||||
|
||||
enum ThirdPartyProvider {
|
||||
WECHAT_PAY
|
||||
WECHAT_REFUND
|
||||
@@ -1062,6 +1074,10 @@ model Store {
|
||||
openTime2 String? @map("open_time_2") @db.VarChar(8)
|
||||
closeTime2 String? @map("close_time_2") @db.VarChar(8)
|
||||
settlementRate Decimal @default(0.60) @map("settlement_rate") @db.Decimal(5, 4)
|
||||
/// Online test: only listed phones can see store on C-end when enabled
|
||||
visibilityWhitelistEnabled Boolean @default(false) @map("visibility_whitelist_enabled")
|
||||
/// FIN-001:允许未出账手动提现的白名单门店
|
||||
withdrawWhitelistEnabled Boolean @default(false) @map("withdraw_whitelist_enabled")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||
|
||||
@@ -1075,6 +1091,8 @@ model Store {
|
||||
ratings StoreRating[]
|
||||
payouts StorePayout[]
|
||||
storeBills StoreBill[]
|
||||
withdrawRequests StoreWithdrawRequest[]
|
||||
visibilityPhones StoreVisibilityPhone[]
|
||||
|
||||
@@index([cityId, status])
|
||||
@@index([partnerAccountId])
|
||||
@@ -1082,6 +1100,20 @@ model Store {
|
||||
@@map("store_store")
|
||||
}
|
||||
|
||||
/// Store visibility whitelist phones (match by bound user phone)
|
||||
model StoreVisibilityPhone {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||
phone String @db.VarChar(20)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([storeId, phone])
|
||||
@@index([phone])
|
||||
@@map("store_visibility_phone")
|
||||
}
|
||||
|
||||
model StoreAccount {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
phone String @unique @db.VarChar(20)
|
||||
@@ -1104,6 +1136,7 @@ model StoreAccount {
|
||||
childAccounts StoreAccount[] @relation("StoreAccountHierarchy")
|
||||
bindings StoreAccountStore[]
|
||||
redeemPendingRecords RedeemPendingRecord[]
|
||||
withdrawRequests StoreWithdrawRequest[]
|
||||
|
||||
@@index([parentAccountId])
|
||||
@@map("store_account")
|
||||
@@ -1291,14 +1324,16 @@ model BenefitCoupon {
|
||||
}
|
||||
|
||||
model RedeemRecord {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
redeemNo String @unique @map("redeem_no") @db.VarChar(32)
|
||||
userId BigInt @map("user_id") @db.UnsignedBigInt
|
||||
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
|
||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
redeemNo String @unique @map("redeem_no") @db.VarChar(32)
|
||||
userId BigInt @map("user_id") @db.UnsignedBigInt
|
||||
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
|
||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
|
||||
/// SCAN=qrcode, PHONE=phone
|
||||
channel RedeemChannel @default(SCAN)
|
||||
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)
|
||||
@@ -1309,6 +1344,7 @@ model RedeemRecord {
|
||||
allocations RedeemRecordAllocation[]
|
||||
|
||||
@@index([storeId, createdAt])
|
||||
@@index([storeId, channel, createdAt])
|
||||
@@map("user_redeem_record")
|
||||
}
|
||||
|
||||
@@ -1415,12 +1451,52 @@ model StorePayout {
|
||||
redeemRecord RedeemRecord @relation(fields: [redeemRecordId], references: [id], onDelete: Restrict)
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
||||
storeBill StoreBill? @relation(fields: [storeBillId], references: [id], onDelete: SetNull)
|
||||
withdrawItem StoreWithdrawPayoutItem?
|
||||
|
||||
@@index([storeId, status])
|
||||
@@index([storeBillId])
|
||||
@@map("store_payout")
|
||||
}
|
||||
|
||||
model StoreWithdrawRequest {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
withdrawNo String @unique @map("withdraw_no") @db.VarChar(32)
|
||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||
storeAccountId BigInt @map("store_account_id") @db.UnsignedBigInt
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
payoutCount Int @default(0) @map("payout_count")
|
||||
status StoreWithdrawStatus @default(PENDING_REVIEW)
|
||||
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
||||
appliedAt DateTime @default(now()) @map("applied_at") @db.DateTime(3)
|
||||
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
||||
reviewedByHqId BigInt? @map("reviewed_by_hq_id") @db.UnsignedBigInt
|
||||
paidAt DateTime? @map("paid_at") @db.DateTime(3)
|
||||
paymentRef String? @map("payment_ref") @db.VarChar(128)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
||||
storeAccount StoreAccount @relation(fields: [storeAccountId], references: [id], onDelete: Restrict)
|
||||
items StoreWithdrawPayoutItem[]
|
||||
|
||||
@@index([storeId, status])
|
||||
@@index([status, appliedAt])
|
||||
@@map("store_withdraw_request")
|
||||
}
|
||||
|
||||
model StoreWithdrawPayoutItem {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
withdrawRequestId BigInt @map("withdraw_request_id") @db.UnsignedBigInt
|
||||
storePayoutId BigInt @unique @map("store_payout_id") @db.UnsignedBigInt
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
withdrawRequest StoreWithdrawRequest @relation(fields: [withdrawRequestId], references: [id], onDelete: Cascade)
|
||||
storePayout StorePayout @relation(fields: [storePayoutId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([withdrawRequestId])
|
||||
@@map("store_withdraw_payout_item")
|
||||
}
|
||||
|
||||
model WineryBill {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
billNo String @unique @map("bill_no") @db.VarChar(32)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.module';
|
||||
import type { AuthUser } from './jwt-auth.guard';
|
||||
|
||||
/** 门店主账号专用(提现等资金操作) */
|
||||
@Injectable()
|
||||
export class ShopPrimaryGuard implements CanActivate {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const user = req.user as AuthUser | undefined;
|
||||
if (!user || user.actorType !== 'STORE') {
|
||||
throw new ForbiddenException('仅门店主账号可操作');
|
||||
}
|
||||
const account = await this.prisma.storeAccount.findUnique({
|
||||
where: { id: user.actorId },
|
||||
select: { isPrimary: true },
|
||||
});
|
||||
if (!account || account.isPrimary !== 1) {
|
||||
throw new ForbiddenException('仅门店主账号可申请提现');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@ export const HqOperationAction = {
|
||||
STORE_PAYOUT_BATCH_CONFIRM: 'STORE_PAYOUT_BATCH_CONFIRM',
|
||||
STORE_BILL_CONFIRM: 'STORE_BILL_CONFIRM',
|
||||
STORE_BILL_BATCH_CONFIRM: 'STORE_BILL_BATCH_CONFIRM',
|
||||
STORE_WITHDRAW_APPROVE: 'STORE_WITHDRAW_APPROVE',
|
||||
STORE_WITHDRAW_REJECT: 'STORE_WITHDRAW_REJECT',
|
||||
PARTNER_BILL_GENERATE: 'PARTNER_BILL_GENERATE',
|
||||
PARTNER_BILL_SEND: 'PARTNER_BILL_SEND',
|
||||
PARTNER_BILL_BATCH_SEND: 'PARTNER_BILL_BATCH_SEND',
|
||||
@@ -164,6 +166,8 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
||||
[HqOperationAction.STORE_PAYOUT_BATCH_CONFIRM]: '批量门店打款',
|
||||
[HqOperationAction.STORE_BILL_CONFIRM]: '门店对账单确认打款',
|
||||
[HqOperationAction.STORE_BILL_BATCH_CONFIRM]: '批量门店对账单打款',
|
||||
[HqOperationAction.STORE_WITHDRAW_APPROVE]: '门店提现审核通过',
|
||||
[HqOperationAction.STORE_WITHDRAW_REJECT]: '门店提现驳回',
|
||||
[HqOperationAction.PARTNER_BILL_GENERATE]: '生成合伙人账单',
|
||||
[HqOperationAction.PARTNER_BILL_SEND]: '发送合伙人账单',
|
||||
[HqOperationAction.PARTNER_BILL_BATCH_SEND]: '批量发送合伙人账单',
|
||||
|
||||
@@ -10,6 +10,7 @@ export const SYSTEM_CONFIG_GROUPS: SystemConfigGroupMeta[] = [
|
||||
{ key: 'app', label: '应用链接' },
|
||||
{ key: 'deploy', label: '发布部署' },
|
||||
{ key: 'winery_bank', label: '酒厂银行账户' },
|
||||
{ key: 'finance', label: '财务结算' },
|
||||
];
|
||||
|
||||
const G = {
|
||||
@@ -21,6 +22,7 @@ const G = {
|
||||
app: 'app',
|
||||
deploy: 'deploy',
|
||||
winery_bank: 'winery_bank',
|
||||
finance: 'finance',
|
||||
} as const;
|
||||
|
||||
/** HQ 可维护字段(不含 NODE_ENV / DATABASE_URL / JWT 等基础设施项) */
|
||||
@@ -187,6 +189,15 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
||||
type: 'string',
|
||||
requiresRestart: false,
|
||||
},
|
||||
{
|
||||
key: 'STORE_WITHDRAW_DAILY_LIMIT',
|
||||
label: '门店未出账提现单日上限(元)',
|
||||
group: G.finance,
|
||||
type: 'number',
|
||||
requiresRestart: false,
|
||||
description: 'FIN-002:单店单日提现上限,默认 5000',
|
||||
placeholder: '5000',
|
||||
},
|
||||
];
|
||||
|
||||
/** 已从 HQ 配置移除、仅保留在 .env 的键(启动时从 DB 清理) */
|
||||
|
||||
@@ -66,7 +66,7 @@ export const WECOM_HANDBOOK_ENTRIES: HandbookEntry[] = [
|
||||
body: [
|
||||
'门店账单:核销×60%,T+1 出账;HQ 确认打款。',
|
||||
'合伙人月账独立确认打款。',
|
||||
'未出账提现受白名单/单日上限等 FIN 护栏。',
|
||||
'门店可对未出账核销主动提现(受单日上限);申请后锁定明细不进入次日出账,HQ 审后打款并企微提醒。',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -7,6 +7,7 @@ import { AlertService } from '../common/alert/alert.service';
|
||||
* 财务对账单定时任务(Asia/Shanghai)
|
||||
* - 每日 08:00:酒厂日账单 + 门店日账单(统计昨日 00:00~今日 00:00)
|
||||
* - 每月 1 日 08:00:合伙人上一自然月账单 + 物流承运商上一自然月对账
|
||||
* - 工作日 18:05:门店提现 T+0 审完预警(FIN-003)
|
||||
*/
|
||||
@Injectable()
|
||||
export class SettlementScheduler {
|
||||
@@ -48,6 +49,25 @@ export class SettlementScheduler {
|
||||
}
|
||||
}
|
||||
|
||||
/** FIN-003:工作日 18:05 扫描超时未审门店提现(企微提醒在 SettlementService 内发送) */
|
||||
@Cron('5 18 * * 1-5', { timeZone: 'Asia/Shanghai' })
|
||||
async handleWithdrawOverdueAlert() {
|
||||
this.logger.log('Store withdraw overdue scan start');
|
||||
try {
|
||||
const summary = await this.settlementService.scanOverdueStoreWithdrawals();
|
||||
this.logger.log(`Store withdraw overdue: ${JSON.stringify(summary)}`);
|
||||
} catch (e) {
|
||||
this.logger.error('Store withdraw overdue scan failed', e instanceof Error ? e.stack : e);
|
||||
this.alert.notify({
|
||||
level: 'P1',
|
||||
category: 'job',
|
||||
title: '门店提现超时扫描失败',
|
||||
detail: e instanceof Error ? e.message : String(e),
|
||||
dedupeKey: `job_store_withdraw_overdue_fail|${new Date().toISOString().slice(0, 10)}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Cron('0 8 1 * *', { timeZone: 'Asia/Shanghai' })
|
||||
async handleMonthlyPartnerBills() {
|
||||
this.logger.log('Monthly partner bills job start');
|
||||
|
||||
@@ -23,6 +23,7 @@ import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
||||
import { ShopStoreGuard } from '../../common/guards/shop-store.guard';
|
||||
import { ShopPrimaryGuard } from '../../common/guards/shop-primary.guard';
|
||||
import { StoreMembershipService } from '../../common/guards/store-membership.service';
|
||||
import {
|
||||
HqPermissionGuard,
|
||||
@@ -63,6 +64,7 @@ import { CommonModule } from '../common/common.module';
|
||||
PartnerPrimaryGuard,
|
||||
PartnerPermissionGuard,
|
||||
ShopStoreGuard,
|
||||
ShopPrimaryGuard,
|
||||
HqPermissionsResolver,
|
||||
HqPermissionGuard,
|
||||
],
|
||||
@@ -80,6 +82,7 @@ import { CommonModule } from '../common/common.module';
|
||||
PartnerPrimaryGuard,
|
||||
PartnerPermissionGuard,
|
||||
ShopStoreGuard,
|
||||
ShopPrimaryGuard,
|
||||
HqPermissionsResolver,
|
||||
HqPermissionGuard,
|
||||
],
|
||||
|
||||
@@ -40,6 +40,21 @@ function num(v: Prisma.Decimal | number | string | null | undefined): number {
|
||||
return typeof v === 'number' ? v : Number(v);
|
||||
}
|
||||
|
||||
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
||||
const day = appliedAt.getDay();
|
||||
if (day === 0 || day === 6) return false;
|
||||
const deadline = new Date(
|
||||
appliedAt.getFullYear(),
|
||||
appliedAt.getMonth(),
|
||||
appliedAt.getDate(),
|
||||
18,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
return now.getTime() > deadline.getTime();
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminDashboardService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -63,6 +78,7 @@ export class AdminDashboardService {
|
||||
pendingBills,
|
||||
pendingPartnerDraftBills,
|
||||
openTickets,
|
||||
pendingWithdrawRows,
|
||||
] = await Promise.all([
|
||||
this.prisma.user.count({ where: { status: 1, mergedIntoUserId: null } }),
|
||||
this.prisma.user.count({
|
||||
@@ -85,8 +101,18 @@ export class AdminDashboardService {
|
||||
this.prisma.partnerBill.count({ where: { status: 'UNPAID' } }),
|
||||
this.prisma.partnerBill.count({ where: { status: 'PENDING_REVIEW' } }),
|
||||
this.prisma.commonTicket.count({ where: { status: { in: ['PENDING', 'OPEN'] } } }),
|
||||
this.prisma.storeWithdrawRequest.findMany({
|
||||
where: { status: 'PENDING_REVIEW' },
|
||||
select: { appliedAt: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const now = new Date();
|
||||
const pendingStoreWithdrawals = pendingWithdrawRows.length;
|
||||
const overdueStoreWithdrawals = pendingWithdrawRows.filter((r) =>
|
||||
isWithdrawOverdue(r.appliedAt, now),
|
||||
).length;
|
||||
|
||||
return {
|
||||
usersTotal,
|
||||
guestUsers,
|
||||
@@ -101,6 +127,8 @@ export class AdminDashboardService {
|
||||
pendingBills,
|
||||
pendingPartnerDraftBills,
|
||||
openTickets,
|
||||
pendingStoreWithdrawals,
|
||||
overdueStoreWithdrawals,
|
||||
ordersByStatus: ordersByStatus.map((row) => ({
|
||||
status: row.status,
|
||||
count: row._count.status,
|
||||
|
||||
@@ -39,6 +39,9 @@ export class AdminRedeemService {
|
||||
if (query.redeemNo) where.redeemNo = { contains: query.redeemNo };
|
||||
if (query.storeId) where.storeId = BigInt(query.storeId);
|
||||
if (query.userId) where.userId = BigInt(query.userId);
|
||||
if (query.channel === 'SCAN' || query.channel === 'PHONE') {
|
||||
where.channel = query.channel;
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.redeemRecord.findMany({
|
||||
|
||||
@@ -25,6 +25,24 @@ function normalizeStoreOptionalText(value: unknown): string | null {
|
||||
return s;
|
||||
}
|
||||
|
||||
function normalizeVisibilityPhones(phones?: string[]): string[] {
|
||||
if (!phones?.length) return [];
|
||||
const out: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of phones) {
|
||||
const phone = String(raw || '')
|
||||
.replace(/\D/g, '')
|
||||
.trim();
|
||||
if (!phone || seen.has(phone)) continue;
|
||||
if (!/^1\d{10}$/.test(phone)) {
|
||||
throw new BadRequestException(`手机号格式无效:${raw}`);
|
||||
}
|
||||
seen.add(phone);
|
||||
out.push(phone);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminStoresService {
|
||||
constructor(
|
||||
@@ -64,19 +82,23 @@ export class AdminStoresService {
|
||||
},
|
||||
},
|
||||
coverResource: { select: { id: true, url: true } },
|
||||
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||
},
|
||||
}),
|
||||
this.prisma.store.count({ where }),
|
||||
]);
|
||||
return serializeBigInt({
|
||||
items: items.map((s) =>
|
||||
mapStoreCompat({
|
||||
...s,
|
||||
items: items.map((s) => {
|
||||
const { visibilityPhones, ...rest } = s;
|
||||
return mapStoreCompat({
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: s.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||
partner: s.partnerAccount,
|
||||
account: s.bindings[0]?.storeAccount ?? null,
|
||||
bindings: undefined,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
@@ -96,6 +118,7 @@ export class AdminStoresService {
|
||||
include: { storeAccount: true },
|
||||
},
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||
_count: { select: { redeemRecords: true, ratings: true } },
|
||||
},
|
||||
});
|
||||
@@ -111,8 +134,12 @@ export class AdminStoresService {
|
||||
take: 5,
|
||||
}),
|
||||
]);
|
||||
const { visibilityPhones, ...rest } = store;
|
||||
return serializeBigInt(mapStoreCompat({
|
||||
...store,
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: store.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||
partner: store.partnerAccount,
|
||||
account: store.bindings[0]?.storeAccount ?? null,
|
||||
/** 门店端登录手机号(store_account.phone),与 store.phone 应对齐 */
|
||||
loginPhone: store.bindings[0]?.storeAccount?.phone ?? store.phone,
|
||||
@@ -235,6 +262,26 @@ export class AdminStoresService {
|
||||
}
|
||||
|
||||
const normalizedPhone = dto.phone !== undefined ? dto.phone.trim() : undefined;
|
||||
if (dto.visibilityWhitelistEnabled !== undefined || dto.visibilityPhones !== undefined) {
|
||||
const nextEnabled =
|
||||
dto.visibilityWhitelistEnabled !== undefined
|
||||
? !!dto.visibilityWhitelistEnabled
|
||||
: current.visibilityWhitelistEnabled;
|
||||
if (nextEnabled) {
|
||||
const phones =
|
||||
dto.visibilityPhones !== undefined
|
||||
? normalizeVisibilityPhones(dto.visibilityPhones)
|
||||
: (
|
||||
await this.prisma.storeVisibilityPhone.findMany({
|
||||
where: { storeId: id },
|
||||
select: { phone: true },
|
||||
})
|
||||
).map((p) => p.phone);
|
||||
if (!phones.length) {
|
||||
throw new BadRequestException('开启白名单时请至少添加一个手机号');
|
||||
}
|
||||
}
|
||||
}
|
||||
const bankTouched =
|
||||
dto.bankAccountName !== undefined ||
|
||||
dto.bankAccountNo !== undefined ||
|
||||
@@ -307,10 +354,23 @@ export class AdminStoresService {
|
||||
...(dto.openTime2 !== undefined ? { openTime2: dto.openTime2 || null } : {}),
|
||||
...(dto.closeTime2 !== undefined ? { closeTime2: dto.closeTime2 || null } : {}),
|
||||
...(dto.avgPrice !== undefined ? { avgPrice: dto.avgPrice } : {}),
|
||||
...(dto.visibilityWhitelistEnabled !== undefined
|
||||
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||
: {}),
|
||||
...(latitude != null && longitude != null ? { latitude, longitude } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (dto.visibilityPhones !== undefined) {
|
||||
const phones = normalizeVisibilityPhones(dto.visibilityPhones);
|
||||
await tx.storeVisibilityPhone.deleteMany({ where: { storeId: id } });
|
||||
if (phones.length) {
|
||||
await tx.storeVisibilityPhone.createMany({
|
||||
data: phones.map((phone) => ({ storeId: id, phone })),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.coverUrl) {
|
||||
if (current.coverResourceId) {
|
||||
await tx.commonResource.update({
|
||||
@@ -430,6 +490,12 @@ export class AdminStoresService {
|
||||
throw new BadRequestException('好客权益券使用规则最多 1000 字');
|
||||
}
|
||||
|
||||
const visibilityPhones = normalizeVisibilityPhones(dto.visibilityPhones);
|
||||
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
||||
if (whitelistEnabled && !visibilityPhones.length) {
|
||||
throw new BadRequestException('开启白名单时请至少添加一个手机号');
|
||||
}
|
||||
|
||||
const store = await this.prisma.store.create({
|
||||
data: {
|
||||
cityId: city.id,
|
||||
@@ -449,11 +515,19 @@ export class AdminStoresService {
|
||||
closeTime,
|
||||
openTime2: openTime2 || null,
|
||||
closeTime2: closeTime2 || null,
|
||||
visibilityWhitelistEnabled: whitelistEnabled,
|
||||
...(latitude != null && longitude != null ? { latitude, longitude } : {}),
|
||||
status: 'OPEN',
|
||||
auditStatus: 'APPROVED',
|
||||
auditedAt: new Date(),
|
||||
rejectReason: null,
|
||||
...(visibilityPhones.length
|
||||
? {
|
||||
visibilityPhones: {
|
||||
create: visibilityPhones.map((phone) => ({ phone })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -127,6 +127,17 @@ export class CreateStoreDto {
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
avgPrice?: number;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
|
||||
/** 可见白名单手机号列表 */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
visibilityPhones?: string[];
|
||||
}
|
||||
|
||||
export class UpdateStoreDto {
|
||||
@@ -215,6 +226,17 @@ export class UpdateStoreDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
bankBranch?: string | null;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
|
||||
/** 可见白名单手机号列表 */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
visibilityPhones?: string[];
|
||||
}
|
||||
|
||||
export class CreateStoreAccountDto {
|
||||
|
||||
@@ -242,6 +242,11 @@ export class AdminRedeemRecordsQueryDto extends PaginationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
userId?: string;
|
||||
|
||||
/** SCAN | PHONE */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
channel?: string;
|
||||
}
|
||||
|
||||
export class AdminStoreRatingsQueryDto extends PaginationQueryDto {
|
||||
|
||||
@@ -96,6 +96,16 @@ export class ShopRedeemController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get('stats')
|
||||
stats(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Query('range') range?: string,
|
||||
) {
|
||||
const normalized =
|
||||
range === '7d' || range === '30d' || range === 'today' ? range : 'today';
|
||||
return this.redeemService.getShopRedeemStats(user.actorId, user.storeId!, normalized);
|
||||
}
|
||||
|
||||
@Post('phone/send-lookup-sms')
|
||||
sendPhoneLookupSms(@CurrentUser() user: AuthUser, @Body() body: RedeemPhoneSendLookupSmsDto) {
|
||||
return this.redeemService.sendPhoneLookupSms(user.actorId, user.storeId!, body.phone);
|
||||
|
||||
@@ -38,6 +38,15 @@ type TokenPayload = {
|
||||
allocations?: Array<{ couponId: string; amount: number }>;
|
||||
};
|
||||
|
||||
/** C 端公示:用户138****5678 / 用户*** */
|
||||
function maskRedeemUserLabel(phone?: string | null): string {
|
||||
const digits = String(phone || '').replace(/\D/g, '');
|
||||
if (digits.length >= 7) {
|
||||
return `用户${digits.slice(0, 3)}****${digits.slice(-4)}`;
|
||||
}
|
||||
return '用户***';
|
||||
}
|
||||
|
||||
type PendingSnapshot = TokenPayload & {
|
||||
redeemType: 'DIRECT' | 'COUPON';
|
||||
};
|
||||
@@ -169,6 +178,7 @@ export class RedeemService {
|
||||
) {
|
||||
const settlementRate = Number(account.store.settlementRate);
|
||||
const settleAmount = calcRedeemSettleAmount(amount, settlementRate);
|
||||
const redeemChannel = analyticsExtra?.channel === 'phone' ? 'PHONE' : 'SCAN';
|
||||
|
||||
let record;
|
||||
try {
|
||||
@@ -183,6 +193,7 @@ export class RedeemService {
|
||||
storeId: account.storeId,
|
||||
amount,
|
||||
settleAmount,
|
||||
channel: redeemChannel,
|
||||
allocations: {
|
||||
create: normalizedAllocations.map((item, index) => ({
|
||||
couponId: BigInt(item.couponId),
|
||||
@@ -1070,6 +1081,51 @@ export class RedeemService {
|
||||
return { list: serializeBigInt(list), total, page, pageSize };
|
||||
}
|
||||
|
||||
async getShopRedeemStats(
|
||||
storeAccountId: bigint,
|
||||
storeId: bigint,
|
||||
range: 'today' | '7d' | '30d' = 'today',
|
||||
) {
|
||||
await this.prisma.storeAccountStore.findUniqueOrThrow({
|
||||
where: { storeAccountId_storeId: { storeAccountId, storeId } },
|
||||
});
|
||||
const start = new Date();
|
||||
start.setHours(0, 0, 0, 0);
|
||||
if (range === '7d') start.setDate(start.getDate() - 6);
|
||||
if (range === '30d') start.setDate(start.getDate() - 29);
|
||||
|
||||
const records = await this.prisma.redeemRecord.findMany({
|
||||
where: { storeId, createdAt: { gte: start } },
|
||||
select: { channel: true, amount: true, settleAmount: true },
|
||||
});
|
||||
|
||||
const buckets: Record<'SCAN' | 'PHONE', { count: number; amount: number; settleAmount: number }> = {
|
||||
SCAN: { count: 0, amount: 0, settleAmount: 0 },
|
||||
PHONE: { count: 0, amount: 0, settleAmount: 0 },
|
||||
};
|
||||
for (const r of records) {
|
||||
const key = r.channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||
buckets[key].count += 1;
|
||||
buckets[key].amount += Number(r.amount);
|
||||
buckets[key].settleAmount += Number(r.settleAmount);
|
||||
}
|
||||
|
||||
const byChannel = (['SCAN', 'PHONE'] as const).map((channel) => ({
|
||||
channel,
|
||||
count: buckets[channel].count,
|
||||
amount: Number(buckets[channel].amount.toFixed(2)),
|
||||
settleAmount: Number(buckets[channel].settleAmount.toFixed(2)),
|
||||
}));
|
||||
|
||||
return {
|
||||
range,
|
||||
totalCount: records.length,
|
||||
totalAmount: Number(byChannel.reduce((s, b) => s + b.amount, 0).toFixed(2)),
|
||||
totalSettleAmount: Number(byChannel.reduce((s, b) => s + b.settleAmount, 0).toFixed(2)),
|
||||
byChannel,
|
||||
};
|
||||
}
|
||||
|
||||
async getShopDashboard(storeAccountId: bigint, storeId: bigint) {
|
||||
const binding = await this.prisma.storeAccountStore.findUniqueOrThrow({
|
||||
where: { storeAccountId_storeId: { storeAccountId, storeId } },
|
||||
@@ -1082,6 +1138,8 @@ export class RedeemService {
|
||||
});
|
||||
const todayCount = records.length;
|
||||
const todayAmount = records.reduce((sum, r) => sum + Number(r.amount), 0);
|
||||
const todayScanCount = records.filter((r) => r.channel !== 'PHONE').length;
|
||||
const todayPhoneCount = records.filter((r) => r.channel === 'PHONE').length;
|
||||
const recent = await this.prisma.redeemRecord.findMany({
|
||||
where: { storeId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
@@ -1091,6 +1149,8 @@ export class RedeemService {
|
||||
store: binding.store,
|
||||
todayCount,
|
||||
todayAmount,
|
||||
todayScanCount,
|
||||
todayPhoneCount,
|
||||
recentRecords: recent,
|
||||
});
|
||||
}
|
||||
@@ -1131,6 +1191,51 @@ export class RedeemService {
|
||||
};
|
||||
}
|
||||
|
||||
/** C 端门店详情走马灯:脱敏用户 + 时间 + 金额 */
|
||||
async listPublicStoreRecentRedeems(storeId: bigint, limit = 20) {
|
||||
const take = Math.min(Math.max(limit, 1), 50);
|
||||
const list = await this.prisma.redeemRecord.findMany({
|
||||
where: { storeId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: { user: { select: { phone: true } } },
|
||||
});
|
||||
|
||||
const fmtAmount = (n: number) => {
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
if (Math.abs(n - Math.round(n)) < 1e-9) return String(Math.round(n));
|
||||
return n.toFixed(2).replace(/\.?0+$/, '');
|
||||
};
|
||||
const fmtTime = (d: Date) => {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).formatToParts(d);
|
||||
const get = (type: Intl.DateTimeFormatPartTypes) =>
|
||||
parts.find((p) => p.type === type)?.value ?? '';
|
||||
return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}:${get('second')}`;
|
||||
};
|
||||
|
||||
return list.map((r) => {
|
||||
const userLabel = maskRedeemUserLabel(r.user?.phone);
|
||||
const amount = Number(r.amount);
|
||||
const createdAt = fmtTime(r.createdAt);
|
||||
return {
|
||||
userLabel,
|
||||
amount,
|
||||
createdAt,
|
||||
/** 前端可直接展示 */
|
||||
text: `${userLabel} ${createdAt} 核销${fmtAmount(amount)}元`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async submitRating(userId: bigint, body: { redeemRecordId: string; serviceScore: number; envScore: number }) {
|
||||
const record = await this.prisma.redeemRecord.findFirst({
|
||||
where: { id: BigInt(body.redeemRecordId), userId },
|
||||
|
||||
@@ -5,6 +5,7 @@ import { SettlementService } from './settlement.service';
|
||||
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||
import { ShopStoreGuard } from '../../common/guards/shop-store.guard';
|
||||
import { ShopPrimaryGuard } from '../../common/guards/shop-primary.guard';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
@@ -59,6 +60,98 @@ export class ShopPayoutController {
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('shop/withdraw')
|
||||
@UseGuards(JwtAuthGuard, ShopStoreGuard)
|
||||
export class ShopWithdrawController {
|
||||
constructor(private readonly settlementService: SettlementService) {}
|
||||
|
||||
@Get('summary')
|
||||
summary(@CurrentUser() user: AuthUser) {
|
||||
return this.settlementService.getShopWithdrawSummary(user.actorId, user.storeId!);
|
||||
}
|
||||
|
||||
@Get('requests')
|
||||
requests(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Query('page') page = '1',
|
||||
@Query('pageSize') pageSize = '20',
|
||||
@Query('status') status?: string,
|
||||
) {
|
||||
return this.settlementService.listShopWithdrawRequests(user.actorId, user.storeId!, {
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize),
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
@Post()
|
||||
@UseGuards(ShopPrimaryGuard)
|
||||
apply(@CurrentUser() user: AuthUser, @Body() body: { amount?: number }) {
|
||||
return this.settlementService.createStoreWithdrawRequest(user.actorId, user.storeId!, body);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('admin/store-withdrawals')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminStoreWithdrawController {
|
||||
constructor(private readonly settlementService: SettlementService) {}
|
||||
|
||||
@Get('overdue-summary')
|
||||
overdueSummary() {
|
||||
return this.settlementService.getStoreWithdrawOverdueSummary();
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(@Query() query: Record<string, string>) {
|
||||
return this.settlementService.listAdminStoreWithdrawals({
|
||||
page: query.page ? Number(query.page) : 1,
|
||||
pageSize: query.pageSize ? Number(query.pageSize) : 20,
|
||||
status: query.status,
|
||||
storeId: query.storeId,
|
||||
dateFrom: query.dateFrom,
|
||||
dateTo: query.dateTo,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@Param('id') id: string) {
|
||||
return this.settlementService.getAdminStoreWithdrawal(BigInt(id));
|
||||
}
|
||||
|
||||
@Post(':id/approve')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.STORE_WITHDRAW_APPROVE,
|
||||
refType: 'STORE_WITHDRAW',
|
||||
refIdParam: 'id',
|
||||
includeBody: true,
|
||||
})
|
||||
approve(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { paymentRef?: string },
|
||||
) {
|
||||
return this.settlementService.approveStoreWithdraw(BigInt(id), user.actorId, body);
|
||||
}
|
||||
|
||||
@Post(':id/reject')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.STORE_WITHDRAW_REJECT,
|
||||
refType: 'STORE_WITHDRAW',
|
||||
refIdParam: 'id',
|
||||
includeBody: true,
|
||||
})
|
||||
reject(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Body() body: { reason?: string },
|
||||
) {
|
||||
if (!body?.reason?.trim()) {
|
||||
throw new BadRequestException('请填写驳回理由');
|
||||
}
|
||||
return this.settlementService.rejectStoreWithdraw(BigInt(id), user.actorId, body.reason);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('admin/store-payouts')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminStorePayoutController {
|
||||
@@ -131,6 +224,25 @@ export class AdminStorePayoutController {
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('admin/store-settlements')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminStoreSettlementController {
|
||||
constructor(private readonly settlementService: SettlementService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query() query: Record<string, string>) {
|
||||
return this.settlementService.listAdminStoreSettlements({
|
||||
page: query.page ? Number(query.page) : 1,
|
||||
pageSize: query.pageSize ? Number(query.pageSize) : 20,
|
||||
kind: query.kind,
|
||||
status: query.status,
|
||||
storeId: query.storeId,
|
||||
dateFrom: query.dateFrom,
|
||||
dateTo: query.dateTo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('admin/store-bills')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminStoreBillController {
|
||||
|
||||
@@ -9,10 +9,13 @@ import {
|
||||
AdminPartnerBillController,
|
||||
AdminStoreBillController,
|
||||
AdminStorePayoutController,
|
||||
AdminStoreSettlementController,
|
||||
AdminStoreWithdrawController,
|
||||
AdminWineryBillController,
|
||||
PartnerMeController,
|
||||
SettlementController,
|
||||
ShopPayoutController,
|
||||
ShopWithdrawController,
|
||||
} from './settlement.controller';
|
||||
|
||||
@Module({
|
||||
@@ -21,7 +24,10 @@ import {
|
||||
SettlementController,
|
||||
PartnerMeController,
|
||||
ShopPayoutController,
|
||||
ShopWithdrawController,
|
||||
AdminStoreWithdrawController,
|
||||
AdminStorePayoutController,
|
||||
AdminStoreSettlementController,
|
||||
AdminStoreBillController,
|
||||
AdminPartnerBillController,
|
||||
AdminWineryBillController,
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { DEFAULT_XFX_LOGISTICS_PRICING, WINERY_SETTLEMENT_RATE } from '@dukang/shared-types';
|
||||
import { calcLogisticsFeeByBottles, type LogisticsPricingRule } from '@dukang/domain';
|
||||
import {
|
||||
DEFAULT_STORE_WITHDRAW_DAILY_LIMIT,
|
||||
DEFAULT_XFX_LOGISTICS_PRICING,
|
||||
WINERY_SETTLEMENT_RATE,
|
||||
} from '@dukang/shared-types';
|
||||
import {
|
||||
calcLogisticsFeeByBottles,
|
||||
pickPayoutsForWithdrawAmount,
|
||||
sumUnbilledPayoutAmount,
|
||||
validateStoreWithdraw,
|
||||
type LogisticsPricingRule,
|
||||
} from '@dukang/domain';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
import { AlertService } from '../../common/alert/alert.service';
|
||||
import { AnalyticsService } from '../analytics/analytics.service';
|
||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
||||
@@ -33,6 +44,28 @@ function round2(n: number) {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
function getStoreWithdrawDailyLimit(): number {
|
||||
const raw = process.env.STORE_WITHDRAW_DAILY_LIMIT;
|
||||
const n = raw != null && raw !== '' ? Number(raw) : DEFAULT_STORE_WITHDRAW_DAILY_LIMIT;
|
||||
return Number.isFinite(n) && n > 0 ? n : DEFAULT_STORE_WITHDRAW_DAILY_LIMIT;
|
||||
}
|
||||
|
||||
/** 工作日 18:00 前未审完视为 FIN-003 超时(Asia/Shanghai 自然日) */
|
||||
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
||||
const day = appliedAt.getDay(); // 0 Sun … 6 Sat
|
||||
if (day === 0 || day === 6) return false;
|
||||
const deadline = new Date(
|
||||
appliedAt.getFullYear(),
|
||||
appliedAt.getMonth(),
|
||||
appliedAt.getDate(),
|
||||
18,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
return now.getTime() > deadline.getTime();
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SettlementService {
|
||||
constructor(
|
||||
@@ -40,6 +73,7 @@ export class SettlementService {
|
||||
private readonly analyticsService: AnalyticsService,
|
||||
private readonly partnerCityService: PartnerCityService,
|
||||
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
||||
private readonly alert: AlertService,
|
||||
) {}
|
||||
|
||||
// ─── Store payout (line) ─────────────────────────────
|
||||
@@ -99,6 +133,476 @@ export class SettlementService {
|
||||
return serializeBigInt({ items, total, page, pageSize });
|
||||
}
|
||||
|
||||
// ─── Store withdraw (未出账手动提现) ─────────────────
|
||||
|
||||
private async assertShopStoreAccess(storeAccountId: bigint, storeId: bigint) {
|
||||
await this.prisma.storeAccountStore.findUniqueOrThrow({
|
||||
where: { storeAccountId_storeId: { storeAccountId, storeId } },
|
||||
});
|
||||
}
|
||||
|
||||
private async listAvailableUnbilledPayouts(storeId: bigint) {
|
||||
return this.prisma.storePayout.findMany({
|
||||
where: {
|
||||
storeId,
|
||||
status: 'PENDING',
|
||||
storeBillId: null,
|
||||
withdrawItem: null,
|
||||
},
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
}
|
||||
|
||||
private async todayWithdrawAppliedAmount(storeId: bigint, now = new Date()) {
|
||||
const start = startOfDay(now);
|
||||
const end = new Date(start);
|
||||
end.setDate(end.getDate() + 1);
|
||||
const agg = await this.prisma.storeWithdrawRequest.aggregate({
|
||||
where: {
|
||||
storeId,
|
||||
status: { in: ['PENDING_REVIEW', 'PAID'] },
|
||||
appliedAt: { gte: start, lt: end },
|
||||
},
|
||||
_sum: { amount: true },
|
||||
});
|
||||
return Number(agg._sum.amount ?? 0);
|
||||
}
|
||||
|
||||
async getShopWithdrawSummary(storeAccountId: bigint, storeId: bigint) {
|
||||
await this.assertShopStoreAccess(storeAccountId, storeId);
|
||||
const [account, available, pending, todayApplied] = await Promise.all([
|
||||
this.prisma.storeAccount.findUniqueOrThrow({
|
||||
where: { id: storeAccountId },
|
||||
select: {
|
||||
isPrimary: true,
|
||||
bankAccountName: true,
|
||||
bankAccountNo: true,
|
||||
bankBranch: true,
|
||||
},
|
||||
}),
|
||||
this.listAvailableUnbilledPayouts(storeId),
|
||||
this.prisma.storeWithdrawRequest.findFirst({
|
||||
where: { storeId, status: 'PENDING_REVIEW' },
|
||||
select: { id: true, amount: true },
|
||||
}),
|
||||
this.todayWithdrawAppliedAmount(storeId),
|
||||
]);
|
||||
|
||||
const availableAmount = sumUnbilledPayoutAmount(
|
||||
available.map((p) => ({ payoutAmount: Number(p.payoutAmount) })),
|
||||
);
|
||||
const dailyLimit = getStoreWithdrawDailyLimit();
|
||||
const hasBankAccount = !!(
|
||||
account.bankAccountName?.trim() &&
|
||||
account.bankAccountNo?.trim()
|
||||
);
|
||||
|
||||
return {
|
||||
availableAmount,
|
||||
pendingReviewAmount: pending ? Number(pending.amount) : 0,
|
||||
todayAppliedAmount: todayApplied,
|
||||
dailyLimit,
|
||||
remainingDailyLimit: Math.max(0, round2(dailyLimit - todayApplied)),
|
||||
isPrimary: account.isPrimary === 1,
|
||||
hasBankAccount,
|
||||
hasPendingRequest: !!pending,
|
||||
bankAccount: {
|
||||
bankAccountName: account.bankAccountName,
|
||||
bankAccountNo: account.bankAccountNo,
|
||||
bankBranch: account.bankBranch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async createStoreWithdrawRequest(
|
||||
storeAccountId: bigint,
|
||||
storeId: bigint,
|
||||
dto?: { amount?: number },
|
||||
) {
|
||||
await this.assertShopStoreAccess(storeAccountId, storeId);
|
||||
|
||||
const [store, account, available, pending, todayApplied] = await Promise.all([
|
||||
this.prisma.store.findUniqueOrThrow({
|
||||
where: { id: storeId },
|
||||
select: { id: true, name: true, phone: true, cityName: true },
|
||||
}),
|
||||
this.prisma.storeAccount.findUniqueOrThrow({
|
||||
where: { id: storeAccountId },
|
||||
select: {
|
||||
isPrimary: true,
|
||||
bankAccountName: true,
|
||||
bankAccountNo: true,
|
||||
},
|
||||
}),
|
||||
this.listAvailableUnbilledPayouts(storeId),
|
||||
this.prisma.storeWithdrawRequest.findFirst({
|
||||
where: { storeId, status: 'PENDING_REVIEW' },
|
||||
select: { id: true },
|
||||
}),
|
||||
this.todayWithdrawAppliedAmount(storeId),
|
||||
]);
|
||||
|
||||
if (account.isPrimary !== 1) {
|
||||
throw new BadRequestException('仅门店主账号可申请提现');
|
||||
}
|
||||
|
||||
const availableAmount = sumUnbilledPayoutAmount(
|
||||
available.map((p) => ({ payoutAmount: Number(p.payoutAmount) })),
|
||||
);
|
||||
const dailyLimit = getStoreWithdrawDailyLimit();
|
||||
const hasBankAccount = !!(
|
||||
account.bankAccountName?.trim() &&
|
||||
account.bankAccountNo?.trim()
|
||||
);
|
||||
const requestAmount =
|
||||
dto?.amount != null && Number.isFinite(Number(dto.amount))
|
||||
? round2(Number(dto.amount))
|
||||
: availableAmount;
|
||||
|
||||
const guard = validateStoreWithdraw({
|
||||
availableAmount,
|
||||
requestAmount,
|
||||
todayApplied,
|
||||
dailyLimit,
|
||||
hasPendingRequest: !!pending,
|
||||
hasBankAccount,
|
||||
});
|
||||
if (!guard.ok) throw new BadRequestException(guard.message);
|
||||
|
||||
const picked = pickPayoutsForWithdrawAmount(
|
||||
available.map((p) => ({ id: p.id, payoutAmount: Number(p.payoutAmount) })),
|
||||
requestAmount,
|
||||
);
|
||||
if (!picked.ok) throw new BadRequestException(picked.message);
|
||||
|
||||
const created = await this.prisma.$transaction(async (tx) => {
|
||||
const stillPending = await tx.storeWithdrawRequest.findFirst({
|
||||
where: { storeId, status: 'PENDING_REVIEW' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (stillPending) {
|
||||
throw new BadRequestException('已有待审核提现申请,请等待处理完成');
|
||||
}
|
||||
|
||||
const payoutIds = picked.selected.map((p) => p.id);
|
||||
const locked = await tx.storePayout.findMany({
|
||||
where: {
|
||||
id: { in: payoutIds },
|
||||
storeId,
|
||||
status: 'PENDING',
|
||||
storeBillId: null,
|
||||
withdrawItem: null,
|
||||
},
|
||||
select: { id: true, payoutAmount: true },
|
||||
});
|
||||
if (locked.length !== payoutIds.length) {
|
||||
throw new BadRequestException('可提余额已变化,请刷新后重试');
|
||||
}
|
||||
const amount = round2(locked.reduce((s, p) => s + Number(p.payoutAmount), 0));
|
||||
|
||||
const req = await tx.storeWithdrawRequest.create({
|
||||
data: {
|
||||
withdrawNo: generateBillNo('SW'),
|
||||
storeId,
|
||||
storeAccountId,
|
||||
amount,
|
||||
payoutCount: locked.length,
|
||||
status: 'PENDING_REVIEW',
|
||||
},
|
||||
});
|
||||
await tx.storeWithdrawPayoutItem.createMany({
|
||||
data: locked.map((p) => ({
|
||||
withdrawRequestId: req.id,
|
||||
storePayoutId: p.id,
|
||||
})),
|
||||
});
|
||||
return req;
|
||||
});
|
||||
|
||||
this.analyticsService.trackStoreOneSafe(storeAccountId, 'SHOP_H5', {
|
||||
storeId,
|
||||
eventName: 'store_withdraw_applied',
|
||||
refType: 'STORE_WITHDRAW',
|
||||
refId: created.id,
|
||||
extraJson: {
|
||||
amount: Number(created.amount),
|
||||
payoutCount: created.payoutCount,
|
||||
},
|
||||
});
|
||||
|
||||
this.alert.notify({
|
||||
level: 'P1',
|
||||
category: 'finance',
|
||||
title: '门店提现待审',
|
||||
detail: [
|
||||
`门店:${store.name}(${store.cityName || '-'} / ${store.phone || '-'})`,
|
||||
`单号:${created.withdrawNo}`,
|
||||
`金额:¥${Number(created.amount).toFixed(2)}`,
|
||||
`明细:${created.payoutCount} 笔未出账核销(已锁定,不进入次日 T+1 出账)`,
|
||||
'请尽快在 HQ「财务 → 门店账单(手动提现)」处理。',
|
||||
].join('\n'),
|
||||
dedupeKey: `store_withdraw_applied|${created.id.toString()}`,
|
||||
dedupeTtlSec: 3600,
|
||||
});
|
||||
|
||||
return serializeBigInt(created);
|
||||
}
|
||||
|
||||
async listShopWithdrawRequests(
|
||||
storeAccountId: bigint,
|
||||
storeId: bigint,
|
||||
query: { page?: number; pageSize?: number; status?: string },
|
||||
) {
|
||||
await this.assertShopStoreAccess(storeAccountId, storeId);
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 20;
|
||||
const where: Prisma.StoreWithdrawRequestWhereInput = { storeId };
|
||||
if (query.status) {
|
||||
where.status = query.status as 'PENDING_REVIEW' | 'REJECTED' | 'PAID';
|
||||
}
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.storeWithdrawRequest.findMany({
|
||||
where,
|
||||
orderBy: { appliedAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.storeWithdrawRequest.count({ where }),
|
||||
]);
|
||||
return serializeBigInt({ items, total, page, pageSize });
|
||||
}
|
||||
|
||||
async listAdminStoreWithdrawals(query: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
status?: string;
|
||||
storeId?: string;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}) {
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 20;
|
||||
const where: Prisma.StoreWithdrawRequestWhereInput = {};
|
||||
if (query.status) {
|
||||
where.status = query.status as 'PENDING_REVIEW' | 'REJECTED' | 'PAID';
|
||||
}
|
||||
if (query.storeId) where.storeId = BigInt(query.storeId);
|
||||
if (query.dateFrom || query.dateTo) {
|
||||
where.appliedAt = {};
|
||||
if (query.dateFrom) where.appliedAt.gte = new Date(query.dateFrom);
|
||||
if (query.dateTo) {
|
||||
const end = new Date(query.dateTo);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
where.appliedAt.lte = end;
|
||||
}
|
||||
}
|
||||
|
||||
const [items, total, aggregates] = await Promise.all([
|
||||
this.prisma.storeWithdrawRequest.findMany({
|
||||
where,
|
||||
orderBy: [{ appliedAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
include: {
|
||||
store: { select: { id: true, name: true, cityName: true, phone: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.storeWithdrawRequest.count({ where }),
|
||||
this.prisma.storeWithdrawRequest.aggregate({
|
||||
where,
|
||||
_sum: { amount: true },
|
||||
_count: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
const now = new Date();
|
||||
const mapped = items.map((row) => ({
|
||||
...row,
|
||||
overdue:
|
||||
row.status === 'PENDING_REVIEW' ? isWithdrawOverdue(row.appliedAt, now) : false,
|
||||
}));
|
||||
|
||||
return serializeBigInt({
|
||||
items: mapped,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
summary: {
|
||||
count: aggregates._count,
|
||||
totalAmount: Number(aggregates._sum.amount ?? 0),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getAdminStoreWithdrawal(id: bigint) {
|
||||
const row = await this.prisma.storeWithdrawRequest.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
store: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
cityName: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
storeAccount: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
phone: true,
|
||||
bankAccountName: true,
|
||||
bankAccountNo: true,
|
||||
bankBranch: true,
|
||||
},
|
||||
},
|
||||
items: {
|
||||
include: {
|
||||
storePayout: {
|
||||
include: {
|
||||
redeemRecord: { select: { redeemNo: true, amount: true, createdAt: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!row) throw new NotFoundException('提现申请不存在');
|
||||
return serializeBigInt({
|
||||
...row,
|
||||
overdue:
|
||||
row.status === 'PENDING_REVIEW' ? isWithdrawOverdue(row.appliedAt) : false,
|
||||
});
|
||||
}
|
||||
|
||||
async approveStoreWithdraw(
|
||||
id: bigint,
|
||||
hqAccountId: bigint,
|
||||
dto?: { paymentRef?: string },
|
||||
) {
|
||||
const row = await this.prisma.storeWithdrawRequest.findUnique({
|
||||
where: { id },
|
||||
include: { items: { select: { storePayoutId: true } } },
|
||||
});
|
||||
if (!row) throw new NotFoundException('提现申请不存在');
|
||||
if (row.status !== 'PENDING_REVIEW') {
|
||||
throw new BadRequestException('仅待审核提现可审核通过');
|
||||
}
|
||||
|
||||
const paidAt = new Date();
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const req = await tx.storeWithdrawRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
reviewedAt: paidAt,
|
||||
reviewedByHqId: hqAccountId,
|
||||
paidAt,
|
||||
paymentRef: dto?.paymentRef?.trim() || null,
|
||||
},
|
||||
});
|
||||
await tx.storePayout.updateMany({
|
||||
where: {
|
||||
id: { in: row.items.map((i) => i.storePayoutId) },
|
||||
status: 'PENDING',
|
||||
},
|
||||
data: { status: 'PAID', paidAt },
|
||||
});
|
||||
return req;
|
||||
});
|
||||
|
||||
this.analyticsService.trackStoreOneSafe(undefined, 'HQ_WEB', {
|
||||
storeId: row.storeId,
|
||||
eventName: 'store_withdraw_paid',
|
||||
refType: 'STORE_WITHDRAW',
|
||||
refId: id,
|
||||
extraJson: {
|
||||
amount: Number(row.amount),
|
||||
paymentRef: dto?.paymentRef,
|
||||
},
|
||||
});
|
||||
|
||||
return serializeBigInt(updated);
|
||||
}
|
||||
|
||||
async rejectStoreWithdraw(id: bigint, hqAccountId: bigint, reason: string) {
|
||||
const row = await this.prisma.storeWithdrawRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!row) throw new NotFoundException('提现申请不存在');
|
||||
if (row.status !== 'PENDING_REVIEW') {
|
||||
throw new BadRequestException('仅待审核提现可驳回');
|
||||
}
|
||||
const rejectReason = reason.trim();
|
||||
if (!rejectReason) throw new BadRequestException('请填写驳回理由');
|
||||
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const req = await tx.storeWithdrawRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'REJECTED',
|
||||
rejectReason,
|
||||
reviewedAt: new Date(),
|
||||
reviewedByHqId: hqAccountId,
|
||||
},
|
||||
});
|
||||
// 释放 payout 锁定,允许再次提现
|
||||
await tx.storeWithdrawPayoutItem.deleteMany({ where: { withdrawRequestId: id } });
|
||||
return req;
|
||||
});
|
||||
|
||||
return serializeBigInt(updated);
|
||||
}
|
||||
|
||||
async getStoreWithdrawOverdueSummary() {
|
||||
const pending = await this.prisma.storeWithdrawRequest.findMany({
|
||||
where: { status: 'PENDING_REVIEW' },
|
||||
select: { id: true, appliedAt: true, amount: true },
|
||||
});
|
||||
const now = new Date();
|
||||
const overdue = pending.filter((r) => isWithdrawOverdue(r.appliedAt, now));
|
||||
return {
|
||||
pendingCount: pending.length,
|
||||
overdueCount: overdue.length,
|
||||
overdueAmount: round2(overdue.reduce((s, r) => s + Number(r.amount), 0)),
|
||||
pendingAmount: round2(pending.reduce((s, r) => s + Number(r.amount), 0)),
|
||||
};
|
||||
}
|
||||
|
||||
/** FIN-003:工作日 18:00 扫描超时未审提现 */
|
||||
async scanOverdueStoreWithdrawals() {
|
||||
const summary = await this.getStoreWithdrawOverdueSummary();
|
||||
if (summary.overdueCount > 0) {
|
||||
const overdueRows = await this.prisma.storeWithdrawRequest.findMany({
|
||||
where: { status: 'PENDING_REVIEW' },
|
||||
include: { store: { select: { name: true, phone: true } } },
|
||||
orderBy: { appliedAt: 'asc' },
|
||||
take: 20,
|
||||
});
|
||||
const now = new Date();
|
||||
const lines = overdueRows
|
||||
.filter((r) => isWithdrawOverdue(r.appliedAt, now))
|
||||
.slice(0, 10)
|
||||
.map(
|
||||
(r) =>
|
||||
`- ${r.store?.name || r.storeId} ${r.withdrawNo} ¥${Number(r.amount).toFixed(2)}`,
|
||||
);
|
||||
this.alert.notify({
|
||||
level: 'P1',
|
||||
category: 'finance',
|
||||
title: '门店提现超时未审',
|
||||
detail: [
|
||||
`待审 ${summary.pendingCount} 笔,超时 ${summary.overdueCount} 笔,超时金额 ¥${summary.overdueAmount.toFixed(2)}`,
|
||||
...lines,
|
||||
'请尽快在 HQ「财务 → 门店账单(手动提现)」处理。',
|
||||
].join('\n'),
|
||||
dedupeKey: `store_withdraw_overdue|${new Date().toISOString().slice(0, 10)}`,
|
||||
dedupeTtlSec: 6 * 3600,
|
||||
});
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
async listAdminStorePayouts(query: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
@@ -277,6 +781,9 @@ export class SettlementService {
|
||||
where: {
|
||||
storeBillId: null,
|
||||
createdAt: { gte: start, lt: end },
|
||||
// 排除已锁定在待审提现单中的明细,避免出账与提现双占
|
||||
withdrawItem: null,
|
||||
status: 'PENDING',
|
||||
},
|
||||
include: { store: { select: { id: true, settlementRate: true } } },
|
||||
});
|
||||
@@ -350,6 +857,152 @@ export class SettlementService {
|
||||
return { billDate: billDate.toISOString().slice(0, 10), created, skipped, payoutLinked: payouts.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 总部「门店账单」统一列表:T+1 StoreBill + 手动提现 StoreWithdrawRequest
|
||||
* 中小数据量内存合并后分页。
|
||||
*/
|
||||
async listAdminStoreSettlements(query: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
kind?: string;
|
||||
status?: string;
|
||||
storeId?: string;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}) {
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 20;
|
||||
const kind = query.kind === 'T1_BILL' || query.kind === 'WITHDRAW' ? query.kind : undefined;
|
||||
const status = query.status?.trim() || undefined;
|
||||
|
||||
const includeBills =
|
||||
!kind || kind === 'T1_BILL'
|
||||
? !status || status === 'UNPAID' || status === 'PAID'
|
||||
: false;
|
||||
const includeWithdraws =
|
||||
!kind || kind === 'WITHDRAW'
|
||||
? !status ||
|
||||
status === 'PENDING_REVIEW' ||
|
||||
status === 'REJECTED' ||
|
||||
status === 'PAID'
|
||||
: false;
|
||||
|
||||
const billWhere = includeBills
|
||||
? this.buildStoreBillWhere({
|
||||
status: status === 'UNPAID' || status === 'PAID' ? status : undefined,
|
||||
storeId: query.storeId,
|
||||
dateFrom: query.dateFrom,
|
||||
dateTo: query.dateTo,
|
||||
})
|
||||
: null;
|
||||
|
||||
const withdrawWhere: Prisma.StoreWithdrawRequestWhereInput | null = includeWithdraws
|
||||
? (() => {
|
||||
const where: Prisma.StoreWithdrawRequestWhereInput = {};
|
||||
if (status === 'PENDING_REVIEW' || status === 'REJECTED' || status === 'PAID') {
|
||||
where.status = status;
|
||||
}
|
||||
if (query.storeId) where.storeId = BigInt(query.storeId);
|
||||
if (query.dateFrom || query.dateTo) {
|
||||
where.appliedAt = {};
|
||||
if (query.dateFrom) where.appliedAt.gte = new Date(query.dateFrom);
|
||||
if (query.dateTo) {
|
||||
const end = new Date(query.dateTo);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
where.appliedAt.lte = end;
|
||||
}
|
||||
}
|
||||
return where;
|
||||
})()
|
||||
: null;
|
||||
|
||||
const bills = billWhere
|
||||
? await this.prisma.storeBill.findMany({
|
||||
where: billWhere,
|
||||
include: {
|
||||
store: { select: { id: true, name: true, cityName: true, phone: true } },
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const withdraws = withdrawWhere
|
||||
? await this.prisma.storeWithdrawRequest.findMany({
|
||||
where: withdrawWhere,
|
||||
include: {
|
||||
store: { select: { id: true, name: true, cityName: true, phone: true } },
|
||||
},
|
||||
})
|
||||
: [];
|
||||
|
||||
const now = new Date();
|
||||
type UnifiedRow = {
|
||||
kind: 'T1_BILL' | 'WITHDRAW';
|
||||
id: bigint;
|
||||
billNo: string;
|
||||
storeId: bigint;
|
||||
amount: number;
|
||||
status: string;
|
||||
date: Date;
|
||||
overdue?: boolean;
|
||||
redeemCount?: number;
|
||||
redeemAmount?: number;
|
||||
settlementRate?: number;
|
||||
payoutCount?: number;
|
||||
store?: { id: bigint; name: string; cityName: string; phone: string | null };
|
||||
};
|
||||
|
||||
const rows: UnifiedRow[] = [
|
||||
...bills.map((b) => ({
|
||||
kind: 'T1_BILL' as const,
|
||||
id: b.id,
|
||||
billNo: b.billNo,
|
||||
storeId: b.storeId,
|
||||
amount: Number(b.payoutAmount),
|
||||
status: b.status,
|
||||
date: b.billDate,
|
||||
redeemCount: b.redeemCount,
|
||||
redeemAmount: Number(b.redeemAmount),
|
||||
settlementRate: Number(b.settlementRate),
|
||||
store: b.store,
|
||||
})),
|
||||
...withdraws.map((w) => ({
|
||||
kind: 'WITHDRAW' as const,
|
||||
id: w.id,
|
||||
billNo: w.withdrawNo,
|
||||
storeId: w.storeId,
|
||||
amount: Number(w.amount),
|
||||
status: w.status,
|
||||
date: w.appliedAt,
|
||||
overdue: w.status === 'PENDING_REVIEW' ? isWithdrawOverdue(w.appliedAt, now) : false,
|
||||
payoutCount: w.payoutCount,
|
||||
store: w.store,
|
||||
})),
|
||||
];
|
||||
|
||||
rows.sort((a, b) => {
|
||||
const dt = b.date.getTime() - a.date.getTime();
|
||||
if (dt !== 0) return dt;
|
||||
return Number(b.id - a.id);
|
||||
});
|
||||
|
||||
const total = rows.length;
|
||||
const slice = rows.slice((page - 1) * pageSize, page * pageSize);
|
||||
const redeemAmount = bills.reduce((s, b) => s + Number(b.redeemAmount), 0);
|
||||
const payoutAmount = rows.reduce((s, r) => s + r.amount, 0);
|
||||
|
||||
return serializeBigInt({
|
||||
items: slice,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
summary: {
|
||||
count: total,
|
||||
redeemAmount,
|
||||
payoutAmount,
|
||||
totalAmount: payoutAmount,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async listAdminStoreBills(query: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { StoreService } from './store.service';
|
||||
import { StoreCategoryService } from './store-category.service';
|
||||
import { RedeemService } from '../redeem/redeem.service';
|
||||
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import { OptionalJwtAuthGuard } from '../../common/guards/optional-jwt-auth.guard';
|
||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||
import { RequirePartnerPermissions } from '../../common/decorators/partner-permission.decorator';
|
||||
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
||||
@@ -11,22 +12,53 @@ import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
|
||||
@Controller('stores')
|
||||
export class PublicStoreController {
|
||||
constructor(private readonly storeService: StoreService) {}
|
||||
constructor(
|
||||
private readonly storeService: StoreService,
|
||||
private readonly redeemService: RedeemService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
list(
|
||||
@UseGuards(OptionalJwtAuthGuard)
|
||||
async list(
|
||||
@CurrentUser() user: AuthUser | undefined,
|
||||
@Query('cityCode') cityCode?: string,
|
||||
@Query('lat') lat?: string,
|
||||
@Query('lng') lng?: string,
|
||||
) {
|
||||
const userLat = lat != null && lat !== '' ? Number(lat) : undefined;
|
||||
const userLng = lng != null && lng !== '' ? Number(lng) : undefined;
|
||||
return this.storeService.listOpenStores(cityCode, userLat, userLng);
|
||||
const viewerPhone = await this.resolveViewerPhone(user);
|
||||
return this.storeService.listOpenStores(cityCode, userLat, userLng, { phone: viewerPhone });
|
||||
}
|
||||
|
||||
@Get(':id/recent-redeems')
|
||||
@UseGuards(OptionalJwtAuthGuard)
|
||||
async recentRedeems(
|
||||
@CurrentUser() user: AuthUser | undefined,
|
||||
@Param('id') id: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
const viewerPhone = await this.resolveViewerPhone(user);
|
||||
// 与详情同权:白名单门店对不可见用户返回空(不泄露存在核销)
|
||||
try {
|
||||
await this.storeService.getStore(BigInt(id), { phone: viewerPhone });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const n = limit != null && limit !== '' ? Number(limit) : 20;
|
||||
return this.redeemService.listPublicStoreRecentRedeems(BigInt(id), Number.isFinite(n) ? n : 20);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@Param('id') id: string) {
|
||||
return this.storeService.getStore(BigInt(id));
|
||||
@UseGuards(OptionalJwtAuthGuard)
|
||||
async detail(@CurrentUser() user: AuthUser | undefined, @Param('id') id: string) {
|
||||
const viewerPhone = await this.resolveViewerPhone(user);
|
||||
return this.storeService.getStore(BigInt(id), { phone: viewerPhone });
|
||||
}
|
||||
|
||||
private async resolveViewerPhone(user?: AuthUser) {
|
||||
if (!user || user.actorType !== 'USER') return null;
|
||||
return this.storeService.resolveUserPhone(user.actorId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,17 @@ function normalizeOptionalTextField(value: unknown): string | null {
|
||||
return s;
|
||||
}
|
||||
|
||||
export type StoreViewer = {
|
||||
/** C 端用户手机号;无则无法看到白名单门店 */
|
||||
phone?: string | null;
|
||||
/** 运营/代下单等场景跳过白名单 */
|
||||
bypassWhitelist?: boolean;
|
||||
};
|
||||
|
||||
function normalizePhone(phone: string | null | undefined): string {
|
||||
return (phone || '').replace(/\D/g, '').trim();
|
||||
}
|
||||
|
||||
function parseOptionalCoord(value: unknown, kind: 'lat' | 'lng' = 'lng'): number | null {
|
||||
if (value == null || value === '') return null;
|
||||
const n = typeof value === 'number' ? value : Number(value);
|
||||
@@ -96,7 +107,34 @@ export class StoreService {
|
||||
return { latitude: geo.latitude, longitude: geo.longitude };
|
||||
}
|
||||
|
||||
async listOpenStores(cityCode?: string, userLat?: number, userLng?: number) {
|
||||
async resolveUserPhone(userId: bigint): Promise<string | null> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { phone: true },
|
||||
});
|
||||
return user?.phone ?? null;
|
||||
}
|
||||
|
||||
isVisibleToViewer(
|
||||
store: {
|
||||
visibilityWhitelistEnabled: boolean;
|
||||
visibilityPhones: Array<{ phone: string }>;
|
||||
},
|
||||
viewer?: StoreViewer,
|
||||
): boolean {
|
||||
if (viewer?.bypassWhitelist) return true;
|
||||
if (!store.visibilityWhitelistEnabled) return true;
|
||||
const phone = normalizePhone(viewer?.phone);
|
||||
if (!phone) return false;
|
||||
return store.visibilityPhones.some((row) => normalizePhone(row.phone) === phone);
|
||||
}
|
||||
|
||||
async listOpenStores(
|
||||
cityCode?: string,
|
||||
userLat?: number,
|
||||
userLng?: number,
|
||||
viewer?: StoreViewer,
|
||||
) {
|
||||
const where: Record<string, unknown> = { status: 'OPEN' };
|
||||
if (cityCode) {
|
||||
const city = await this.prisma.commonCity.findFirst({ where: { code: cityCode } });
|
||||
@@ -104,10 +142,16 @@ export class StoreService {
|
||||
}
|
||||
const stores = await this.prisma.store.findMany({
|
||||
where: where as never,
|
||||
include: { category: true, coverResource: true },
|
||||
include: {
|
||||
category: true,
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const visible = stores.filter((s) => this.isVisibleToViewer(s, viewer));
|
||||
|
||||
const hasUser =
|
||||
userLat != null &&
|
||||
userLng != null &&
|
||||
@@ -121,10 +165,11 @@ export class StoreService {
|
||||
};
|
||||
|
||||
const items: StoreListItem[] = [];
|
||||
for (const store of stores) {
|
||||
for (const store of visible) {
|
||||
const coords = await this.ensureStoreCoordinates(store);
|
||||
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||
const mapped = mapStoreCompat({
|
||||
...store,
|
||||
...rest,
|
||||
latitude: coords?.latitude ?? store.latitude,
|
||||
longitude: coords?.longitude ?? store.longitude,
|
||||
});
|
||||
@@ -146,20 +191,27 @@ export class StoreService {
|
||||
return serializeBigInt(items);
|
||||
}
|
||||
|
||||
async getStore(id: bigint) {
|
||||
async getStore(id: bigint, viewer?: StoreViewer) {
|
||||
const store = await this.prisma.store.findFirst({
|
||||
where: { id, status: 'OPEN' },
|
||||
include: { category: true, coverResource: true },
|
||||
include: {
|
||||
category: true,
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true } },
|
||||
},
|
||||
});
|
||||
if (!store) throw new NotFoundException('门店不存在');
|
||||
if (!store || !this.isVisibleToViewer(store, viewer)) {
|
||||
throw new NotFoundException('门店不存在');
|
||||
}
|
||||
const coords = await this.ensureStoreCoordinates(store);
|
||||
const media = await this.prisma.commonResource.findMany({
|
||||
where: { ownerType: 'STORE', ownerId: id, status: 'ACTIVE', bizType: 'ENV' },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
});
|
||||
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||
return serializeBigInt(
|
||||
mapStoreCompat({
|
||||
...store,
|
||||
...rest,
|
||||
latitude: coords?.latitude ?? store.latitude,
|
||||
longitude: coords?.longitude ?? store.longitude,
|
||||
media,
|
||||
|
||||
Reference in New Issue
Block a user