Compare commits
57 Commits
5deffbdbfb
...
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 | |||
| 87c4af7364 | |||
| 9f67221457 | |||
| 23587418c1 | |||
| daf534b4db | |||
| 0621ac18fb | |||
| 442f1ea842 | |||
| 8e25e23e81 | |||
| 118993a01f | |||
| a017a27b60 | |||
| 8f361981bf | |||
| 847a3f0dc3 | |||
| 49a5c057db | |||
| 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)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import DashboardPage from './pages/DashboardPage';
|
||||
import UsersPage from './pages/UsersPage';
|
||||
import OrdersPage from './pages/OrdersPage';
|
||||
import StoresPage from './pages/StoresPage';
|
||||
import StoreRatingsPage from './pages/StoreRatingsPage';
|
||||
import StoreAccountsPage from './pages/StoreAccountsPage';
|
||||
import BenefitCouponsPage from './pages/BenefitCouponsPage';
|
||||
import BenefitLedgersPage from './pages/BenefitLedgersPage';
|
||||
@@ -78,6 +79,7 @@ export default function App() {
|
||||
<Route path="/products" element={<ProductsPage />} />
|
||||
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||
<Route path="/stores" element={<StoresPage />} />
|
||||
<Route path="/store-ratings" element={<StoreRatingsPage />} />
|
||||
<Route path="/store-categories" element={<StoreCategoriesPage />} />
|
||||
<Route path="/store-accounts" element={<StoreAccountsPage />} />
|
||||
<Route path="/store-media" element={<StoreMediaPage />} />
|
||||
@@ -94,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 />} />
|
||||
|
||||
@@ -86,6 +86,22 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
.finally(() => setLoadingOptions(false));
|
||||
}, [open]);
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const allowOnline = selectedProduct ? selectedProduct.allowOnlinePurchase !== false : true;
|
||||
const allowOnSite = !!selectedProduct?.allowOnSitePickup;
|
||||
const allowCrossCity = selectedProduct ? selectedProduct.allowCrossCityDelivery !== false : true;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !selectedProduct) return;
|
||||
if (!allowOnline && allowOnSite && deliveryMode !== 'ON_SITE_PICKUP') {
|
||||
setDeliveryMode('ON_SITE_PICKUP');
|
||||
return;
|
||||
}
|
||||
if (allowOnline && !allowOnSite && deliveryMode !== 'ADDRESS') {
|
||||
setDeliveryMode('ADDRESS');
|
||||
}
|
||||
}, [open, selectedProduct, allowOnline, allowOnSite, deliveryMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !productId || quantity < 1 || step !== 'form') {
|
||||
if (step === 'form') setPreview(null);
|
||||
@@ -128,7 +144,6 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
setCreated(null);
|
||||
setCodeUrl(null);
|
||||
setPayLoading(false);
|
||||
setMockConfirming(false);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
@@ -140,12 +155,12 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||
if (!productId) return '请选择商品';
|
||||
if (deliveryMode === 'ADDRESS') {
|
||||
if (!allowOnline) return '该商品不支持线上购买';
|
||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||
if (!addressDetail.trim()) return '请填写详细地址';
|
||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||
} else {
|
||||
const product = options?.products.find((p) => p.id === productId);
|
||||
if (product && product.allowOnSitePickup === false) return '该商品不支持现场提货';
|
||||
} else if (!allowOnSite) {
|
||||
return '该商品不支持现场提货';
|
||||
}
|
||||
if (!preview) return '请等待费用计算完成';
|
||||
return null;
|
||||
@@ -329,20 +344,32 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
{allowOnline && allowOnSite ? (
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Typography.Text type="secondary">
|
||||
{!allowOnline && allowOnSite
|
||||
? '该商品仅支持现场提货'
|
||||
: allowOnline && !allowOnSite
|
||||
? allowCrossCity
|
||||
? '该商品仅支持配送到址(含跨城)'
|
||||
: '该商品仅支持配送到址(不可跨城)'
|
||||
: '该商品暂无可选履约方式'}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
|
||||
@@ -51,6 +51,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
label: '门店',
|
||||
children: [
|
||||
{ key: '/stores', label: '门店列表' },
|
||||
{ key: '/store-ratings', label: '门店评价' },
|
||||
{ key: '/store-categories', label: '门店分类' },
|
||||
{ key: '/store-accounts', label: '门店账户' },
|
||||
{ key: '/store-media', label: '门店资源' },
|
||||
@@ -145,6 +146,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/knowledge-bases': 'knowledge_bases',
|
||||
'stores-group': 'stores',
|
||||
'/stores': 'stores',
|
||||
'/store-ratings': 'stores',
|
||||
'/store-categories': 'stores',
|
||||
'/store-accounts': 'stores',
|
||||
'/store-media': 'stores',
|
||||
@@ -155,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="个" />
|
||||
|
||||
@@ -32,6 +32,8 @@ type Row = {
|
||||
status: string;
|
||||
sortOrder: number;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
mainImageUrl?: string | null;
|
||||
@@ -53,6 +55,8 @@ type ProductFormValues = {
|
||||
status?: string;
|
||||
sortOrder?: number;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
coverUrl?: string;
|
||||
@@ -72,13 +76,17 @@ type UserPickRow = {
|
||||
|
||||
function mapDetailToForm(d: Record<string, unknown>) {
|
||||
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
||||
const row = d as Row;
|
||||
return {
|
||||
...d,
|
||||
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
||||
carouselUrls: ((d as Row).carouselUrls?.length ? (d as Row).carouselUrls : ['']) as string[],
|
||||
detailImageUrls: ((d as Row).detailImageUrls?.length ? (d as Row).detailImageUrls : ['']) as string[],
|
||||
visibilityWhitelistEnabled: !!(d as Row).visibilityWhitelistEnabled,
|
||||
visibilityPhones: ((d as Row).visibilityPhones ?? []) as string[],
|
||||
carouselUrls: (row.carouselUrls?.length ? row.carouselUrls : ['']) as string[],
|
||||
detailImageUrls: (row.detailImageUrls?.length ? row.detailImageUrls : ['']) as string[],
|
||||
allowOnlinePurchase: row.allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery: row.allowOnlinePurchase === false ? false : row.allowCrossCityDelivery !== false,
|
||||
allowOnSitePickup: !!row.allowOnSitePickup,
|
||||
visibilityWhitelistEnabled: !!row.visibilityWhitelistEnabled,
|
||||
visibilityPhones: (row.visibilityPhones ?? []) as string[],
|
||||
storyTitle: detail.storyTitle ?? '',
|
||||
storyText: detail.storyText ?? '',
|
||||
features: detail.features?.length
|
||||
@@ -109,7 +117,6 @@ function buildProductPayload(v: ProductFormValues) {
|
||||
.filter(Boolean);
|
||||
|
||||
return {
|
||||
skuCode: v.skuCode,
|
||||
barcode69: v.barcode69,
|
||||
name: v.name,
|
||||
subtitle: v.subtitle,
|
||||
@@ -120,6 +127,9 @@ function buildProductPayload(v: ProductFormValues) {
|
||||
status: v.status,
|
||||
sortOrder: v.sortOrder,
|
||||
allowOnSitePickup: !!v.allowOnSitePickup,
|
||||
allowOnlinePurchase: v.allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery:
|
||||
v.allowOnlinePurchase === false ? false : v.allowCrossCityDelivery !== false,
|
||||
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||
visibilityPhones,
|
||||
coverUrl: v.coverUrl,
|
||||
@@ -288,8 +298,8 @@ function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormIns
|
||||
<>
|
||||
{mode === 'create' && (
|
||||
<>
|
||||
<Form.Item name="skuCode" label="SKU" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
<Form.Item label="SKU">
|
||||
<Input disabled placeholder="保存后自动生成" />
|
||||
</Form.Item>
|
||||
<Form.Item name="barcode69" label="69码" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
@@ -320,6 +330,36 @@ function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormIns
|
||||
<Form.Item name="sortOrder" label="排序">
|
||||
<InputNumber min={0} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="allowOnlinePurchase"
|
||||
label="允许线上购买"
|
||||
valuePropName="checked"
|
||||
extra="配送到址(同城)"
|
||||
>
|
||||
<Switch
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
onChange={(checked) => {
|
||||
if (!checked) form.setFieldsValue({ allowCrossCityDelivery: false });
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item noStyle shouldUpdate={(prev, cur) => prev.allowOnlinePurchase !== cur.allowOnlinePurchase}>
|
||||
{() => (
|
||||
<Form.Item
|
||||
name="allowCrossCityDelivery"
|
||||
label="允许跨城配送"
|
||||
valuePropName="checked"
|
||||
extra="须先开启线上购买"
|
||||
>
|
||||
<Switch
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
disabled={!form.getFieldValue('allowOnlinePurchase')}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form.Item>
|
||||
<Form.Item name="allowOnSitePickup" label="允许现场取货" valuePropName="checked">
|
||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||
</Form.Item>
|
||||
@@ -383,10 +423,19 @@ export default function ProductsPage() {
|
||||
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||
},
|
||||
{
|
||||
title: '现场取货',
|
||||
dataIndex: 'allowOnSitePickup',
|
||||
width: 90,
|
||||
render: (v: boolean) => (v ? <Tag color="green">允许</Tag> : <Tag>否</Tag>),
|
||||
title: '履约',
|
||||
key: 'fulfillment',
|
||||
width: 160,
|
||||
render: (_, row) => (
|
||||
<Space size={[0, 4]} wrap>
|
||||
{row.allowOnlinePurchase !== false ? <Tag color="blue">线上</Tag> : null}
|
||||
{row.allowOnlinePurchase !== false && row.allowCrossCityDelivery !== false ? (
|
||||
<Tag color="cyan">跨城</Tag>
|
||||
) : null}
|
||||
{row.allowOnSitePickup ? <Tag color="green">现场</Tag> : null}
|
||||
{row.allowOnlinePurchase === false && !row.allowOnSitePickup ? <Tag>无</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '排序', dataIndex: 'sortOrder', width: 60 },
|
||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
@@ -431,12 +480,16 @@ export default function ProductsPage() {
|
||||
</Form.Item>
|
||||
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
||||
</Form>
|
||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1240 }}
|
||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1320 }}
|
||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||
<Drawer title="编辑商品" width={720} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||
extra={detail && (
|
||||
<Button type="primary" onClick={async () => {
|
||||
const v = await editForm.validateFields();
|
||||
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||
return;
|
||||
}
|
||||
const payload = buildProductPayload(v);
|
||||
await request(`/admin/products/${detail.id}`, { method: 'PUT', body: JSON.stringify(payload) });
|
||||
message.success('已保存');
|
||||
@@ -471,6 +524,10 @@ export default function ProductsPage() {
|
||||
</Drawer>
|
||||
<Modal title="新建商品" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
|
||||
const v = await createForm.validateFields();
|
||||
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||
return;
|
||||
}
|
||||
const payload = buildProductPayload(v);
|
||||
await request('/admin/products', { method: 'POST', body: JSON.stringify(payload) });
|
||||
message.success('已创建');
|
||||
@@ -479,7 +536,8 @@ export default function ProductsPage() {
|
||||
void reload();
|
||||
}} width={720}>
|
||||
<Form form={createForm} layout="vertical" initialValues={{
|
||||
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0, allowOnSitePickup: false,
|
||||
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0,
|
||||
allowOnlinePurchase: true, allowCrossCityDelivery: true, allowOnSitePickup: false,
|
||||
visibilityWhitelistEnabled: false, visibilityPhones: [],
|
||||
carouselUrls: [''], detailImageUrls: [''],
|
||||
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
||||
|
||||
@@ -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,105 @@
|
||||
import { useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button, Form, Input, Table, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
serviceScore: number;
|
||||
envScore: number;
|
||||
createdAt: string;
|
||||
redeemNo: string;
|
||||
redeemAmount: number;
|
||||
store?: { id: string; name: string; cityName?: string };
|
||||
user?: { userNo: string; phone: string | null; nickname: string | null };
|
||||
};
|
||||
|
||||
export default function StoreRatingsPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialStoreId = searchParams.get('storeId') || '';
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({
|
||||
...(initialStoreId ? { storeId: initialStoreId } : {}),
|
||||
});
|
||||
|
||||
const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
|
||||
'/admin/store-ratings',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
);
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||
{
|
||||
title: '门店',
|
||||
dataIndex: ['store', 'name'],
|
||||
render: (v, row) => (row.store?.cityName ? `${v}(${row.store.cityName})` : v),
|
||||
},
|
||||
{
|
||||
title: '用户',
|
||||
width: 140,
|
||||
render: (_, row) => row.user?.phone || row.user?.userNo || '-',
|
||||
},
|
||||
{ title: '核销额', dataIndex: 'redeemAmount', width: 90, render: (v) => `¥${v}` },
|
||||
{ title: '服务分', dataIndex: 'serviceScore', width: 80 },
|
||||
{ title: '环境分', dataIndex: 'envScore', width: 80 },
|
||||
{ title: '评价时间', dataIndex: 'createdAt', width: 170, render: fmtTime },
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4} style={{ marginTop: 0 }}>
|
||||
门店评价
|
||||
</Typography.Title>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
initialValues={filters}
|
||||
onFinish={(v) => {
|
||||
setFilters({
|
||||
storeId: v.storeId || '',
|
||||
redeemNo: v.redeemNo || '',
|
||||
});
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="storeId" label="门店ID">
|
||||
<Input allowClear placeholder="storeId" />
|
||||
</Form.Item>
|
||||
<Form.Item name="redeemNo" label="核销号">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</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,13 +867,23 @@ 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 },
|
||||
{
|
||||
title: '操作', width: 80,
|
||||
title: '操作', width: 140,
|
||||
render: (_, row) => (
|
||||
<Button type="link" size="small" onClick={() => void openStoreDetail(row)}>详情</Button>
|
||||
<Space size={0}>
|
||||
<Button type="link" size="small" onClick={() => void openStoreDetail(row)}>详情</Button>
|
||||
<Button type="link" size="small" onClick={() => navigate(`/store-ratings?storeId=${row.id}`)}>评价</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -1056,6 +1167,7 @@ export default function StoresPage() {
|
||||
<Input type="time" style={{ width: 140 }} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<StoreVisibilityWhitelistFields form={editForm} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1276,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">
|
||||
|
||||
@@ -151,6 +151,22 @@ export default function ProxyOrderPage() {
|
||||
autoReceive,
|
||||
]);
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const allowOnline = selectedProduct ? selectedProduct.allowOnlinePurchase !== false : true;
|
||||
const allowOnSite = !!selectedProduct?.allowOnSitePickup;
|
||||
const allowCrossCity = selectedProduct ? selectedProduct.allowCrossCityDelivery !== false : true;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProduct) return;
|
||||
if (!allowOnline && allowOnSite && deliveryMode !== 'ON_SITE_PICKUP') {
|
||||
setDeliveryMode('ON_SITE_PICKUP');
|
||||
return;
|
||||
}
|
||||
if (allowOnline && !allowOnSite && deliveryMode !== 'ADDRESS') {
|
||||
setDeliveryMode('ADDRESS');
|
||||
}
|
||||
}, [selectedProduct, allowOnline, allowOnSite, deliveryMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!productId || quantity < 1) {
|
||||
setPreview(null);
|
||||
@@ -169,8 +185,14 @@ export default function ProxyOrderPage() {
|
||||
}),
|
||||
silent: true,
|
||||
})
|
||||
.then(setPreview)
|
||||
.catch(() => setPreview(null))
|
||||
.then((data) => {
|
||||
setPreview(data);
|
||||
setMsg('');
|
||||
})
|
||||
.catch((e) => {
|
||||
setPreview(null);
|
||||
setMsg(e instanceof Error ? e.message : '费用预览失败');
|
||||
})
|
||||
.finally(() => setPreviewLoading(false));
|
||||
}, 300);
|
||||
return () => clearTimeout(timer);
|
||||
@@ -180,11 +202,14 @@ export default function ProxyOrderPage() {
|
||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||
if (!productId) return '请选择商品';
|
||||
if (deliveryMode === 'ADDRESS') {
|
||||
if (!allowOnline) return '该商品不支持线上购买';
|
||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||
if (!addressDetail.trim()) return '请填写详细地址';
|
||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||
} else if (!allowOnSite) {
|
||||
return '该商品不支持现场提货';
|
||||
}
|
||||
if (!preview) return '请等待费用计算完成';
|
||||
if (!preview) return msg || '请等待费用计算完成';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -305,7 +330,6 @@ export default function ProxyOrderPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const deliveryLabel =
|
||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '现场提货'
|
||||
@@ -477,25 +501,37 @@ export default function ProxyOrderPage() {
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">履约方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${deliveryMode === 'ADDRESS' ? ' is-active' : ''}`}
|
||||
onClick={() => setDeliveryMode('ADDRESS')}
|
||||
>
|
||||
配送到址
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${deliveryMode === 'ON_SITE_PICKUP' ? ' is-active' : ''}`}
|
||||
onClick={() => setDeliveryMode('ON_SITE_PICKUP')}
|
||||
>
|
||||
现场提货
|
||||
</button>
|
||||
</div>
|
||||
{allowOnline && allowOnSite ? (
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${deliveryMode === 'ADDRESS' ? ' is-active' : ''}`}
|
||||
onClick={() => setDeliveryMode('ADDRESS')}
|
||||
>
|
||||
配送到址
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${deliveryMode === 'ON_SITE_PICKUP' ? ' is-active' : ''}`}
|
||||
onClick={() => setDeliveryMode('ON_SITE_PICKUP')}
|
||||
>
|
||||
现场提货
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="label-md text-muted">
|
||||
{!allowOnline && allowOnSite
|
||||
? '该商品仅支持现场提货'
|
||||
: allowOnline && !allowOnSite
|
||||
? allowCrossCity
|
||||
? '该商品仅支持配送到址(含跨城)'
|
||||
: '该商品仅支持配送到址(不可跨城)'
|
||||
: '该商品暂无可选履约方式'}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||
<>
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">收货人(选填)</label>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { request } from '../lib/api';
|
||||
@@ -9,12 +9,30 @@ function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
type FulfillmentFilter = 'ALL' | 'ONLINE' | 'CROSS_CITY' | 'ON_SITE';
|
||||
|
||||
const FILTERS: Array<{ key: FulfillmentFilter; label: string }> = [
|
||||
{ key: 'ALL', label: '全部' },
|
||||
{ key: 'ONLINE', label: '线上' },
|
||||
{ key: 'CROSS_CITY', label: '跨城' },
|
||||
{ key: 'ON_SITE', label: '现场' },
|
||||
];
|
||||
|
||||
function matchFilter(p: PartnerProxyOrderProductOption, filter: FulfillmentFilter): boolean {
|
||||
if (filter === 'ALL') return true;
|
||||
if (filter === 'ONLINE') return p.allowOnlinePurchase !== false;
|
||||
if (filter === 'CROSS_CITY') return p.allowCrossCityDelivery !== false;
|
||||
return !!p.allowOnSitePickup;
|
||||
}
|
||||
|
||||
export default function ProxyOrderProductsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const selectedId = searchParams.get('selected') || '';
|
||||
const [products, setProducts] = useState<PartnerProxyOrderProductOption[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [filter, setFilter] = useState<FulfillmentFilter>('ALL');
|
||||
|
||||
useEffect(() => {
|
||||
request<PartnerProxyOrderOptions>('PARTNER_H5', '/partner/proxy-orders/options')
|
||||
@@ -23,6 +41,15 @@ export default function ProxyOrderProductsPage() {
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = keyword.trim().toLowerCase();
|
||||
return products.filter((p) => {
|
||||
if (!matchFilter(p, filter)) return false;
|
||||
if (!q) return true;
|
||||
return `${p.name} ${p.spec}`.toLowerCase().includes(q);
|
||||
});
|
||||
}, [products, keyword, filter]);
|
||||
|
||||
function pick(product: PartnerProxyOrderProductOption) {
|
||||
navigate(`/proxy-order?productId=${encodeURIComponent(product.id)}`, { replace: true });
|
||||
}
|
||||
@@ -30,12 +57,32 @@ export default function ProxyOrderProductsPage() {
|
||||
return (
|
||||
<div className="page partner-proxy-order-page">
|
||||
<PageHeader title="选择酒品" onBack={() => navigate(-1)} />
|
||||
<div className="partner-proxy-product-toolbar">
|
||||
<input
|
||||
className="partner-input"
|
||||
placeholder="搜索酒品名称 / 规格"
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
/>
|
||||
<div className="partner-proxy-product-filters">
|
||||
{FILTERS.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
type="button"
|
||||
className={`partner-proxy-product-filter${filter === f.key ? ' is-active' : ''}`}
|
||||
onClick={() => setFilter(f.key)}
|
||||
>
|
||||
{f.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<main className="partner-proxy-product-list">
|
||||
{loading ? <p className="label-md text-muted">加载中…</p> : null}
|
||||
{!loading && products.length === 0 ? (
|
||||
<p className="label-md text-muted">暂无可售商品</p>
|
||||
{!loading && filtered.length === 0 ? (
|
||||
<p className="label-md text-muted">暂无符合条件的商品</p>
|
||||
) : null}
|
||||
{products.map((p) => {
|
||||
{filtered.map((p) => {
|
||||
const benefit = p.benefitAmount != null ? Number(p.benefitAmount) : Number(p.price);
|
||||
const active = p.id === selectedId;
|
||||
return (
|
||||
@@ -59,6 +106,11 @@ export default function ProxyOrderProductsPage() {
|
||||
</div>
|
||||
<p className="partner-proxy-product-spec">{p.spec}</p>
|
||||
<p className="partner-proxy-product-benefit">好客权益 ¥{fmtMoney(benefit)}</p>
|
||||
<div className="partner-proxy-product-tags">
|
||||
{p.allowOnlinePurchase !== false ? <span className="partner-proxy-tag">线上</span> : null}
|
||||
{p.allowCrossCityDelivery !== false ? <span className="partner-proxy-tag">跨城</span> : null}
|
||||
{p.allowOnSitePickup ? <span className="partner-proxy-tag">现场</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -3374,6 +3374,50 @@ body {
|
||||
color: var(--color-muted, #999);
|
||||
}
|
||||
|
||||
.partner-proxy-product-toolbar {
|
||||
padding: 0 16px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.partner-proxy-product-filters {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.partner-proxy-product-filter {
|
||||
border: 1px solid var(--color-border);
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--color-muted, #888);
|
||||
}
|
||||
|
||||
.partner-proxy-product-filter.is-active {
|
||||
border-color: var(--color-heritage-red);
|
||||
color: var(--color-heritage-red);
|
||||
background: rgba(166, 29, 36, 0.06);
|
||||
}
|
||||
|
||||
.partner-proxy-product-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.partner-proxy-tag {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
color: var(--color-muted, #666);
|
||||
}
|
||||
|
||||
.partner-proxy-product-list {
|
||||
padding: 0 16px 24px;
|
||||
display: flex;
|
||||
|
||||
@@ -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 />} />
|
||||
|
||||
@@ -27,7 +27,7 @@ function formatScanError(e: unknown): string {
|
||||
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
||||
}
|
||||
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
||||
return `${msg}(可在 URL 后加 ?wxdebug=1 开启 JSSDK 调试查看详情)`;
|
||||
return '微信权限校验尚未完成,请等待 1~2 秒后再次点击扫码(首次绑定微信时较常见)';
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export default function HomePage() {
|
||||
};
|
||||
}, [loadDashboard]);
|
||||
|
||||
async function runScan() {
|
||||
async function runScan(opts?: { postAuthWarmup?: boolean }) {
|
||||
if (!isWechatEnv()) {
|
||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||
return;
|
||||
@@ -81,8 +81,14 @@ export default function HomePage() {
|
||||
setScanning(true);
|
||||
setScanMsg('');
|
||||
try {
|
||||
// 授权回跳后强制重签,避免沿用带 code 的旧签名态
|
||||
if (opts?.postAuthWarmup) {
|
||||
weixinSdk.reset();
|
||||
}
|
||||
await weixinSdk.init();
|
||||
const raw = await weixinSdk.scanQrCode();
|
||||
const raw = await weixinSdk.scanQrCode(
|
||||
opts?.postAuthWarmup ? { postAuthWarmup: true } : undefined,
|
||||
);
|
||||
if (!raw) {
|
||||
void loadDashboard();
|
||||
return;
|
||||
@@ -111,12 +117,14 @@ export default function HomePage() {
|
||||
}
|
||||
setAuthModalOpen(false);
|
||||
setAuthError('');
|
||||
// 先清 OAuth 参数再扫,保证 JSSDK 签名 URL 与当前页一致
|
||||
stripOAuthParamsFromLocation();
|
||||
setSearchParams({}, { replace: true });
|
||||
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
||||
if (shouldScan) {
|
||||
window.setTimeout(() => void runScan(), 0);
|
||||
// OAuth 回跳后微信权限离线校验未完成;稍候再扫,失败可再点一次
|
||||
window.setTimeout(() => void runScan({ postAuthWarmup: true }), 400);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -182,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`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/** 商品履约能力(与 HQ / 交易硬闸一致) */
|
||||
|
||||
export type FulfillmentFlags = {
|
||||
allowOnlinePurchase?: boolean | null;
|
||||
allowOnSitePickup?: boolean | null;
|
||||
allowCrossCityDelivery?: boolean | null;
|
||||
};
|
||||
|
||||
/** 未返回时默认允许线上(存量商品) */
|
||||
export function canBuyOnline(p: FulfillmentFlags): boolean {
|
||||
return p.allowOnlinePurchase !== false;
|
||||
}
|
||||
|
||||
/** 仅显式开启才展示现场取货 */
|
||||
export function canPickupOnSite(p: FulfillmentFlags): boolean {
|
||||
return p.allowOnSitePickup === true;
|
||||
}
|
||||
|
||||
export function canCrossCity(p: FulfillmentFlags): boolean {
|
||||
return p.allowCrossCityDelivery !== false;
|
||||
}
|
||||
|
||||
export function normalizeFulfillmentFlags<T extends FulfillmentFlags>(p: T): T {
|
||||
return {
|
||||
...p,
|
||||
allowOnlinePurchase: canBuyOnline(p),
|
||||
allowOnSitePickup: canPickupOnSite(p),
|
||||
allowCrossCityDelivery: canCrossCity(p),
|
||||
};
|
||||
}
|
||||
|
||||
/** 与交易侧一致:收货市 ≠ 开城市且 ≠ 郑州 → 跨城 */
|
||||
export function isCrossCityAddress(
|
||||
addressCity: string | null | undefined,
|
||||
openCityName: string | null | undefined,
|
||||
): boolean {
|
||||
const addr = (addressCity || '').trim();
|
||||
const open = (openCityName || '').trim();
|
||||
if (!addr) return false;
|
||||
if (addr === '郑州市') return false;
|
||||
if (open && addr === open) return false;
|
||||
// 尚无开城信息时,非郑州地址先按可能跨城处理(由预览接口最终裁定)
|
||||
if (!open) return addr !== '郑州市';
|
||||
return true;
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export type StoresSessionCategory = {
|
||||
export type StoresListCache = {
|
||||
cityKey: string;
|
||||
cityCode: string;
|
||||
/** 登录态指纹:token 变化时需重新拉取(白名单) */
|
||||
authKey: string;
|
||||
listRegion: StoresSessionRegion;
|
||||
items: unknown[];
|
||||
filterRegion: StoresSessionRegion;
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useCallback, useMemo, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
@@ -13,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 = {
|
||||
@@ -31,9 +31,13 @@ type CouponItem = {
|
||||
sourceProduct: string;
|
||||
};
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
type RedeemHistoryItem = {
|
||||
id: string;
|
||||
redeemNo: string;
|
||||
amount: number;
|
||||
storeName: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function usagePercent(coupon: CouponItem) {
|
||||
const total = Number(coupon.totalAmount);
|
||||
@@ -46,11 +50,13 @@ export default function BenefitPage() {
|
||||
const [loggedIn, setLoggedIn] = useState(() => isLoggedIn());
|
||||
const [summary, setSummary] = useState<BenefitSummary | null>(null);
|
||||
const [coupons, setCoupons] = useState<CouponItem[]>([]);
|
||||
const [redeemHistory, setRedeemHistory] = useState<RedeemHistoryItem[]>([]);
|
||||
const [tab, setTab] = useState<'available' | 'history'>('available');
|
||||
|
||||
const resetGuestState = useCallback(() => {
|
||||
setSummary(null);
|
||||
setCoupons([]);
|
||||
setRedeemHistory([]);
|
||||
}, []);
|
||||
|
||||
const loadBenefit = useCallback(() => {
|
||||
@@ -58,10 +64,17 @@ export default function BenefitPage() {
|
||||
return Promise.all([
|
||||
request<BenefitSummary>('/benefit/summary'),
|
||||
request<CouponItem[]>('/benefit/coupons'),
|
||||
request<{ list?: RedeemHistoryItem[] } | RedeemHistoryItem[]>('/redeem/records?page=1&pageSize=50'),
|
||||
])
|
||||
.then(([s, list]) => {
|
||||
.then(([s, list, records]) => {
|
||||
setSummary(s);
|
||||
setCoupons(Array.isArray(list) ? list : []);
|
||||
const hist = Array.isArray(records)
|
||||
? records
|
||||
: Array.isArray(records?.list)
|
||||
? records.list
|
||||
: [];
|
||||
setRedeemHistory(hist);
|
||||
})
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
}, []);
|
||||
@@ -89,8 +102,6 @@ export default function BenefitPage() {
|
||||
});
|
||||
|
||||
const available = coupons.filter((c) => c.status === 'ACTIVE' && c.balance > 0);
|
||||
const history = coupons.filter((c) => c.status === 'USED_UP' || c.status === 'VOID');
|
||||
const visible = tab === 'available' ? available : history;
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => ({
|
||||
@@ -123,9 +134,6 @@ export default function BenefitPage() {
|
||||
<View className="benefit-header-city-pin" />
|
||||
<Text>郑州市</Text>
|
||||
</View>
|
||||
<View className="benefit-header__share page-nav-bar__right-slot">
|
||||
<ShareNavButton payload={sharePayload} />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -180,26 +188,26 @@ export default function BenefitPage() {
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<View className="u-empty">{tab === 'available' ? '暂无可用权益' : '暂无历史记录'}</View>
|
||||
) : (
|
||||
visible.map((c) => (
|
||||
<View key={c.id} className="benefit-coupon">
|
||||
<View className="benefit-coupon-notch" />
|
||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||
<View className="benefit-coupon-head">
|
||||
<Text className="benefit-coupon-name">{c.sourceProduct || '好客权益'}</Text>
|
||||
<Text className="benefit-coupon-balance">¥{formatMoney(c.balance)}</Text>
|
||||
</View>
|
||||
<Text className="benefit-coupon-no">NO. {c.couponNo}</Text>
|
||||
<View className="benefit-progress">
|
||||
<View className="benefit-progress-bar" style={{ width: `${usagePercent(c)}%` }} />
|
||||
</View>
|
||||
<View className="benefit-coupon-footer">
|
||||
<Text className="benefit-coupon-meta">
|
||||
已用 ¥{formatMoney(c.usedAmount)} / 总额 ¥{formatMoney(c.totalAmount)}
|
||||
</Text>
|
||||
{tab === 'available' ? (
|
||||
{tab === 'available' ? (
|
||||
available.length === 0 ? (
|
||||
<View className="u-empty">暂无可用权益</View>
|
||||
) : (
|
||||
available.map((c) => (
|
||||
<View key={c.id} className="benefit-coupon">
|
||||
<View className="benefit-coupon-notch" />
|
||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||
<View className="benefit-coupon-head">
|
||||
<Text className="benefit-coupon-name">{c.sourceProduct || '好客权益'}</Text>
|
||||
<Text className="benefit-coupon-balance">¥{formatMoney(c.balance)}</Text>
|
||||
</View>
|
||||
<Text className="benefit-coupon-no">NO. {c.couponNo}</Text>
|
||||
<View className="benefit-progress">
|
||||
<View className="benefit-progress-bar" style={{ width: `${usagePercent(c)}%` }} />
|
||||
</View>
|
||||
<View className="benefit-coupon-footer">
|
||||
<Text className="benefit-coupon-meta">
|
||||
已用 ¥{formatMoney(c.usedAmount)} / 总额 ¥{formatMoney(c.totalAmount)}
|
||||
</Text>
|
||||
<Text
|
||||
className="benefit-coupon-btn"
|
||||
onClick={() =>
|
||||
@@ -210,7 +218,26 @@ export default function BenefitPage() {
|
||||
>
|
||||
立即核销
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
))
|
||||
)
|
||||
) : redeemHistory.length === 0 ? (
|
||||
<View className="u-empty">暂无核销记录</View>
|
||||
) : (
|
||||
redeemHistory.map((r) => (
|
||||
<View key={r.id} className="benefit-coupon">
|
||||
<View className="benefit-coupon-notch" />
|
||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||
<View className="benefit-coupon-head">
|
||||
<Text className="benefit-coupon-name">{r.storeName || '门店核销'}</Text>
|
||||
<Text className="benefit-coupon-balance">-¥{formatMoney(Number(r.amount))}</Text>
|
||||
</View>
|
||||
<Text className="benefit-coupon-no">NO. {r.redeemNo}</Text>
|
||||
<View className="benefit-coupon-footer">
|
||||
<Text className="benefit-coupon-meta">
|
||||
{r.createdAt ? String(r.createdAt).slice(0, 19).replace('T', ' ') : '-'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
))
|
||||
|
||||
@@ -1,23 +1,39 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
usePageScroll,
|
||||
usePullDownRefresh,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import TabMainHeader from '../../components/TabMainHeader';
|
||||
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';
|
||||
import {
|
||||
canBuyOnline,
|
||||
canCrossCity,
|
||||
canPickupOnSite,
|
||||
normalizeFulfillmentFlags,
|
||||
} from '../../lib/product-fulfillment';
|
||||
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
|
||||
type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -29,8 +45,26 @@ type Product = {
|
||||
carouselUrls?: string[] | null;
|
||||
aromaType: string;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
};
|
||||
|
||||
type FulfillmentFilter = 'ALL' | 'ONLINE' | 'CROSS_CITY' | 'ON_SITE';
|
||||
|
||||
const FULFILLMENT_FILTERS: Array<{ key: FulfillmentFilter; label: string }> = [
|
||||
{ key: 'ALL', label: '全部' },
|
||||
{ key: 'ONLINE', label: '线上' },
|
||||
{ key: 'CROSS_CITY', label: '跨城' },
|
||||
{ key: 'ON_SITE', label: '现场' },
|
||||
];
|
||||
|
||||
function matchFulfillmentFilter(p: Product, filter: FulfillmentFilter): boolean {
|
||||
if (filter === 'ALL') return true;
|
||||
if (filter === 'ONLINE') return canBuyOnline(p);
|
||||
if (filter === 'CROSS_CITY') return canCrossCity(p);
|
||||
return canPickupOnSite(p);
|
||||
}
|
||||
|
||||
type MiniHomeConfig = {
|
||||
banners: string[];
|
||||
footerUrl: string | null;
|
||||
@@ -42,13 +76,26 @@ const AROMA_TABS = [
|
||||
{ key: 'NONGXIANG', label: '浓香型' },
|
||||
] as const;
|
||||
|
||||
type AromaKey = (typeof AROMA_TABS)[number]['key'];
|
||||
|
||||
/** sticky 香型导航高度(与 CSS 大致一致),锚点滚动时预留 */
|
||||
const AROMA_NAV_OFFSET_PX = 44;
|
||||
|
||||
function aromaSectionId(key: AromaKey) {
|
||||
return `aroma-section-${key}`;
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const [tab, setTab] = useState('QINGXIANG');
|
||||
const [activeAroma, setActiveAroma] = useState<AromaKey>('QINGXIANG');
|
||||
const [fulfillmentFilter, setFulfillmentFilter] = useState<FulfillmentFilter>('ALL');
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [displayCity, setDisplayCity] = useState('郑州市');
|
||||
const [cityCode, setCityCode] = useState('410100');
|
||||
const [miniHome, setMiniHome] = useState<MiniHomeConfig>({ banners: [], footerUrl: null });
|
||||
const scrollingToRef = useRef<AromaKey | null>(null);
|
||||
const scrollLockTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastScrollSyncAtRef = useRef(0);
|
||||
|
||||
const loadMiniHome = useCallback(() => {
|
||||
return request<{ miniHome?: MiniHomeConfig }>('/common/client-config')
|
||||
@@ -67,31 +114,60 @@ export default function HomePage() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
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();
|
||||
void resolveUserCity().then((resolved) => {
|
||||
|
||||
const authKey = getToken() || '';
|
||||
void (async () => {
|
||||
const resolved = await resolveUserCity();
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
setDisplayCity(resolved.displayCity);
|
||||
setCityCode(getCityCodeForCatalog(resolved));
|
||||
});
|
||||
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);
|
||||
})();
|
||||
});
|
||||
|
||||
const loadProducts = useCallback(() => {
|
||||
setLoading(true);
|
||||
return request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(cityCode)}`)
|
||||
.then((list) => setProducts(Array.isArray(list) ? list : []))
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [cityCode]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadProducts();
|
||||
}, [loadProducts]);
|
||||
|
||||
usePullDownRefresh(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const authKey = getToken() || '';
|
||||
const resolved = await resolveUserCity();
|
||||
setDisplayCity(resolved.displayCity);
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
@@ -101,7 +177,11 @@ export default function HomePage() {
|
||||
request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
|
||||
loadMiniHome(),
|
||||
]);
|
||||
setProducts(Array.isArray(list) ? list : []);
|
||||
applyProductList(
|
||||
Array.isArray(list) ? list : [],
|
||||
nextCode,
|
||||
authKey,
|
||||
);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
@@ -110,7 +190,6 @@ export default function HomePage() {
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
function openProductDetail(id: string) {
|
||||
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
||||
}
|
||||
@@ -126,7 +205,24 @@ export default function HomePage() {
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
const filtered = products.filter((p) => p.aromaType === tab);
|
||||
const filteredProducts = useMemo(
|
||||
() => products.filter((p) => matchFulfillmentFilter(p, fulfillmentFilter)),
|
||||
[products, fulfillmentFilter],
|
||||
);
|
||||
|
||||
const productsByAroma = useMemo(() => {
|
||||
const map: Record<AromaKey, Product[]> = {
|
||||
QINGXIANG: [],
|
||||
JIANGXIANG: [],
|
||||
NONGXIANG: [],
|
||||
};
|
||||
for (const p of filteredProducts) {
|
||||
const key = p.aromaType as AromaKey;
|
||||
if (key in map) map[key].push(p);
|
||||
}
|
||||
return map;
|
||||
}, [filteredProducts]);
|
||||
|
||||
const banners = miniHome.banners;
|
||||
const footerUrl = miniHome.footerUrl;
|
||||
|
||||
@@ -147,6 +243,102 @@ export default function HomePage() {
|
||||
imageUrl: sharePayload.imgUrl,
|
||||
}));
|
||||
|
||||
function scrollToAroma(key: AromaKey) {
|
||||
setActiveAroma(key);
|
||||
scrollingToRef.current = key;
|
||||
if (scrollLockTimerRef.current) clearTimeout(scrollLockTimerRef.current);
|
||||
scrollLockTimerRef.current = setTimeout(() => {
|
||||
scrollingToRef.current = null;
|
||||
}, 450);
|
||||
|
||||
const query = Taro.createSelectorQuery();
|
||||
query.select(`#${aromaSectionId(key)}`).boundingClientRect();
|
||||
query.selectViewport().scrollOffset();
|
||||
query.exec((res) => {
|
||||
const rect = res?.[0] as { top?: number } | undefined;
|
||||
const viewport = res?.[1] as { scrollTop?: number } | undefined;
|
||||
if (rect?.top == null || viewport?.scrollTop == null) return;
|
||||
const scrollTop = Math.max(0, viewport.scrollTop + rect.top - AROMA_NAV_OFFSET_PX);
|
||||
void Taro.pageScrollTo({ scrollTop, duration: 280 });
|
||||
});
|
||||
}
|
||||
|
||||
usePageScroll(() => {
|
||||
if (scrollingToRef.current) return;
|
||||
const now = Date.now();
|
||||
if (now - lastScrollSyncAtRef.current < 80) return;
|
||||
lastScrollSyncAtRef.current = now;
|
||||
const query = Taro.createSelectorQuery();
|
||||
AROMA_TABS.forEach((t) => {
|
||||
query.select(`#${aromaSectionId(t.key)}`).boundingClientRect();
|
||||
});
|
||||
query.exec((rects) => {
|
||||
if (!Array.isArray(rects) || rects.length === 0) return;
|
||||
let next: AromaKey = AROMA_TABS[0].key;
|
||||
for (let i = 0; i < AROMA_TABS.length; i++) {
|
||||
const rect = rects[i] as { top?: number } | null;
|
||||
if (!rect || rect.top == null) continue;
|
||||
// 区块顶进入导航下方一带时视为当前香型
|
||||
if (rect.top <= AROMA_NAV_OFFSET_PX + 24) {
|
||||
next = AROMA_TABS[i].key;
|
||||
}
|
||||
}
|
||||
setActiveAroma((prev) => (prev === next ? prev : next));
|
||||
});
|
||||
});
|
||||
|
||||
function renderProductCard(p: Product) {
|
||||
const thumb = getProductMainImage(p);
|
||||
const spec = p.subtitle || p.spec || '';
|
||||
return (
|
||||
<View key={p.id} className="home-product-card">
|
||||
<View className="home-product-card-inner" onClick={() => openProductDetail(p.id)}>
|
||||
<View className="home-product-thumb-wrap">
|
||||
{thumb ? (
|
||||
<Image className="home-product-thumb" src={thumb} mode="aspectFill" />
|
||||
) : (
|
||||
<View className="home-product-thumb home-product-thumb--empty" />
|
||||
)}
|
||||
</View>
|
||||
<View className="home-product-main">
|
||||
<View className="home-product-row">
|
||||
<Text className="home-product-name">{p.name}</Text>
|
||||
<Text className="home-product-price">¥{Number(p.price).toFixed(0)}</Text>
|
||||
</View>
|
||||
{spec ? <Text className="home-product-sub">{spec}</Text> : null}
|
||||
<View className="home-product-footer">
|
||||
<CouponBadge amount={p.benefitDisplay ?? p.price} label="好客权益" />
|
||||
</View>
|
||||
<View className="home-product-actions">
|
||||
{canPickupOnSite(p) ? (
|
||||
<Text
|
||||
className="home-pickup-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
void goOnSitePickup(p.id);
|
||||
}}
|
||||
>
|
||||
现场取货
|
||||
</Text>
|
||||
) : null}
|
||||
{canBuyOnline(p) ? (
|
||||
<Text
|
||||
className="home-buy-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
openProductDetail(p.id);
|
||||
}}
|
||||
>
|
||||
立即购买
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell variant="tab" className="home-page no-tab-header">
|
||||
<WechatShareReady payload={sharePayload} />
|
||||
@@ -175,8 +367,8 @@ export default function HomePage() {
|
||||
{AROMA_TABS.map((t) => (
|
||||
<Text
|
||||
key={t.key}
|
||||
className={`home-aroma-tab${tab === t.key ? ' home-aroma-tab--active' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
className={`home-aroma-tab${activeAroma === t.key ? ' home-aroma-tab--active' : ''}`}
|
||||
onClick={() => scrollToAroma(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</Text>
|
||||
@@ -185,64 +377,38 @@ export default function HomePage() {
|
||||
<Text className="home-aroma-city">{displayCity}</Text>
|
||||
</View>
|
||||
|
||||
<View className="home-fulfillment-filters">
|
||||
{FULFILLMENT_FILTERS.map((f) => (
|
||||
<Text
|
||||
key={f.key}
|
||||
className={`home-fulfillment-chip${fulfillmentFilter === f.key ? ' home-fulfillment-chip--active' : ''}`}
|
||||
onClick={() => setFulfillmentFilter(f.key)}
|
||||
>
|
||||
{f.label}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
|
||||
<View className="home-product-list">
|
||||
{loading ? <View className="home-empty">加载中…</View> : null}
|
||||
{!loading && products.length === 0 ? (
|
||||
<View className="home-empty">当前城市暂无在售商品</View>
|
||||
) : null}
|
||||
{!loading && products.length > 0 && filtered.length === 0 ? (
|
||||
<View className="home-empty">该香型暂未上线</View>
|
||||
{!loading && products.length > 0 && filteredProducts.length === 0 ? (
|
||||
<View className="home-empty">暂无符合履约方式的商品</View>
|
||||
) : null}
|
||||
{!loading &&
|
||||
filtered.map((p) => {
|
||||
const thumb = getProductMainImage(p);
|
||||
const spec = p.subtitle || p.spec || '';
|
||||
filteredProducts.length > 0 &&
|
||||
AROMA_TABS.map((t) => {
|
||||
const list = productsByAroma[t.key];
|
||||
return (
|
||||
<View key={p.id} className="home-product-card">
|
||||
<View
|
||||
className="home-product-card-inner"
|
||||
onClick={() => openProductDetail(p.id)}
|
||||
>
|
||||
<View className="home-product-thumb-wrap">
|
||||
{thumb ? (
|
||||
<Image className="home-product-thumb" src={thumb} mode="aspectFill" />
|
||||
) : (
|
||||
<View className="home-product-thumb home-product-thumb--empty" />
|
||||
)}
|
||||
</View>
|
||||
<View className="home-product-main">
|
||||
<View className="home-product-row">
|
||||
<Text className="home-product-name">{p.name}</Text>
|
||||
<Text className="home-product-price">¥{Number(p.price).toFixed(0)}</Text>
|
||||
</View>
|
||||
{spec ? <Text className="home-product-sub">{spec}</Text> : null}
|
||||
<View className="home-product-footer">
|
||||
<CouponBadge amount={p.benefitDisplay ?? p.price} label="好客权益" />
|
||||
</View>
|
||||
<View className="home-product-actions">
|
||||
{p.allowOnSitePickup ? (
|
||||
<Text
|
||||
className="home-pickup-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
void goOnSitePickup(p.id);
|
||||
}}
|
||||
>
|
||||
现场取货
|
||||
</Text>
|
||||
) : null}
|
||||
<Text
|
||||
className="home-buy-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
openProductDetail(p.id);
|
||||
}}
|
||||
>
|
||||
立即购买
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View key={t.key} id={aromaSectionId(t.key)} className="home-aroma-section">
|
||||
<Text className="home-aroma-section-title">{t.label}</Text>
|
||||
{list.length === 0 ? (
|
||||
<View className="home-empty home-empty--section">该香型暂未上线</View>
|
||||
) : (
|
||||
list.map((p) => renderProductCard(p))
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -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);
|
||||
@@ -221,7 +218,10 @@ export default function MinePage() {
|
||||
|
||||
/** 点击头像:绑定账号后用 chooseAvatar + nickname 获取头像昵称 */
|
||||
async function handleAvatarTap() {
|
||||
if (bindingWx || savingProfile) return;
|
||||
if (bindingWx || savingProfile) {
|
||||
toast(savingProfile ? '资料保存中…' : '请稍候…');
|
||||
return;
|
||||
}
|
||||
if (!isLoggedIn()) {
|
||||
goLogin('/pages/mine/index');
|
||||
return;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { goLogin } from '../../lib/auth-nav';
|
||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||
import { request } from '../../lib/api';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
|
||||
type PreviewProduct = {
|
||||
@@ -75,7 +75,14 @@ export default function OrderConfirmPickupPage() {
|
||||
const canSubmit = !!preview && quantityOk && !loading && !previewLoading;
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < minQty) return;
|
||||
if (next < minQty) {
|
||||
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
}
|
||||
|
||||
@@ -95,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}`;
|
||||
@@ -185,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>
|
||||
|
||||
@@ -9,7 +9,8 @@ import { tryGetClientGpsLocation } from '../../lib/client-location';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||
import { request } from '../../lib/api';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
|
||||
type Address = {
|
||||
@@ -31,6 +32,8 @@ type PreviewProduct = {
|
||||
price: number;
|
||||
mainImageUrl?: string | null;
|
||||
carouselUrls?: string[] | null;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
};
|
||||
|
||||
type OrderPreview = {
|
||||
@@ -41,12 +44,18 @@ type OrderPreview = {
|
||||
freightPayType: 'COD' | null;
|
||||
payAmount: number;
|
||||
benefitAmount: number;
|
||||
city?: { localMinQty: number; crossMinQty: number };
|
||||
city?: { name?: string; localMinQty: number; crossMinQty: number };
|
||||
quantityOk?: boolean;
|
||||
quantityMessage?: string | null;
|
||||
addressOk?: boolean;
|
||||
addressMessage?: string | null;
|
||||
minQty?: number;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
};
|
||||
|
||||
const CROSS_CITY_BLOCK_MSG = '该商品不支持跨城配送,请更换为开城城市内的收货地址';
|
||||
|
||||
function formatAddress(a: Address) {
|
||||
return `${a.province}${a.city}${a.district}${a.detail}`;
|
||||
}
|
||||
@@ -64,6 +73,7 @@ export default function OrderConfirmPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const phonePromptSkipped = useRef(false);
|
||||
const toastedAddressBlockRef = useRef('');
|
||||
|
||||
useEffect(() => {
|
||||
request<Address[]>('/user/addresses')
|
||||
@@ -94,7 +104,24 @@ export default function OrderConfirmPage() {
|
||||
.then((data) => {
|
||||
if (!cancelled) {
|
||||
setPreview(data);
|
||||
setMsg(data.quantityOk === false ? (data.quantityMessage || '') : '');
|
||||
const nextMsg =
|
||||
data.addressOk === false
|
||||
? data.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||
: data.quantityOk === false
|
||||
? data.quantityMessage || ''
|
||||
: '';
|
||||
setMsg(nextMsg);
|
||||
if (
|
||||
data.addressOk === false &&
|
||||
addressId &&
|
||||
toastedAddressBlockRef.current !== addressId
|
||||
) {
|
||||
toastedAddressBlockRef.current = addressId;
|
||||
toast(data.addressMessage || CROSS_CITY_BLOCK_MSG);
|
||||
}
|
||||
if (data.addressOk !== false) {
|
||||
toastedAddressBlockRef.current = '';
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -117,15 +144,39 @@ export default function OrderConfirmPage() {
|
||||
[addresses, addressId],
|
||||
);
|
||||
|
||||
const isCross = forceCross || preview?.deliveryType === 'CROSS_CITY';
|
||||
const allowCross =
|
||||
preview?.allowCrossCityDelivery !== undefined
|
||||
? canCrossCity({ allowCrossCityDelivery: preview.allowCrossCityDelivery })
|
||||
: canCrossCity(preview?.product ?? {});
|
||||
const localCross =
|
||||
!!selectedAddress &&
|
||||
isCrossCityAddress(selectedAddress.city, preview?.city?.name);
|
||||
const isCross =
|
||||
forceCross || preview?.deliveryType === 'CROSS_CITY' || localCross;
|
||||
const crossBlocked = isCross && !allowCross;
|
||||
const addressOk = preview ? preview.addressOk !== false && !crossBlocked : !crossBlocked;
|
||||
const minQty =
|
||||
preview?.minQty ??
|
||||
(isCross ? (preview?.city?.crossMinQty ?? 6) : (preview?.city?.localMinQty ?? 2));
|
||||
const quantityOk = preview ? preview.quantityOk !== false && quantity >= minQty : false;
|
||||
const canSubmit = !!addressId && !!preview && quantityOk && !loading && !previewLoading;
|
||||
const canSubmit =
|
||||
!!addressId && !!preview && quantityOk && addressOk && !loading && !previewLoading;
|
||||
|
||||
const addressHint = !addressOk
|
||||
? preview?.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||
: '';
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < 1) return;
|
||||
if (next < minQty) {
|
||||
const tip = isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
}
|
||||
|
||||
@@ -162,12 +213,18 @@ export default function OrderConfirmPage() {
|
||||
setMsg('请选择收货地址');
|
||||
return;
|
||||
}
|
||||
if (!addressOk) {
|
||||
const tip = addressHint || CROSS_CITY_BLOCK_MSG;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
return;
|
||||
}
|
||||
if (!quantityOk) {
|
||||
setMsg(
|
||||
isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`,
|
||||
);
|
||||
const tip = isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -219,9 +276,12 @@ export default function OrderConfirmPage() {
|
||||
? '提交中…'
|
||||
: !addressId
|
||||
? '请选择地址'
|
||||
: !quantityOk
|
||||
? `至少购买 ${minQty} 瓶`
|
||||
: '提交订单';
|
||||
: !addressOk
|
||||
? '请更换地址'
|
||||
: !quantityOk
|
||||
? `至少购买 ${minQty} 瓶`
|
||||
: '提交订单';
|
||||
const displayMsg = msg || addressHint;
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="order-confirm-page" hasFixedFooter>
|
||||
@@ -254,7 +314,13 @@ export default function OrderConfirmPage() {
|
||||
)}
|
||||
</View>
|
||||
|
||||
{isCross ? (
|
||||
{!addressOk && addressId ? (
|
||||
<View className="order-card order-card--warn">
|
||||
<Text className="order-warn-text">{addressHint || CROSS_CITY_BLOCK_MSG}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{isCross && addressOk ? (
|
||||
<View className="order-card">
|
||||
<Text className="u-muted">
|
||||
该地址超出同城配送范围,将由总部物流发货,运费到付
|
||||
@@ -286,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>
|
||||
@@ -333,9 +399,9 @@ export default function OrderConfirmPage() {
|
||||
{!previewLoading && !preview && productId ? (
|
||||
<View className="u-empty">无法加载商品信息</View>
|
||||
) : null}
|
||||
{msg ? (
|
||||
<Text className="u-muted" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
||||
{msg}
|
||||
{displayMsg ? (
|
||||
<Text className="order-warn-text" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
||||
{displayMsg}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -180,6 +180,17 @@ export default function OrderDetailPage() {
|
||||
<WechatShareReady payload={sharePayload} />
|
||||
<SubPageHeader
|
||||
title="订单详情"
|
||||
onBack={() => {
|
||||
// 支付完成后 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.navigateBack();
|
||||
}}
|
||||
right={<ShareNavButton payload={sharePayload} />}
|
||||
/>
|
||||
<View className="sub-page-body">
|
||||
|
||||
@@ -93,7 +93,14 @@ export default function OrdersPage() {
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="orders-page">
|
||||
<SubPageHeader title="我的订单" />
|
||||
<SubPageHeader
|
||||
title="我的订单"
|
||||
onBack={() => {
|
||||
Taro.switchTab({ url: '/pages/home/index' }).catch(() => {
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<View className="order-tabs">
|
||||
{TABS.map((t) => (
|
||||
<Text
|
||||
|
||||
@@ -144,10 +144,10 @@ export default function PayPage() {
|
||||
toast('支付成功', 'success');
|
||||
}
|
||||
if (deliveryType === 'ON_SITE_PICKUP') {
|
||||
// 现场提货支付即完成 → 订单详情(已完成)
|
||||
Taro.redirectTo({ url: `/pages/order-detail/index?id=${orderId}` });
|
||||
// 现场提货支付即完成 → 订单详情;from=pay 返回强制回首页,避免 navigateBack 退出小程序
|
||||
Taro.reLaunch({ url: `/pages/order-detail/index?id=${orderId}&from=pay` });
|
||||
} else {
|
||||
Taro.redirectTo({ url: '/pages/orders/index?tab=paid' });
|
||||
Taro.reLaunch({ url: '/pages/orders/index?tab=paid&from=pay' });
|
||||
}
|
||||
} catch (e) {
|
||||
if (isWechatAuthRequiredError(e)) {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { usePageScroll, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
usePageScroll,
|
||||
useRouter,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import type { ProductDetailContentDto } from '@dukang/shared-types';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import PageNavBar from '../../components/PageNavBar';
|
||||
@@ -16,6 +22,11 @@ import {
|
||||
getProductMainImage,
|
||||
type ProductImageSource,
|
||||
} from '../../lib/product-images';
|
||||
import {
|
||||
canBuyOnline,
|
||||
canPickupOnSite,
|
||||
normalizeFulfillmentFlags,
|
||||
} from '../../lib/product-fulfillment';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -31,6 +42,9 @@ type Product = ProductImageSource & {
|
||||
benefitAmount?: number;
|
||||
benefitDisplay?: number;
|
||||
detailContent?: ProductDetailContentDto | null;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
};
|
||||
|
||||
export default function ProductDetailPage() {
|
||||
@@ -43,13 +57,32 @@ export default function ProductDetailPage() {
|
||||
setHeaderSolid(scrollTop > 100);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const loadProduct = useCallback(() => {
|
||||
if (!productId) return;
|
||||
request<Product>(`/catalog/products/${productId}`)
|
||||
.then(setProduct)
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
request<Product | null>(`/catalog/products/${productId}`)
|
||||
.then((p) => {
|
||||
if (!p) {
|
||||
setProduct(null);
|
||||
toast('商品不存在或暂未开放');
|
||||
return;
|
||||
}
|
||||
setProduct(normalizeFulfillmentFlags(p));
|
||||
})
|
||||
.catch((e) => {
|
||||
setProduct(null);
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
});
|
||||
}, [productId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProduct();
|
||||
}, [loadProduct]);
|
||||
|
||||
// 登录后返回详情须带 token 重拉,否则白名单商品会一直空白
|
||||
useDidShow(() => {
|
||||
loadProduct();
|
||||
});
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => ({
|
||||
title: product?.name || DEFAULT_SHARE_TITLE,
|
||||
@@ -92,6 +125,18 @@ export default function ProductDetailPage() {
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
async function goOnSitePickup() {
|
||||
if (!productId) return;
|
||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=1`;
|
||||
if (!isLoggedIn()) {
|
||||
goLogin(returnPath);
|
||||
return;
|
||||
}
|
||||
const ready = await ensurePayReady(returnPath);
|
||||
if (!ready) return;
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
if (!product) {
|
||||
return (
|
||||
<PageShell variant="scroll" className="product-detail-page">
|
||||
@@ -101,6 +146,8 @@ export default function ProductDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const allowOnline = canBuyOnline(product);
|
||||
const allowOnSite = canPickupOnSite(product);
|
||||
const benefit = Number(product.benefitDisplay ?? product.benefitAmount ?? product.price);
|
||||
const carouselImages = getProductCarouselImages(product);
|
||||
const detailImages = getProductDetailImages(product);
|
||||
@@ -199,9 +246,21 @@ export default function ProductDetailPage() {
|
||||
<Image className="product-detail-bar-home-icon" src={iconHome} mode="aspectFit" />
|
||||
<Text className="product-detail-bar-home-label">首页</Text>
|
||||
</View>
|
||||
<View className="product-detail-buy-btn" onClick={() => void goBuy()}>
|
||||
<Text className="product-detail-buy-btn-text">立即购买</Text>
|
||||
</View>
|
||||
{allowOnSite ? (
|
||||
<View className="product-detail-pickup-btn" onClick={() => void goOnSitePickup()}>
|
||||
<Text className="product-detail-pickup-btn-text">现场取货</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{allowOnline ? (
|
||||
<View className="product-detail-buy-btn" onClick={() => void goBuy()}>
|
||||
<Text className="product-detail-buy-btn-text">立即购买</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{!allowOnline && !allowOnSite ? (
|
||||
<View className="product-detail-buy-btn product-detail-buy-btn--disabled">
|
||||
<Text className="product-detail-buy-btn-text">暂不可购</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</PageShell>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
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';
|
||||
|
||||
@@ -15,12 +18,43 @@ 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({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (score: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="redeem-rating-row">
|
||||
<Text className="redeem-rating-label">{label}</Text>
|
||||
<View className="redeem-star-row">
|
||||
{[1, 2, 3, 4, 5].map((score) => (
|
||||
<Text
|
||||
key={score}
|
||||
className={`redeem-star-btn${score <= value ? ' redeem-star-btn--active' : ''}`}
|
||||
onClick={() => onChange(score)}
|
||||
>
|
||||
★
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RedeemSuccessPage() {
|
||||
const router = useRouter();
|
||||
const [serviceScore, setServiceScore] = useState(5);
|
||||
const [envScore, setEnvScore] = useState(5);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const record = useMemo<RedeemRecord | null>(() => {
|
||||
try {
|
||||
@@ -34,18 +68,51 @@ 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 {
|
||||
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function goBenefit() {
|
||||
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
||||
clearCache();
|
||||
Taro.switchTab({ url: '/pages/benefit/index' });
|
||||
}
|
||||
|
||||
function goHome() {
|
||||
clearCache();
|
||||
Taro.switchTab({ url: '/pages/home/index' });
|
||||
}
|
||||
|
||||
async function submitRatingAndFinish() {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (record?.id) {
|
||||
await request('/redeem/ratings', {
|
||||
method: 'POST',
|
||||
data: {
|
||||
redeemRecordId: record.id,
|
||||
serviceScore,
|
||||
envScore,
|
||||
},
|
||||
});
|
||||
toast('评价已提交', 'success');
|
||||
}
|
||||
} catch {
|
||||
/* 评价失败不阻塞返回 */
|
||||
} finally {
|
||||
setLoading(false);
|
||||
goBenefit();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="redeem-success-page">
|
||||
<SubPageHeader title="核销成功" />
|
||||
<SubPageHeader title="核销成功" onBack={goBenefit} />
|
||||
<View className="sub-page-body">
|
||||
<View className="redeem-success-icon">
|
||||
<Text>✓</Text>
|
||||
@@ -69,14 +136,21 @@ export default function RedeemSuccessPage() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="redeem-submit" onClick={goBenefit}>
|
||||
<Text>返回权益</Text>
|
||||
<View className="redeem-success-rating">
|
||||
<Text className="redeem-success-rating-title">为门店服务评分</Text>
|
||||
<StarRating label="服务态度" value={serviceScore} onChange={setServiceScore} />
|
||||
<StarRating label="用餐环境" value={envScore} onChange={setEnvScore} />
|
||||
</View>
|
||||
|
||||
<View
|
||||
className="u-btn u-btn--ghost u-btn--block"
|
||||
style={{ margin: '0 20px', boxSizing: 'border-box' }}
|
||||
onClick={() => Taro.switchTab({ url: '/pages/home/index' })}
|
||||
className={`redeem-submit${loading ? ' redeem-submit--disabled' : ''}`}
|
||||
onClick={() => {
|
||||
if (!loading) void submitRatingAndFinish();
|
||||
}}
|
||||
>
|
||||
<Text>{loading ? '提交中…' : '提交评价并返回'}</Text>
|
||||
</View>
|
||||
<View className="redeem-cancel-btn" onClick={goHome}>
|
||||
<Text>回到首页</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -103,6 +103,30 @@
|
||||
border-bottom-color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.home-fulfillment-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px var(--space-page) 2px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.home-fulfillment-chip {
|
||||
flex-shrink: 0;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--color-subtle-gray);
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.home-fulfillment-chip--active {
|
||||
color: var(--color-heritage-red);
|
||||
background: rgba(179, 38, 30, 0.1);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.home-product-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -110,6 +134,32 @@
|
||||
padding: 8px var(--space-page) 12px;
|
||||
}
|
||||
|
||||
.home-aroma-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
scroll-margin-top: 48px;
|
||||
}
|
||||
|
||||
.home-aroma-section + .home-aroma-section {
|
||||
margin-top: 8px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.home-aroma-section-title {
|
||||
font-family: var(--font-headline);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 22px;
|
||||
color: var(--color-on-surface);
|
||||
padding: 2px 2px 0;
|
||||
}
|
||||
|
||||
.home-empty--section {
|
||||
padding: 16px 0 8px;
|
||||
}
|
||||
|
||||
.home-product-card {
|
||||
background: var(--color-card);
|
||||
border-radius: 12px;
|
||||
|
||||
@@ -10,9 +10,10 @@
|
||||
|
||||
.mine-header {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
padding: 16px var(--space-page) 44px;
|
||||
background: linear-gradient(135deg, #820012 0%, var(--color-heritage-red) 40%, #d4a373 100%);
|
||||
overflow: hidden;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.mine-header-texture {
|
||||
@@ -33,11 +34,12 @@
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
z-index: 1;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.mine-avatar-wrap {
|
||||
position: relative;
|
||||
z-index: 4;
|
||||
flex-shrink: 0;
|
||||
margin-right: 12px;
|
||||
}
|
||||
@@ -160,7 +162,7 @@
|
||||
.mine-main {
|
||||
margin-top: -28px;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
z-index: 1;
|
||||
padding: 0 var(--space-page) 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -81,6 +81,19 @@
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.order-card--warn {
|
||||
background: rgba(166, 29, 36, 0.06);
|
||||
box-shadow: none;
|
||||
border: 1px solid rgba(166, 29, 36, 0.15);
|
||||
}
|
||||
|
||||
.order-warn-text {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-card-title {
|
||||
display: block;
|
||||
font-family: var(--font-headline);
|
||||
|
||||
@@ -301,6 +301,25 @@
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.product-detail-pickup-btn {
|
||||
flex: 1;
|
||||
height: 48px;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-heritage-red);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.product-detail-pickup-btn-text {
|
||||
color: var(--color-heritage-red);
|
||||
font-family: var(--font-headline);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.product-detail-buy-btn {
|
||||
flex: 1;
|
||||
height: 48px;
|
||||
@@ -312,6 +331,12 @@
|
||||
box-shadow: 0 8px 24px rgba(166, 29, 36, 0.2);
|
||||
}
|
||||
|
||||
.product-detail-buy-btn--disabled {
|
||||
background: #c4c4c4;
|
||||
box-shadow: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.product-detail-buy-btn-text {
|
||||
color: #fff;
|
||||
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 {
|
||||
@@ -378,6 +388,49 @@
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.redeem-success-rating {
|
||||
margin: 16px var(--space-page) 0;
|
||||
padding: 16px;
|
||||
background: var(--color-card);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.redeem-success-rating-title {
|
||||
display: block;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--color-on-surface);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.redeem-rating-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.redeem-rating-label {
|
||||
font-size: 14px;
|
||||
color: var(--color-on-surface);
|
||||
}
|
||||
|
||||
.redeem-star-row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.redeem-star-btn {
|
||||
font-size: 22px;
|
||||
color: #d0d0d0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.redeem-star-btn--active {
|
||||
color: #f5a623;
|
||||
}
|
||||
|
||||
.ledger-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-1
@@ -169,10 +169,11 @@ git fetch "\$GIT_REMOTE"
|
||||
git checkout "\$GIT_BRANCH"
|
||||
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
|
||||
|
||||
# 无额外参数时执行 DB 同步;无 schema 变更请显式传 -- --skip-db
|
||||
if [[ -n "\$RELEASE_ARGS" ]]; then
|
||||
bash deploy/remote-release.sh \$RELEASE_ARGS
|
||||
else
|
||||
bash deploy/remote-release.sh --skip-db
|
||||
bash deploy/remote-release.sh
|
||||
fi
|
||||
EOF
|
||||
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -27,6 +27,10 @@ export interface ProductDto {
|
||||
detailContent?: ProductDetailContentDto | null;
|
||||
/** 是否允许现场取货下单 */
|
||||
allowOnSitePickup?: boolean;
|
||||
/** 是否允许配送到址(同城线上购买) */
|
||||
allowOnlinePurchase?: boolean;
|
||||
/** 是否允许跨城配送 */
|
||||
allowCrossCityDelivery?: boolean;
|
||||
}
|
||||
|
||||
export interface ProductDetailFeatureDto {
|
||||
|
||||
@@ -55,7 +55,7 @@ export const MINI_USER_STATIC_OSS_BASE =
|
||||
export const QUALIFICATION_DISCLOSURE_URL = `${MINI_USER_STATIC_OSS_BASE}qualification-disclosure.png`;
|
||||
|
||||
/** 总部客服电话(C 端联系客服) */
|
||||
export const CUSTOMER_SERVICE_PHONE = '400-888-1234';
|
||||
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
||||
|
||||
/**
|
||||
* 企业微信「微信客服」链接(C 端「在线客服」;微信内网页点击后进入原生客服会话)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -85,6 +85,8 @@ export type PartnerProxyOrderProductOption = {
|
||||
benefitAmount: number | null;
|
||||
coverUrl?: string | null;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
};
|
||||
|
||||
export type PartnerProxyOrderPromoOption = {
|
||||
|
||||
@@ -70,7 +70,7 @@ export function createWeixinSdk(config: WeixinSdkConfig) {
|
||||
getPhoneNumber: () => getWechatPhoneNumber(config),
|
||||
getLocation: () => getWechatLocation(config),
|
||||
getLocationDetailed: () => getWechatLocationDetailed(config),
|
||||
scanQrCode: () => scanQrCode(config),
|
||||
scanQrCode: (options?: Parameters<typeof scanQrCode>[1]) => scanQrCode(config, options),
|
||||
chooseImages: (options?: Parameters<typeof chooseWechatImages>[1]) =>
|
||||
chooseWechatImages(config, options),
|
||||
pay: (prepay: Parameters<typeof invokeWechatPay>[0]) =>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { getRuntimePlatform, isIosDevice, isWechatDevTools } from './env';
|
||||
import { ensureJssdkReady } from './jssdk';
|
||||
import {
|
||||
ensureJssdkReady,
|
||||
getJssdkSignUrl,
|
||||
initWechatJssdk,
|
||||
resetJssdkConfig,
|
||||
} from './jssdk';
|
||||
import type { WeixinSdkConfig } from './types';
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
@@ -11,7 +16,7 @@ export function formatScanFailMessage(errMsg: string): string {
|
||||
const msg = errMsg.trim() || '扫码失败';
|
||||
if (/cancel/i.test(msg)) return '';
|
||||
|
||||
// iOS 常见:JSSDK 权限离线校验尚未完成,并非系统相机权限
|
||||
// iOS / 授权回调后常见:JSSDK 权限离线校验尚未完成,并非系统相机权限
|
||||
if (/offline verifying|permission value is offline/i.test(msg)) {
|
||||
return '微信权限验证中,请稍候再试或刷新页面后重新扫码';
|
||||
}
|
||||
@@ -33,6 +38,47 @@ export function formatScanFailMessage(errMsg: string): string {
|
||||
return msg;
|
||||
}
|
||||
|
||||
function isScanPermissionWarmupError(msg: string): boolean {
|
||||
return /offline verifying|permission value is offline|权限验证中|接口未就绪|invalid signature|config:fail|signature/i.test(
|
||||
msg,
|
||||
);
|
||||
}
|
||||
|
||||
function checkJsApi(apiName: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
if (!window.wx?.checkJsApi) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
window.wx.checkJsApi({
|
||||
jsApiList: [apiName],
|
||||
success: (res) => resolve(!!res.checkResult?.[apiName]),
|
||||
fail: () => resolve(false),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureScanJssdk(config: WeixinSdkConfig): Promise<void> {
|
||||
const jssdkOptions = {
|
||||
apiBase: config.apiBase ?? '/api/v1',
|
||||
clientApp: config.clientApp,
|
||||
getAccessToken: config.getAccessToken,
|
||||
jsApiList: ['scanQRCode', 'checkJsApi'],
|
||||
};
|
||||
|
||||
await ensureJssdkReady(jssdkOptions);
|
||||
|
||||
let ready = await checkJsApi('scanQRCode');
|
||||
if (!ready) {
|
||||
resetJssdkConfig();
|
||||
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
||||
ready = await checkJsApi('scanQRCode');
|
||||
}
|
||||
if (!ready) {
|
||||
throw new Error('微信扫码接口未授权,请刷新页面后重试');
|
||||
}
|
||||
}
|
||||
|
||||
function invokeScanQrCode(): Promise<string | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
window.wx!.scanQRCode!({
|
||||
@@ -52,8 +98,16 @@ function invokeScanQrCode(): Promise<string | null> {
|
||||
});
|
||||
}
|
||||
|
||||
/** 调起扫码(返回二维码/条码内容,失败返回 null) */
|
||||
export async function scanQrCode(config: WeixinSdkConfig): Promise<string | null> {
|
||||
export type ScanQrCodeOptions = {
|
||||
/** OAuth / 首次绑定后权限离线校验更慢,加长预热 */
|
||||
postAuthWarmup?: boolean;
|
||||
};
|
||||
|
||||
/** 调起扫码(返回二维码/条码内容,取消返回 null) */
|
||||
export async function scanQrCode(
|
||||
config: WeixinSdkConfig,
|
||||
options: ScanQrCodeOptions = {},
|
||||
): Promise<string | null> {
|
||||
const platform = getRuntimePlatform();
|
||||
|
||||
if (platform === 'mini' && window.wx?.scanCode) {
|
||||
@@ -68,32 +122,42 @@ export async function scanQrCode(config: WeixinSdkConfig): Promise<string | null
|
||||
}
|
||||
|
||||
if (platform === 'wechat-h5') {
|
||||
await ensureJssdkReady({
|
||||
const jssdkOptions = {
|
||||
apiBase: config.apiBase ?? '/api/v1',
|
||||
clientApp: config.clientApp,
|
||||
getAccessToken: config.getAccessToken,
|
||||
});
|
||||
jsApiList: ['scanQRCode', 'checkJsApi'],
|
||||
};
|
||||
|
||||
await ensureScanJssdk(config);
|
||||
if (!window.wx?.scanQRCode) {
|
||||
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
||||
}
|
||||
|
||||
// iOS 在 wx.ready 后立即调 scanQRCode 可能触发 offline verifying
|
||||
if (isIosDevice() && !isWechatDevTools()) {
|
||||
await delay(500);
|
||||
}
|
||||
// wx.ready ≠ 权限离线校验完成;授权回跳后更明显
|
||||
const warmupMs = options.postAuthWarmup
|
||||
? 1200
|
||||
: isIosDevice() && !isWechatDevTools()
|
||||
? 800
|
||||
: 300;
|
||||
await delay(warmupMs);
|
||||
|
||||
const maxAttempts = 2;
|
||||
const maxAttempts = options.postAuthWarmup ? 3 : 2;
|
||||
let lastError: Error | null = null;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (attempt > 0) {
|
||||
await delay(800);
|
||||
if (lastError && isScanPermissionWarmupError(lastError.message)) {
|
||||
resetJssdkConfig();
|
||||
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
||||
await checkJsApi('scanQRCode');
|
||||
}
|
||||
await delay(700 + attempt * 500);
|
||||
}
|
||||
try {
|
||||
return await invokeScanQrCode();
|
||||
} catch (e) {
|
||||
lastError = e instanceof Error ? e : new Error('扫码失败');
|
||||
const raw = lastError.message;
|
||||
const retryable = /offline verifying|权限验证中|接口未就绪/i.test(raw);
|
||||
const retryable = isScanPermissionWarmupError(lastError.message);
|
||||
if (attempt < maxAttempts - 1 && retryable) continue;
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
+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
|
||||
@@ -593,6 +605,10 @@ model CommonProductItem {
|
||||
status ProductStatus @default(DRAFT)
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
allowOnSitePickup Boolean @default(false) @map("allow_on_site_pickup")
|
||||
/// 允许配送到址(同城线上购买)
|
||||
allowOnlinePurchase Boolean @default(true) @map("allow_online_purchase")
|
||||
/// 允许跨城配送(依附线上购买)
|
||||
allowCrossCityDelivery Boolean @default(true) @map("allow_cross_city_delivery")
|
||||
/// Online test: only listed phones can see/buy when enabled
|
||||
visibilityWhitelistEnabled Boolean @default(false) @map("visibility_whitelist_enabled")
|
||||
coverResourceId BigInt? @map("cover_resource_id") @db.UnsignedBigInt
|
||||
@@ -1058,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)
|
||||
|
||||
@@ -1071,6 +1091,8 @@ model Store {
|
||||
ratings StoreRating[]
|
||||
payouts StorePayout[]
|
||||
storeBills StoreBill[]
|
||||
withdrawRequests StoreWithdrawRequest[]
|
||||
visibilityPhones StoreVisibilityPhone[]
|
||||
|
||||
@@index([cityId, status])
|
||||
@@index([partnerAccountId])
|
||||
@@ -1078,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)
|
||||
@@ -1100,6 +1136,7 @@ model StoreAccount {
|
||||
childAccounts StoreAccount[] @relation("StoreAccountHierarchy")
|
||||
bindings StoreAccountStore[]
|
||||
redeemPendingRecords RedeemPendingRecord[]
|
||||
withdrawRequests StoreWithdrawRequest[]
|
||||
|
||||
@@index([parentAccountId])
|
||||
@@map("store_account")
|
||||
@@ -1287,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)
|
||||
@@ -1305,6 +1344,7 @@ model RedeemRecord {
|
||||
allocations RedeemRecordAllocation[]
|
||||
|
||||
@@index([storeId, createdAt])
|
||||
@@index([storeId, channel, createdAt])
|
||||
@@map("user_redeem_record")
|
||||
}
|
||||
|
||||
@@ -1411,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)
|
||||
|
||||
@@ -7,6 +7,15 @@ import { JwtService } from '@nestjs/jwt';
|
||||
import { CLIENT_APP_ACTOR_MAP, ClientApp } from '@dukang/shared-types';
|
||||
import type { AuthUser } from './jwt-auth.guard';
|
||||
|
||||
/** C 端 H5 / 小程序同属 USER,目录白名单只认 actorId→手机号,允许端间 token 兼容 */
|
||||
const USER_CLIENT_APPS = new Set<ClientApp>([ClientApp.USER_MINI, ClientApp.USER_H5]);
|
||||
|
||||
function clientAppCompatible(headerApp: ClientApp | undefined, payloadApp: unknown): boolean {
|
||||
if (!headerApp || payloadApp == null) return false;
|
||||
if (headerApp === payloadApp) return true;
|
||||
return USER_CLIENT_APPS.has(headerApp) && USER_CLIENT_APPS.has(payloadApp as ClientApp);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OptionalJwtAuthGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
@@ -20,7 +29,7 @@ export class OptionalJwtAuthGuard implements CanActivate {
|
||||
try {
|
||||
const payload = this.jwtService.verify(auth.slice(7));
|
||||
const clientApp = req.headers['x-client-app'] as ClientApp;
|
||||
if (!clientApp || payload.clientApp !== clientApp) return true;
|
||||
if (!clientAppCompatible(clientApp, payload.clientApp)) return true;
|
||||
const expectedActor = CLIENT_APP_ACTOR_MAP[clientApp];
|
||||
if (payload.actorType !== expectedActor) return true;
|
||||
req.user = {
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -119,7 +119,29 @@ export class BenefitService {
|
||||
where: benefitLedgerWhere(userId, couponId),
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
return serializeBigInt(list);
|
||||
return serializeBigInt(
|
||||
list.map((e) => {
|
||||
const type = e.param1 || '';
|
||||
const amount = Number(e.amount1 ?? 0);
|
||||
const title =
|
||||
e.remark ||
|
||||
(type === 'REDEEM'
|
||||
? '门店核销'
|
||||
: type === 'GRANT'
|
||||
? '购酒入账'
|
||||
: type === 'REFUND_VOID'
|
||||
? '退款作废'
|
||||
: '权益变动');
|
||||
return {
|
||||
id: e.id,
|
||||
type,
|
||||
amount,
|
||||
title,
|
||||
createdAt: e.createdAt,
|
||||
balanceAfter: e.amount2 != null ? Number(e.amount2) : null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async getCoupon(userId: bigint, couponId: bigint) {
|
||||
|
||||
@@ -81,11 +81,9 @@ export class CatalogService {
|
||||
return serializeBigInt(
|
||||
visible.map((p) => {
|
||||
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
||||
const { visibilityPhones, ...rest } = p;
|
||||
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = p;
|
||||
return {
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: p.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||
benefitAmount: p.benefitAmount ?? p.price,
|
||||
price: Number(p.price),
|
||||
benefitDisplay: Number(p.benefitAmount ?? p.price),
|
||||
@@ -119,11 +117,9 @@ export class CatalogService {
|
||||
});
|
||||
|
||||
const media = mapProductMedia(product, resources);
|
||||
const { visibilityPhones, ...rest } = product;
|
||||
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = product;
|
||||
return serializeBigInt({
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: product.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||
benefitAmount: product.benefitAmount ?? product.price,
|
||||
price: Number(product.price),
|
||||
...media,
|
||||
|
||||
@@ -23,6 +23,14 @@ export class ClientErrorService {
|
||||
const stack = dto.stack?.trim().slice(0, 4000);
|
||||
const pagePath = dto.pagePath?.trim().slice(0, 128);
|
||||
const fingerprint = `${dto.level}|${dto.category}|${message.slice(0, 120)}`;
|
||||
const anonymous = user?.actorId == null;
|
||||
const skipWecom = shouldSkipWecomClientErrorAlert({
|
||||
message,
|
||||
pagePath,
|
||||
clientApp,
|
||||
anonymous,
|
||||
category: dto.category,
|
||||
});
|
||||
|
||||
const logLine = {
|
||||
level: dto.level,
|
||||
@@ -34,6 +42,7 @@ export class ClientErrorService {
|
||||
actorId: user?.actorId != null ? String(user.actorId) : undefined,
|
||||
stack: stack?.slice(0, 800),
|
||||
extra: dto.extra,
|
||||
skipWecom,
|
||||
};
|
||||
|
||||
if (dto.level === 'fatal') {
|
||||
@@ -61,6 +70,7 @@ export class ClientErrorService {
|
||||
actorType: user?.actorType ?? null,
|
||||
actorId: user?.actorId != null ? String(user.actorId) : null,
|
||||
storeId: user?.storeId != null ? String(user.storeId) : null,
|
||||
skipWecom,
|
||||
...(dto.extra && typeof dto.extra === 'object' ? { clientExtra: dto.extra } : {}),
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
@@ -71,7 +81,7 @@ export class ClientErrorService {
|
||||
);
|
||||
}
|
||||
|
||||
if (WECOM_LEVELS.has(dto.level)) {
|
||||
if (WECOM_LEVELS.has(dto.level) && !skipWecom) {
|
||||
const alertLevel: AlertLevel = dto.level === 'fatal' ? 'P0' : 'P1';
|
||||
this.alert.notify({
|
||||
level: alertLevel,
|
||||
@@ -91,12 +101,56 @@ export class ClientErrorService {
|
||||
dedupeKey: `client_error|${fingerprint}`,
|
||||
dedupeTtlSec: 600,
|
||||
});
|
||||
} else if (skipWecom && WECOM_LEVELS.has(dto.level)) {
|
||||
this.logger.log(
|
||||
`[client_error] skip WeCom alert (likely mini-program audit noise): ${message.slice(0, 160)}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤企微推送:微信小程序审核机 / 自动化探测常见噪声。
|
||||
* 仍落库与写服务端日志,仅跳过 webhook。
|
||||
*
|
||||
* 典型特征(与本次协议页报错一致):
|
||||
* - 匿名 USER_MINI
|
||||
* - navigateTo/redirectTo 等 page … is not found(常带 .html,Taro H5 路径形态)
|
||||
*/
|
||||
export function shouldSkipWecomClientErrorAlert(input: {
|
||||
message: string;
|
||||
pagePath?: string | null;
|
||||
clientApp: string;
|
||||
anonymous: boolean;
|
||||
category?: string;
|
||||
}): boolean {
|
||||
const msg = input.message || '';
|
||||
const app = input.clientApp || '';
|
||||
const isMini = app === 'USER_MINI' || app === 'PARTNER_MINI' || app === 'HQ_MINI';
|
||||
|
||||
// 路由页不存在:审核机点协议/隐私链接触发最常见
|
||||
const isNavPageMissing =
|
||||
/(navigateTo|redirectTo|reLaunch|switchTab):fail/i.test(msg) &&
|
||||
/is not found/i.test(msg);
|
||||
|
||||
// Taro 把路径拼成 *.html 的形态,几乎不可能是真·原生页路径
|
||||
const isTaroHtmlPagePath =
|
||||
/\.html(\b|"|')/i.test(msg) && /is not found|page /i.test(msg);
|
||||
|
||||
if (isMini && input.anonymous && (isNavPageMissing || isTaroHtmlPagePath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 即使带登录态,纯 *.html not found 也视为框架/探测噪声
|
||||
if (isMini && isTaroHtmlPagePath) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isClientApp(v: string): v is ClientApp {
|
||||
return [
|
||||
'USER_MINI',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -24,6 +24,37 @@ function normalizePhones(phones?: string[]): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
const SKU_AUTO_PREFIX = 'DK';
|
||||
const SKU_AUTO_PAD = 6;
|
||||
|
||||
/** 解析履约开关:无线上则强制不可跨城;须至少线上或现场之一 */
|
||||
function resolveFulfillmentFlags(input: {
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
allowOnSitePickup?: boolean;
|
||||
defaults?: {
|
||||
allowOnlinePurchase: boolean;
|
||||
allowCrossCityDelivery: boolean;
|
||||
allowOnSitePickup: boolean;
|
||||
};
|
||||
}) {
|
||||
const d = input.defaults ?? {
|
||||
allowOnlinePurchase: true,
|
||||
allowCrossCityDelivery: true,
|
||||
allowOnSitePickup: false,
|
||||
};
|
||||
const allowOnlinePurchase = input.allowOnlinePurchase ?? d.allowOnlinePurchase;
|
||||
const allowOnSitePickup = input.allowOnSitePickup ?? d.allowOnSitePickup;
|
||||
let allowCrossCityDelivery = input.allowCrossCityDelivery ?? d.allowCrossCityDelivery;
|
||||
if (!allowOnlinePurchase) {
|
||||
allowCrossCityDelivery = false;
|
||||
}
|
||||
if (!allowOnlinePurchase && !allowOnSitePickup) {
|
||||
throw new BadRequestException('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||
}
|
||||
return { allowOnlinePurchase, allowCrossCityDelivery, allowOnSitePickup };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminProductsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -96,39 +127,44 @@ export class AdminProductsService {
|
||||
}
|
||||
|
||||
async create(dto: CreateProductDto) {
|
||||
const exists = await this.prisma.commonProductItem.findFirst({
|
||||
where: { OR: [{ skuCode: dto.skuCode }, { barcode69: dto.barcode69 }] },
|
||||
const barcodeExists = await this.prisma.commonProductItem.findFirst({
|
||||
where: { barcode69: dto.barcode69 },
|
||||
});
|
||||
if (barcodeExists) throw new BadRequestException('69 码已存在');
|
||||
|
||||
const flags = resolveFulfillmentFlags({
|
||||
allowOnlinePurchase: dto.allowOnlinePurchase,
|
||||
allowCrossCityDelivery: dto.allowCrossCityDelivery,
|
||||
allowOnSitePickup: dto.allowOnSitePickup,
|
||||
});
|
||||
if (exists) throw new BadRequestException('SKU 或 69 码已存在');
|
||||
|
||||
const phones = normalizePhones(dto.visibilityPhones);
|
||||
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
||||
|
||||
const product = await this.prisma.commonProductItem.create({
|
||||
data: {
|
||||
skuCode: dto.skuCode,
|
||||
barcode69: dto.barcode69,
|
||||
name: dto.name,
|
||||
subtitle: dto.subtitle,
|
||||
aromaType: dto.aromaType as 'QINGXIANG' | 'JIANGXIANG' | 'NONGXIANG',
|
||||
spec: dto.spec,
|
||||
price: dto.price,
|
||||
benefitAmount: dto.benefitAmount ?? dto.price,
|
||||
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
||||
sortOrder: dto.sortOrder ?? 0,
|
||||
allowOnSitePickup: dto.allowOnSitePickup ?? false,
|
||||
visibilityWhitelistEnabled: whitelistEnabled,
|
||||
...(dto.detailContent !== undefined
|
||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(phones.length
|
||||
? {
|
||||
visibilityPhones: {
|
||||
create: phones.map((phone) => ({ phone })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
const product = await this.createWithGeneratedSku({
|
||||
barcode69: dto.barcode69,
|
||||
name: dto.name,
|
||||
subtitle: dto.subtitle,
|
||||
aromaType: dto.aromaType as 'QINGXIANG' | 'JIANGXIANG' | 'NONGXIANG',
|
||||
spec: dto.spec,
|
||||
price: dto.price,
|
||||
benefitAmount: dto.benefitAmount ?? dto.price,
|
||||
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
||||
sortOrder: dto.sortOrder ?? 0,
|
||||
allowOnSitePickup: flags.allowOnSitePickup,
|
||||
allowOnlinePurchase: flags.allowOnlinePurchase,
|
||||
allowCrossCityDelivery: flags.allowCrossCityDelivery,
|
||||
visibilityWhitelistEnabled: whitelistEnabled,
|
||||
...(dto.detailContent !== undefined
|
||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(phones.length
|
||||
? {
|
||||
visibilityPhones: {
|
||||
create: phones.map((phone) => ({ phone })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
if (dto.coverUrl) {
|
||||
@@ -143,7 +179,26 @@ export class AdminProductsService {
|
||||
}
|
||||
|
||||
async update(id: bigint, dto: UpdateProductDto) {
|
||||
await this.detail(id);
|
||||
const existing = await this.prisma.commonProductItem.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('商品不存在');
|
||||
|
||||
const fulfillmentTouched =
|
||||
dto.allowOnlinePurchase !== undefined ||
|
||||
dto.allowCrossCityDelivery !== undefined ||
|
||||
dto.allowOnSitePickup !== undefined;
|
||||
const flags = fulfillmentTouched
|
||||
? resolveFulfillmentFlags({
|
||||
allowOnlinePurchase: dto.allowOnlinePurchase,
|
||||
allowCrossCityDelivery: dto.allowCrossCityDelivery,
|
||||
allowOnSitePickup: dto.allowOnSitePickup,
|
||||
defaults: {
|
||||
allowOnlinePurchase: existing.allowOnlinePurchase,
|
||||
allowCrossCityDelivery: existing.allowCrossCityDelivery,
|
||||
allowOnSitePickup: existing.allowOnSitePickup,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
|
||||
await this.prisma.commonProductItem.update({
|
||||
where: { id },
|
||||
data: {
|
||||
@@ -154,7 +209,13 @@ export class AdminProductsService {
|
||||
...(dto.benefitAmount !== undefined ? { benefitAmount: dto.benefitAmount } : {}),
|
||||
...(dto.status !== undefined ? { status: dto.status as 'DRAFT' | 'ON_SALE' | 'OFF_SALE' } : {}),
|
||||
...(dto.sortOrder !== undefined ? { sortOrder: dto.sortOrder } : {}),
|
||||
...(dto.allowOnSitePickup !== undefined ? { allowOnSitePickup: dto.allowOnSitePickup } : {}),
|
||||
...(flags
|
||||
? {
|
||||
allowOnSitePickup: flags.allowOnSitePickup,
|
||||
allowOnlinePurchase: flags.allowOnlinePurchase,
|
||||
allowCrossCityDelivery: flags.allowCrossCityDelivery,
|
||||
}
|
||||
: {}),
|
||||
...(dto.visibilityWhitelistEnabled !== undefined
|
||||
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||
: {}),
|
||||
@@ -196,6 +257,46 @@ export class AdminProductsService {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** 生成 DK + 6 位自增 SKU,冲突重试 */
|
||||
private async nextAutoSkuCode(): Promise<string> {
|
||||
const rows = await this.prisma.commonProductItem.findMany({
|
||||
where: { skuCode: { startsWith: SKU_AUTO_PREFIX } },
|
||||
select: { skuCode: true },
|
||||
});
|
||||
let maxSeq = 0;
|
||||
const re = new RegExp(`^${SKU_AUTO_PREFIX}(\\d+)$`);
|
||||
for (const row of rows) {
|
||||
const m = re.exec(row.skuCode);
|
||||
if (!m) continue;
|
||||
const n = Number(m[1]);
|
||||
if (Number.isFinite(n) && n > maxSeq) maxSeq = n;
|
||||
}
|
||||
return `${SKU_AUTO_PREFIX}${String(maxSeq + 1).padStart(SKU_AUTO_PAD, '0')}`;
|
||||
}
|
||||
|
||||
private async createWithGeneratedSku(
|
||||
data: Omit<Prisma.CommonProductItemCreateInput, 'skuCode'>,
|
||||
) {
|
||||
for (let attempt = 0; attempt < 8; attempt++) {
|
||||
const skuCode = await this.nextAutoSkuCode();
|
||||
try {
|
||||
return await this.prisma.commonProductItem.create({
|
||||
data: { ...data, skuCode },
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
|
||||
const target = err.meta?.target;
|
||||
const fields = Array.isArray(target) ? target.map(String) : [String(target ?? '')];
|
||||
if (fields.some((f) => f.includes('sku'))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
throw new BadRequestException('SKU 生成失败,请重试');
|
||||
}
|
||||
|
||||
private async syncVisibilityPhones(productId: bigint, phones: string[]) {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.commonProductVisibilityPhone.deleteMany({ where: { productId } });
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import { AdminStoreRatingsService } from './admin-store-ratings.service';
|
||||
import { AdminStoreRatingsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
@Controller('admin/store-ratings')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminStoreRatingsController {
|
||||
constructor(private readonly service: AdminStoreRatingsService) {}
|
||||
|
||||
@Get()
|
||||
list(@Query() query: AdminStoreRatingsQueryDto) {
|
||||
return this.service.list(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
import type { AdminStoreRatingsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AdminStoreRatingsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(query: AdminStoreRatingsQueryDto) {
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 20;
|
||||
const where: Prisma.StoreRatingWhereInput = {};
|
||||
if (query.storeId) where.storeId = BigInt(query.storeId);
|
||||
if (query.redeemNo) {
|
||||
where.redeemRecord = { redeemNo: { contains: query.redeemNo } };
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.storeRating.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
include: {
|
||||
store: { select: { id: true, name: true, cityName: true } },
|
||||
redeemRecord: {
|
||||
select: {
|
||||
id: true,
|
||||
redeemNo: true,
|
||||
amount: true,
|
||||
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.storeRating.count({ where }),
|
||||
]);
|
||||
|
||||
return serializeBigInt({
|
||||
items: items.map((r) => ({
|
||||
id: r.id,
|
||||
serviceScore: r.serviceScore,
|
||||
envScore: r.envScore,
|
||||
createdAt: r.createdAt,
|
||||
store: r.store,
|
||||
redeemRecordId: r.redeemRecordId,
|
||||
redeemNo: r.redeemRecord.redeemNo,
|
||||
redeemAmount: Number(r.redeemRecord.amount),
|
||||
user: r.redeemRecord.user,
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -1068,9 +1090,10 @@ export class SaveHqAccountPermissionsDto {
|
||||
}
|
||||
|
||||
export class CreateProductDto {
|
||||
/** 可选;创建时由服务端自增生成,忽略客户端传入 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
skuCode: string;
|
||||
skuCode?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@@ -1110,6 +1133,14 @@ export class CreateProductDto {
|
||||
@IsBoolean()
|
||||
allowOnSitePickup?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowOnlinePurchase?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowCrossCityDelivery?: boolean;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@@ -1173,6 +1204,14 @@ export class UpdateProductDto {
|
||||
@IsBoolean()
|
||||
allowOnSitePickup?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowOnlinePurchase?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
allowCrossCityDelivery?: boolean;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
|
||||
@@ -242,6 +242,21 @@ export class AdminRedeemRecordsQueryDto extends PaginationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
userId?: string;
|
||||
|
||||
/** SCAN | PHONE */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
channel?: string;
|
||||
}
|
||||
|
||||
export class AdminStoreRatingsQueryDto extends PaginationQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
storeId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
redeemNo?: string;
|
||||
}
|
||||
|
||||
export class AdminDeliveriesQueryDto extends PaginationQueryDto {
|
||||
|
||||
@@ -23,6 +23,8 @@ import { AdminBenefitCouponsController, AdminBenefitLedgersController } from './
|
||||
import { AdminBenefitService } from './admin-benefit.service';
|
||||
import { AdminRedeemRecordsController, AdminDeliveriesController } from './admin-redeem.controller';
|
||||
import { AdminRedeemService, AdminDeliveriesService } from './admin-redeem.service';
|
||||
import { AdminStoreRatingsController } from './admin-store-ratings.controller';
|
||||
import { AdminStoreRatingsService } from './admin-store-ratings.service';
|
||||
import { AdminHqAccountsController } from './admin-hq-accounts.controller';
|
||||
import { AdminHqAccountsService } from './admin-hq-accounts.service';
|
||||
import { AdminProductsController } from './admin-products.controller';
|
||||
@@ -90,6 +92,7 @@ import { AdminFulfillmentProvidersController } from './admin-fulfillment-provide
|
||||
AdminBenefitCouponsController,
|
||||
AdminBenefitLedgersController,
|
||||
AdminRedeemRecordsController,
|
||||
AdminStoreRatingsController,
|
||||
AdminDeliveriesController,
|
||||
AdminHqAccountsController,
|
||||
AdminProductsController,
|
||||
@@ -122,6 +125,7 @@ import { AdminFulfillmentProvidersController } from './admin-fulfillment-provide
|
||||
AdminCitiesService,
|
||||
AdminBenefitService,
|
||||
AdminRedeemService,
|
||||
AdminStoreRatingsService,
|
||||
AdminDeliveriesService,
|
||||
AdminHqAccountsService,
|
||||
AdminProductsService,
|
||||
|
||||
@@ -36,6 +36,19 @@ export class UserRedeemController {
|
||||
rating(@CurrentUser() user: AuthUser, @Body() body: Record<string, unknown>) {
|
||||
return this.redeemService.submitRating(user.actorId, body as never);
|
||||
}
|
||||
|
||||
@Get('records')
|
||||
records(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Query('page') page = '1',
|
||||
@Query('pageSize') pageSize = '20',
|
||||
) {
|
||||
return this.redeemService.listUserRecords(
|
||||
user.actorId,
|
||||
Number(page),
|
||||
Number(pageSize),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('shop/redeem')
|
||||
@@ -83,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,15 +1149,102 @@ export class RedeemService {
|
||||
store: binding.store,
|
||||
todayCount,
|
||||
todayAmount,
|
||||
todayScanCount,
|
||||
todayPhoneCount,
|
||||
recentRecords: recent,
|
||||
});
|
||||
}
|
||||
|
||||
async listUserRecords(userId: bigint, page = 1, pageSize = 20) {
|
||||
const take = Math.min(Math.max(pageSize, 1), 50);
|
||||
const skip = (Math.max(page, 1) - 1) * take;
|
||||
const [list, total] = await Promise.all([
|
||||
this.prisma.redeemRecord.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip,
|
||||
take,
|
||||
include: {
|
||||
store: { select: { id: true, name: true } },
|
||||
rating: { select: { serviceScore: true, envScore: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.redeemRecord.count({ where: { userId } }),
|
||||
]);
|
||||
return {
|
||||
list: serializeBigInt(
|
||||
list.map((r) => ({
|
||||
id: r.id,
|
||||
redeemNo: r.redeemNo,
|
||||
amount: Number(r.amount),
|
||||
storeId: r.storeId,
|
||||
storeName: r.store?.name ?? '门店',
|
||||
createdAt: r.createdAt,
|
||||
rating: r.rating
|
||||
? { serviceScore: r.rating.serviceScore, envScore: r.rating.envScore }
|
||||
: null,
|
||||
})),
|
||||
),
|
||||
total,
|
||||
page: Math.max(page, 1),
|
||||
pageSize: take,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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 },
|
||||
});
|
||||
if (!record) throw new NotFoundException('核销记录不存在');
|
||||
const existing = await this.prisma.storeRating.findUnique({
|
||||
where: { redeemRecordId: record.id },
|
||||
});
|
||||
if (existing) return serializeBigInt(existing);
|
||||
const rating = await this.prisma.storeRating.create({
|
||||
data: {
|
||||
redeemRecordId: record.id,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -86,6 +86,25 @@ export class TradeService {
|
||||
}
|
||||
}
|
||||
|
||||
let addressOk = true;
|
||||
let addressMessage: string | null = null;
|
||||
if (!onSitePickup) {
|
||||
const allowOnline = product.allowOnlinePurchase !== false;
|
||||
const allowCross = product.allowCrossCityDelivery !== false;
|
||||
if (deliveryType === 'LOCAL' && !allowOnline) {
|
||||
addressOk = false;
|
||||
addressMessage = '该商品不支持线上购买';
|
||||
} else if (deliveryType === 'CROSS_CITY') {
|
||||
if (!allowOnline) {
|
||||
addressOk = false;
|
||||
addressMessage = '该商品不支持线上购买';
|
||||
} else if (!allowCross) {
|
||||
addressOk = false;
|
||||
addressMessage = '该商品不支持跨城配送,请更换为开城城市内的收货地址';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const check = validateMinPurchase(
|
||||
deliveryType,
|
||||
body.quantity,
|
||||
@@ -121,8 +140,13 @@ export class TradeService {
|
||||
/** 起购未满足时仍返回预览,供确认页改数量;下单接口仍会硬校验 */
|
||||
quantityOk: check.ok,
|
||||
quantityMessage: check.ok ? null : (check.message ?? null),
|
||||
/** 地址/履约未满足时仍返回预览,供确认页提示换地址;下单接口仍会硬校验 */
|
||||
addressOk,
|
||||
addressMessage,
|
||||
minQty,
|
||||
onSitePickup,
|
||||
allowCrossCityDelivery: product.allowCrossCityDelivery !== false,
|
||||
allowOnlinePurchase: product.allowOnlinePurchase !== false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -141,6 +165,9 @@ export class TradeService {
|
||||
if (preview.quantityOk === false) {
|
||||
throw new BadRequestException(preview.quantityMessage || '购买数量不满足起购要求');
|
||||
}
|
||||
if (preview.addressOk === false) {
|
||||
throw new BadRequestException(preview.addressMessage || '收货地址不可用');
|
||||
}
|
||||
|
||||
const onSitePickup = !!body.onSitePickup || preview.deliveryType === 'ON_SITE_PICKUP';
|
||||
let receiverName = '现场取货';
|
||||
@@ -1121,6 +1148,9 @@ export class TradeService {
|
||||
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
||||
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
||||
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
||||
allowOnlinePurchase: (p as { allowOnlinePurchase?: boolean }).allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery:
|
||||
(p as { allowCrossCityDelivery?: boolean }).allowCrossCityDelivery !== false,
|
||||
})),
|
||||
promoCodes,
|
||||
stores: stores.map((s) => ({
|
||||
@@ -1166,6 +1196,19 @@ export class TradeService {
|
||||
if (receiverCity && receiverCity !== city.name && receiverCity !== '郑州市') {
|
||||
deliveryType = 'CROSS_CITY';
|
||||
}
|
||||
const allowOnline = product.allowOnlinePurchase !== false;
|
||||
const allowCross = product.allowCrossCityDelivery !== false;
|
||||
if (deliveryType === 'LOCAL' && !allowOnline) {
|
||||
throw new BadRequestException('该商品不支持线上购买');
|
||||
}
|
||||
if (deliveryType === 'CROSS_CITY') {
|
||||
if (!allowOnline) {
|
||||
throw new BadRequestException('该商品不支持线上购买');
|
||||
}
|
||||
if (!allowCross) {
|
||||
throw new BadRequestException('该商品不支持跨城配送');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const check = validateMinPurchase(
|
||||
@@ -1486,6 +1529,9 @@ export class TradeService {
|
||||
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
||||
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
||||
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
||||
allowOnlinePurchase: (p as { allowOnlinePurchase?: boolean }).allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery:
|
||||
(p as { allowCrossCityDelivery?: boolean }).allowCrossCityDelivery !== false,
|
||||
})),
|
||||
promoCodes,
|
||||
stores: [],
|
||||
|
||||
Reference in New Issue
Block a user