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
|
- **仅用户明确要求时** 才执行 git commit / push
|
||||||
- 不 amend 已推送的 commit,不 force push main/master/dev
|
- 不 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` |
|
| `dev` | **staging 测试** | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||||
| `main` | **production 生产** | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
| `main` | **production 生产** | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||||
|
|
||||||
默认:`dev_jacy` → merge → `dev` → **发测试**。
|
默认:`dev_jacy` → merge → `dev` → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
||||||
生产:`dev` 验收通过 → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
|
||||||
|
|
||||||
用户只说「发布」且未指明生产时 → **发测试(staging)**。
|
> **团队约定(2026-08)**:用户说「发布 / 发版 / 直接发版」且**未特别强调**时 → **发生产(production)**。
|
||||||
用户说「发生产 / 上线生产」→ 用 `deploy-prod.sh`。
|
> 仅当用户明确说「发测试 / staging / 测试环境」时 → 发 staging。
|
||||||
|
|
||||||
|
用户说「发生产 / 上线生产 / 发版」→ 用 `deploy-prod.sh`。
|
||||||
|
用户说「发测试」→ 用 `deploy-staging.sh`。
|
||||||
|
|
||||||
## 标准流程(Windows)
|
## 标准流程(Windows)
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import DashboardPage from './pages/DashboardPage';
|
|||||||
import UsersPage from './pages/UsersPage';
|
import UsersPage from './pages/UsersPage';
|
||||||
import OrdersPage from './pages/OrdersPage';
|
import OrdersPage from './pages/OrdersPage';
|
||||||
import StoresPage from './pages/StoresPage';
|
import StoresPage from './pages/StoresPage';
|
||||||
|
import StoreRatingsPage from './pages/StoreRatingsPage';
|
||||||
import StoreAccountsPage from './pages/StoreAccountsPage';
|
import StoreAccountsPage from './pages/StoreAccountsPage';
|
||||||
import BenefitCouponsPage from './pages/BenefitCouponsPage';
|
import BenefitCouponsPage from './pages/BenefitCouponsPage';
|
||||||
import BenefitLedgersPage from './pages/BenefitLedgersPage';
|
import BenefitLedgersPage from './pages/BenefitLedgersPage';
|
||||||
@@ -78,6 +79,7 @@ export default function App() {
|
|||||||
<Route path="/products" element={<ProductsPage />} />
|
<Route path="/products" element={<ProductsPage />} />
|
||||||
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||||
<Route path="/stores" element={<StoresPage />} />
|
<Route path="/stores" element={<StoresPage />} />
|
||||||
|
<Route path="/store-ratings" element={<StoreRatingsPage />} />
|
||||||
<Route path="/store-categories" element={<StoreCategoriesPage />} />
|
<Route path="/store-categories" element={<StoreCategoriesPage />} />
|
||||||
<Route path="/store-accounts" element={<StoreAccountsPage />} />
|
<Route path="/store-accounts" element={<StoreAccountsPage />} />
|
||||||
<Route path="/store-media" element={<StoreMediaPage />} />
|
<Route path="/store-media" element={<StoreMediaPage />} />
|
||||||
@@ -94,11 +96,19 @@ export default function App() {
|
|||||||
<Route path="/redeem-pending" element={<PendingRedeemPage />} />
|
<Route path="/redeem-pending" element={<PendingRedeemPage />} />
|
||||||
<Route path="/redeem/debug" element={<RedeemDebugPage />} />
|
<Route path="/redeem/debug" element={<RedeemDebugPage />} />
|
||||||
<Route path="/finance/store-bills" element={<StoreBillsPage />} />
|
<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/partner-bills" element={<PartnerBillsPage />} />
|
||||||
<Route path="/finance/winery-bills" element={<WineryBillsPage />} />
|
<Route path="/finance/winery-bills" element={<WineryBillsPage />} />
|
||||||
<Route path="/finance/logistics-bills" element={<LogisticsBillsPage />} />
|
<Route path="/finance/logistics-bills" element={<LogisticsBillsPage />} />
|
||||||
<Route path="/store-bills" element={<Navigate to="/finance/store-bills" replace />} />
|
<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-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="/partner-bills" element={<Navigate to="/finance/partner-bills" replace />} />
|
||||||
<Route path="/tickets" element={<TicketsPage />} />
|
<Route path="/tickets" element={<TicketsPage />} />
|
||||||
<Route path="/tickets/support" element={<SupportTicketsPage />} />
|
<Route path="/tickets/support" element={<SupportTicketsPage />} />
|
||||||
|
|||||||
@@ -86,6 +86,22 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
|||||||
.finally(() => setLoadingOptions(false));
|
.finally(() => setLoadingOptions(false));
|
||||||
}, [open]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
if (!open || !productId || quantity < 1 || step !== 'form') {
|
if (!open || !productId || quantity < 1 || step !== 'form') {
|
||||||
if (step === 'form') setPreview(null);
|
if (step === 'form') setPreview(null);
|
||||||
@@ -128,7 +144,6 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
|||||||
setCreated(null);
|
setCreated(null);
|
||||||
setCodeUrl(null);
|
setCodeUrl(null);
|
||||||
setPayLoading(false);
|
setPayLoading(false);
|
||||||
setMockConfirming(false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleClose() {
|
function handleClose() {
|
||||||
@@ -140,12 +155,12 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
|||||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||||
if (!productId) return '请选择商品';
|
if (!productId) return '请选择商品';
|
||||||
if (deliveryMode === 'ADDRESS') {
|
if (deliveryMode === 'ADDRESS') {
|
||||||
|
if (!allowOnline) return '该商品不支持线上购买';
|
||||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||||
if (!addressDetail.trim()) return '请填写详细地址';
|
if (!addressDetail.trim()) return '请填写详细地址';
|
||||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||||
} else {
|
} else if (!allowOnSite) {
|
||||||
const product = options?.products.find((p) => p.id === productId);
|
return '该商品不支持现场提货';
|
||||||
if (product && product.allowOnSitePickup === false) return '该商品不支持现场提货';
|
|
||||||
}
|
}
|
||||||
if (!preview) return '请等待费用计算完成';
|
if (!preview) return '请等待费用计算完成';
|
||||||
return null;
|
return null;
|
||||||
@@ -329,20 +344,32 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<Form.Item label="履约方式" required>
|
<Form.Item label="履约方式" required>
|
||||||
<Radio.Group
|
{allowOnline && allowOnSite ? (
|
||||||
value={deliveryMode}
|
<Radio.Group
|
||||||
onChange={(e) => {
|
value={deliveryMode}
|
||||||
setDeliveryMode(e.target.value);
|
onChange={(e) => {
|
||||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
setDeliveryMode(e.target.value);
|
||||||
}}
|
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||||
options={[
|
}}
|
||||||
{ value: 'ADDRESS', label: '配送到址' },
|
options={[
|
||||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
{ value: 'ADDRESS', label: '配送到址' },
|
||||||
]}
|
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||||
/>
|
]}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
{!allowOnline && allowOnSite
|
||||||
|
? '该商品仅支持现场提货'
|
||||||
|
: allowOnline && !allowOnSite
|
||||||
|
? allowCrossCity
|
||||||
|
? '该商品仅支持配送到址(含跨城)'
|
||||||
|
: '该商品仅支持配送到址(不可跨城)'
|
||||||
|
: '该商品暂无可选履约方式'}
|
||||||
|
</Typography.Text>
|
||||||
|
)}
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
{deliveryMode === 'ADDRESS' ? (
|
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||||
<>
|
<>
|
||||||
<Form.Item label="收货人(选填)">
|
<Form.Item label="收货人(选填)">
|
||||||
<Input
|
<Input
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
label: '门店',
|
label: '门店',
|
||||||
children: [
|
children: [
|
||||||
{ key: '/stores', label: '门店列表' },
|
{ key: '/stores', label: '门店列表' },
|
||||||
|
{ key: '/store-ratings', label: '门店评价' },
|
||||||
{ key: '/store-categories', label: '门店分类' },
|
{ key: '/store-categories', label: '门店分类' },
|
||||||
{ key: '/store-accounts', label: '门店账户' },
|
{ key: '/store-accounts', label: '门店账户' },
|
||||||
{ key: '/store-media', label: '门店资源' },
|
{ key: '/store-media', label: '门店资源' },
|
||||||
@@ -145,6 +146,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/knowledge-bases': 'knowledge_bases',
|
'/knowledge-bases': 'knowledge_bases',
|
||||||
'stores-group': 'stores',
|
'stores-group': 'stores',
|
||||||
'/stores': 'stores',
|
'/stores': 'stores',
|
||||||
|
'/store-ratings': 'stores',
|
||||||
'/store-categories': 'stores',
|
'/store-categories': 'stores',
|
||||||
'/store-accounts': 'stores',
|
'/store-accounts': 'stores',
|
||||||
'/store-media': 'stores',
|
'/store-media': 'stores',
|
||||||
@@ -155,6 +157,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/fulfillment-providers': 'partners',
|
'/fulfillment-providers': 'partners',
|
||||||
'finance-group': 'finance',
|
'finance-group': 'finance',
|
||||||
'/finance/store-bills': 'finance',
|
'/finance/store-bills': 'finance',
|
||||||
|
'/finance/store-withdrawals': 'finance',
|
||||||
'/finance/partner-bills': 'finance',
|
'/finance/partner-bills': 'finance',
|
||||||
'/finance/winery-bills': 'finance',
|
'/finance/winery-bills': 'finance',
|
||||||
'/finance/logistics-bills': 'finance',
|
'/finance/logistics-bills': 'finance',
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ export type DashboardStats = {
|
|||||||
pendingBills?: number;
|
pendingBills?: number;
|
||||||
pendingPartnerDraftBills?: number;
|
pendingPartnerDraftBills?: number;
|
||||||
openTickets?: number;
|
openTickets?: number;
|
||||||
|
pendingStoreWithdrawals?: number;
|
||||||
|
overdueStoreWithdrawals?: number;
|
||||||
ordersByStatus: Array<{ status: string; count: number }>;
|
ordersByStatus: Array<{ status: string; count: number }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ export type StoreCreateForm = {
|
|||||||
bankAccountNo: string;
|
bankAccountNo: string;
|
||||||
bankBranch: string;
|
bankBranch: string;
|
||||||
settlementRate?: number;
|
settlementRate?: number;
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
visibilityPhones?: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const PHONE_RE = /^1\d{10}$/;
|
const PHONE_RE = /^1\d{10}$/;
|
||||||
|
|||||||
@@ -717,6 +717,26 @@ export default function DashboardPage() {
|
|||||||
/>
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</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}>
|
<Col xs={24} sm={12} lg={8}>
|
||||||
<Card loading={loading} title="待处理工单">
|
<Card loading={loading} title="待处理工单">
|
||||||
<Statistic value={stats?.openTickets ?? 0} suffix="个" />
|
<Statistic value={stats?.openTickets ?? 0} suffix="个" />
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ type Row = {
|
|||||||
status: string;
|
status: string;
|
||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
visibilityWhitelistEnabled?: boolean;
|
visibilityWhitelistEnabled?: boolean;
|
||||||
visibilityPhones?: string[];
|
visibilityPhones?: string[];
|
||||||
mainImageUrl?: string | null;
|
mainImageUrl?: string | null;
|
||||||
@@ -53,6 +55,8 @@ type ProductFormValues = {
|
|||||||
status?: string;
|
status?: string;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
visibilityWhitelistEnabled?: boolean;
|
visibilityWhitelistEnabled?: boolean;
|
||||||
visibilityPhones?: string[];
|
visibilityPhones?: string[];
|
||||||
coverUrl?: string;
|
coverUrl?: string;
|
||||||
@@ -72,13 +76,17 @@ type UserPickRow = {
|
|||||||
|
|
||||||
function mapDetailToForm(d: Record<string, unknown>) {
|
function mapDetailToForm(d: Record<string, unknown>) {
|
||||||
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
||||||
|
const row = d as Row;
|
||||||
return {
|
return {
|
||||||
...d,
|
...d,
|
||||||
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
||||||
carouselUrls: ((d as Row).carouselUrls?.length ? (d as Row).carouselUrls : ['']) as string[],
|
carouselUrls: (row.carouselUrls?.length ? row.carouselUrls : ['']) as string[],
|
||||||
detailImageUrls: ((d as Row).detailImageUrls?.length ? (d as Row).detailImageUrls : ['']) as string[],
|
detailImageUrls: (row.detailImageUrls?.length ? row.detailImageUrls : ['']) as string[],
|
||||||
visibilityWhitelistEnabled: !!(d as Row).visibilityWhitelistEnabled,
|
allowOnlinePurchase: row.allowOnlinePurchase !== false,
|
||||||
visibilityPhones: ((d as Row).visibilityPhones ?? []) as string[],
|
allowCrossCityDelivery: row.allowOnlinePurchase === false ? false : row.allowCrossCityDelivery !== false,
|
||||||
|
allowOnSitePickup: !!row.allowOnSitePickup,
|
||||||
|
visibilityWhitelistEnabled: !!row.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: (row.visibilityPhones ?? []) as string[],
|
||||||
storyTitle: detail.storyTitle ?? '',
|
storyTitle: detail.storyTitle ?? '',
|
||||||
storyText: detail.storyText ?? '',
|
storyText: detail.storyText ?? '',
|
||||||
features: detail.features?.length
|
features: detail.features?.length
|
||||||
@@ -109,7 +117,6 @@ function buildProductPayload(v: ProductFormValues) {
|
|||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
skuCode: v.skuCode,
|
|
||||||
barcode69: v.barcode69,
|
barcode69: v.barcode69,
|
||||||
name: v.name,
|
name: v.name,
|
||||||
subtitle: v.subtitle,
|
subtitle: v.subtitle,
|
||||||
@@ -120,6 +127,9 @@ function buildProductPayload(v: ProductFormValues) {
|
|||||||
status: v.status,
|
status: v.status,
|
||||||
sortOrder: v.sortOrder,
|
sortOrder: v.sortOrder,
|
||||||
allowOnSitePickup: !!v.allowOnSitePickup,
|
allowOnSitePickup: !!v.allowOnSitePickup,
|
||||||
|
allowOnlinePurchase: v.allowOnlinePurchase !== false,
|
||||||
|
allowCrossCityDelivery:
|
||||||
|
v.allowOnlinePurchase === false ? false : v.allowCrossCityDelivery !== false,
|
||||||
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||||
visibilityPhones,
|
visibilityPhones,
|
||||||
coverUrl: v.coverUrl,
|
coverUrl: v.coverUrl,
|
||||||
@@ -288,8 +298,8 @@ function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormIns
|
|||||||
<>
|
<>
|
||||||
{mode === 'create' && (
|
{mode === 'create' && (
|
||||||
<>
|
<>
|
||||||
<Form.Item name="skuCode" label="SKU" rules={[{ required: true }]}>
|
<Form.Item label="SKU">
|
||||||
<Input />
|
<Input disabled placeholder="保存后自动生成" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="barcode69" label="69码" rules={[{ required: true }]}>
|
<Form.Item name="barcode69" label="69码" rules={[{ required: true }]}>
|
||||||
<Input />
|
<Input />
|
||||||
@@ -320,6 +330,36 @@ function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormIns
|
|||||||
<Form.Item name="sortOrder" label="排序">
|
<Form.Item name="sortOrder" label="排序">
|
||||||
<InputNumber min={0} style={{ width: '100%' }} />
|
<InputNumber min={0} style={{ width: '100%' }} />
|
||||||
</Form.Item>
|
</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">
|
<Form.Item name="allowOnSitePickup" label="允许现场取货" valuePropName="checked">
|
||||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -383,10 +423,19 @@ export default function ProductsPage() {
|
|||||||
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '现场取货',
|
title: '履约',
|
||||||
dataIndex: 'allowOnSitePickup',
|
key: 'fulfillment',
|
||||||
width: 90,
|
width: 160,
|
||||||
render: (v: boolean) => (v ? <Tag color="green">允许</Tag> : <Tag>否</Tag>),
|
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: 'sortOrder', width: 60 },
|
||||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
@@ -431,12 +480,16 @@ export default function ProductsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
<Table rowKey="id" 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); } }} />
|
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)}
|
<Drawer title="编辑商品" width={720} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||||
extra={detail && (
|
extra={detail && (
|
||||||
<Button type="primary" onClick={async () => {
|
<Button type="primary" onClick={async () => {
|
||||||
const v = await editForm.validateFields();
|
const v = await editForm.validateFields();
|
||||||
|
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||||
|
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const payload = buildProductPayload(v);
|
const payload = buildProductPayload(v);
|
||||||
await request(`/admin/products/${detail.id}`, { method: 'PUT', body: JSON.stringify(payload) });
|
await request(`/admin/products/${detail.id}`, { method: 'PUT', body: JSON.stringify(payload) });
|
||||||
message.success('已保存');
|
message.success('已保存');
|
||||||
@@ -471,6 +524,10 @@ export default function ProductsPage() {
|
|||||||
</Drawer>
|
</Drawer>
|
||||||
<Modal title="新建商品" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
|
<Modal title="新建商品" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
|
||||||
const v = await createForm.validateFields();
|
const v = await createForm.validateFields();
|
||||||
|
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||||
|
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const payload = buildProductPayload(v);
|
const payload = buildProductPayload(v);
|
||||||
await request('/admin/products', { method: 'POST', body: JSON.stringify(payload) });
|
await request('/admin/products', { method: 'POST', body: JSON.stringify(payload) });
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
@@ -479,7 +536,8 @@ export default function ProductsPage() {
|
|||||||
void reload();
|
void reload();
|
||||||
}} width={720}>
|
}} width={720}>
|
||||||
<Form form={createForm} layout="vertical" initialValues={{
|
<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: [],
|
visibilityWhitelistEnabled: false, visibilityPhones: [],
|
||||||
carouselUrls: [''], detailImageUrls: [''],
|
carouselUrls: [''], detailImageUrls: [''],
|
||||||
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
import { useState } from 'react';
|
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 type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
type Row = {
|
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 };
|
user?: { userNo: string; phone: string | null };
|
||||||
store?: { name: string; cityName: string };
|
store?: { name: string; cityName: string };
|
||||||
coupon?: { couponNo: string };
|
coupon?: { couponNo: string };
|
||||||
@@ -21,6 +27,7 @@ export default function RedeemRecordsPage() {
|
|||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
||||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||||
|
if (filters.channel) qs.set('channel', filters.channel);
|
||||||
return qs;
|
return qs;
|
||||||
},
|
},
|
||||||
[filters],
|
[filters],
|
||||||
@@ -30,6 +37,19 @@ export default function RedeemRecordsPage() {
|
|||||||
|
|
||||||
const columns: ColumnsType<Row> = [
|
const columns: ColumnsType<Row> = [
|
||||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
{ 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: ['user', 'userNo'], width: 110 },
|
||||||
{ title: '门店', dataIndex: ['store', 'name'] },
|
{ title: '门店', dataIndex: ['store', 'name'] },
|
||||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||||
@@ -37,12 +57,19 @@ export default function RedeemRecordsPage() {
|
|||||||
{ title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 },
|
{ title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 },
|
||||||
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
{
|
{
|
||||||
title: '操作', width: 80,
|
title: '操作',
|
||||||
|
width: 80,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Button type="link" size="small" onClick={async () => {
|
<Button
|
||||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
type="link"
|
||||||
setDrawerOpen(true);
|
size="small"
|
||||||
}}>详情</Button>
|
onClick={async () => {
|
||||||
|
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
||||||
|
setDrawerOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -50,16 +77,65 @@ export default function RedeemRecordsPage() {
|
|||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Typography.Title level={4}>核销记录</Typography.Title>
|
<Typography.Title level={4}>核销记录</Typography.Title>
|
||||||
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
|
<Form
|
||||||
<Form.Item name="redeemNo" label="核销号"><Input allowClear /></Form.Item>
|
form={form}
|
||||||
<Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item>
|
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>
|
</Form>
|
||||||
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1000 }}
|
<Table
|
||||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
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)}>
|
<Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
|
||||||
{detail && (
|
{detail && (
|
||||||
<Descriptions column={1} bordered size="small">
|
<Descriptions column={1} bordered size="small">
|
||||||
<Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
|
<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.amount)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useSearchParams } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
@@ -6,6 +7,7 @@ import {
|
|||||||
Descriptions,
|
Descriptions,
|
||||||
Drawer,
|
Drawer,
|
||||||
Form,
|
Form,
|
||||||
|
Input,
|
||||||
Modal,
|
Modal,
|
||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
@@ -17,44 +19,61 @@ import {
|
|||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import type { Dayjs } from 'dayjs';
|
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 { request, type Paginated } from '../lib/api';
|
||||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
type Row = {
|
type Row = {
|
||||||
|
kind: StoreSettlementKind;
|
||||||
id: string;
|
id: string;
|
||||||
billNo: string;
|
billNo: string;
|
||||||
billDate: string;
|
amount: number;
|
||||||
redeemCount: number;
|
status: StoreSettlementStatus;
|
||||||
redeemAmount: number;
|
date: string;
|
||||||
settlementRate: number;
|
overdue?: boolean;
|
||||||
payoutAmount: number;
|
redeemCount?: number | null;
|
||||||
status: string;
|
redeemAmount?: number | null;
|
||||||
paidAt?: string | null;
|
settlementRate?: number | null;
|
||||||
store?: { id: string; name: string; cityName: string; phone?: string };
|
payoutCount?: number | null;
|
||||||
|
store?: { id: string; name: string; cityName: string; phone?: string | null };
|
||||||
};
|
};
|
||||||
|
|
||||||
type StoreOption = { id: string; name: string; phone: string };
|
type StoreOption = { id: string; name: string; phone: string };
|
||||||
|
|
||||||
const STATUS_LABELS: Record<string, string> = {
|
|
||||||
UNPAID: '未打款',
|
|
||||||
PAID: '已打款',
|
|
||||||
};
|
|
||||||
|
|
||||||
const STATUS_COLORS: Record<string, string> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
UNPAID: 'red',
|
UNPAID: 'red',
|
||||||
PAID: 'green',
|
PAID: 'green',
|
||||||
|
PENDING_REVIEW: 'orange',
|
||||||
|
REJECTED: 'red',
|
||||||
|
};
|
||||||
|
|
||||||
|
const KIND_COLORS: Record<StoreSettlementKind, string> = {
|
||||||
|
T1_BILL: 'blue',
|
||||||
|
WITHDRAW: 'purple',
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function StoreBillsPage() {
|
export default function StoreBillsPage() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : '';
|
||||||
const [form] = Form.useForm();
|
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 [stores, setStores] = useState<StoreOption[]>([]);
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||||
'/admin/store-bills',
|
'/admin/store-settlements',
|
||||||
() => {
|
() => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.kind) qs.set('kind', filters.kind);
|
||||||
if (filters.status) qs.set('status', filters.status);
|
if (filters.status) qs.set('status', filters.status);
|
||||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||||
@@ -64,21 +83,38 @@ export default function StoreBillsPage() {
|
|||||||
[filters],
|
[filters],
|
||||||
);
|
);
|
||||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||||
|
const [detailKind, setDetailKind] = useState<StoreSettlementKind | null>(null);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
|
const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
|
||||||
const [batchLoading, setBatchLoading] = useState(false);
|
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(() => {
|
useEffect(() => {
|
||||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||||
.then((res) => setStores(res.items))
|
.then((res) => setStores(res.items))
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
|
void request<{ pendingCount: number; overdueCount: number }>(
|
||||||
|
'/admin/store-withdrawals/overdue-summary',
|
||||||
|
)
|
||||||
|
.then(setOverdueSummary)
|
||||||
|
.catch(() => {});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
function confirmPay(ids: string[], amountHint?: number) {
|
function confirmPay(ids: string[], amountHint?: number) {
|
||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
title: '确认打款?',
|
title: '确认打款?',
|
||||||
content: `将确认 ${ids.length} 笔门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
content: `将确认 ${ids.length} 笔 T+1 门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
||||||
okText: '确认打款',
|
okText: '确认打款',
|
||||||
cancelText: '取消',
|
cancelText: '取消',
|
||||||
onOk: async () => {
|
onOk: async () => {
|
||||||
@@ -102,9 +138,75 @@ export default function StoreBillsPage() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openDetail(id: string) {
|
function approveWithdraw(id: string) {
|
||||||
const d = await request<Record<string, unknown>>(`/admin/store-bills/${id}`);
|
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);
|
setDetail(d);
|
||||||
|
setDetailKind(row.kind);
|
||||||
setDrawerOpen(true);
|
setDrawerOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,88 +220,134 @@ export default function StoreBillsPage() {
|
|||||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||||
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
||||||
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
||||||
message.success(`已导出 ${result.count} 条`);
|
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
||||||
} finally {
|
} finally {
|
||||||
setExporting(false);
|
setExporting(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = data?.summary;
|
const summary = data?.summary;
|
||||||
const selectedRows = (data?.items ?? []).filter((r) => selectedKeys.includes(r.id));
|
const selectedRows = (data?.items ?? []).filter(
|
||||||
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.payoutAmount), 0);
|
(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> = [
|
const columns: ColumnsType<Row> = [
|
||||||
{ title: '账单号', dataIndex: 'billNo', width: 170, ellipsis: true },
|
|
||||||
{
|
{
|
||||||
title: '账单日',
|
title: '类型',
|
||||||
dataIndex: 'billDate',
|
dataIndex: 'kind',
|
||||||
width: 110,
|
width: 100,
|
||||||
render: (v) => String(v || '').slice(0, 10),
|
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', 'name'], width: 140, ellipsis: true },
|
||||||
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||||
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||||
{ title: '核销笔数', dataIndex: 'redeemCount', width: 90 },
|
|
||||||
{
|
{
|
||||||
title: '核销金额',
|
title: '笔数',
|
||||||
dataIndex: 'redeemAmount',
|
width: 80,
|
||||||
width: 110,
|
render: (_, row) =>
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '结算比例',
|
|
||||||
dataIndex: 'settlementRate',
|
|
||||||
width: 90,
|
|
||||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '应付金额',
|
title: '应付金额',
|
||||||
dataIndex: 'payoutAmount',
|
dataIndex: 'amount',
|
||||||
width: 110,
|
width: 110,
|
||||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '状态',
|
title: '状态',
|
||||||
dataIndex: 'status',
|
dataIndex: 'status',
|
||||||
width: 90,
|
width: 100,
|
||||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
render: (s: string, row) => (
|
||||||
|
<Tag color={STATUS_COLORS[s] || 'default'}>{storeSettlementStatusLabel(row.kind, s)}</Tag>
|
||||||
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 160,
|
width: 200,
|
||||||
fixed: 'right',
|
fixed: 'right',
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space size={0}>
|
<Space size={0}>
|
||||||
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
<Button type="link" size="small" onClick={() => void openDetail(row)}>
|
||||||
明细
|
明细
|
||||||
</Button>
|
</Button>
|
||||||
{row.status === 'UNPAID' && (
|
{row.kind === 'T1_BILL' && row.status === 'UNPAID' && (
|
||||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.payoutAmount))}>
|
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.amount))}>
|
||||||
确认打款
|
确认打款
|
||||||
</Button>
|
</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>
|
</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 (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}>
|
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}>
|
||||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||||
门店对账单
|
门店账单
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
按核销日汇总(每日 8:00 自动出账);未打款红色、已打款绿色
|
含 T+1 自动出账与门店手动提现;按类型筛选,详情与审核动作沿用原接口
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
|
{overdueSummary && overdueSummary.overdueCount > 0 ? (
|
||||||
|
<Typography.Text type="danger">
|
||||||
|
手动提现超时未审 {overdueSummary.overdueCount} 笔(待审共 {overdueSummary.pendingCount})
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
</Space>
|
</Space>
|
||||||
|
|
||||||
{summary && (
|
{summary && (
|
||||||
<Card size="small" style={{ marginBottom: 16 }}>
|
<Card size="small" style={{ marginBottom: 16 }}>
|
||||||
<Space size="large" wrap>
|
<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.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>
|
</Space>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
@@ -208,16 +356,37 @@ export default function StoreBillsPage() {
|
|||||||
form={form}
|
form={form}
|
||||||
layout="inline"
|
layout="inline"
|
||||||
style={{ marginBottom: 16 }}
|
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({
|
setFilters({
|
||||||
|
kind: v.kind || '',
|
||||||
storeId: v.storeId || '',
|
storeId: v.storeId || '',
|
||||||
status: v.status || '',
|
status: v.status || '',
|
||||||
dateFrom: v.range?.[0] ? v.range[0].format('YYYY-MM-DD') : '',
|
dateFrom: v.range?.[0] ? v.range[0].format('YYYY-MM-DD') : '',
|
||||||
dateTo: v.range?.[1] ? v.range[1].format('YYYY-MM-DD') : '',
|
dateTo: v.range?.[1] ? v.range[1].format('YYYY-MM-DD') : '',
|
||||||
});
|
});
|
||||||
setPage(1);
|
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="门店">
|
<Form.Item name="storeId" label="门店">
|
||||||
<Select
|
<Select
|
||||||
allowClear
|
allowClear
|
||||||
@@ -232,10 +401,16 @@ export default function StoreBillsPage() {
|
|||||||
<Select
|
<Select
|
||||||
allowClear
|
allowClear
|
||||||
style={{ width: 120 }}
|
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>
|
||||||
<Form.Item name="range" label="账单日">
|
<Form.Item name="range" label="日期">
|
||||||
<DatePicker.RangePicker />
|
<DatePicker.RangePicker />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
@@ -249,6 +424,7 @@ export default function StoreBillsPage() {
|
|||||||
form.resetFields();
|
form.resetFields();
|
||||||
setFilters({});
|
setFilters({});
|
||||||
setPage(1);
|
setPage(1);
|
||||||
|
setSelectedKeys([]);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
重置
|
重置
|
||||||
@@ -256,33 +432,36 @@ export default function StoreBillsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
<Button loading={exporting} onClick={() => void exportExcel()}>
|
<Button loading={exporting} onClick={() => void exportExcel()}>
|
||||||
导出 Excel
|
导出 T+1 Excel
|
||||||
</Button>
|
</Button>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item>
|
<Form.Item>
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
disabled={!selectedKeys.length}
|
disabled={!selectedRows.length}
|
||||||
loading={batchLoading}
|
loading={batchLoading}
|
||||||
onClick={() => confirmPay(selectedKeys.map(String), selectedAmount)}
|
onClick={() => confirmPay(selectedRows.map((r) => r.id), selectedAmount)}
|
||||||
>
|
>
|
||||||
批量确认打款 ({selectedKeys.length})
|
批量确认打款 ({selectedRows.length})
|
||||||
</Button>
|
</Button>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
<Table
|
<Table
|
||||||
rowKey="id"
|
rowKey={(r) => `${r.kind}-${r.id}`}
|
||||||
className="admin-table-nowrap"
|
className="admin-table-nowrap"
|
||||||
loading={loading}
|
loading={loading}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data?.items ?? []}
|
dataSource={data?.items ?? []}
|
||||||
|
rowClassName={(row) => (row.overdue ? 'ant-table-row-selected' : '')}
|
||||||
rowSelection={{
|
rowSelection={{
|
||||||
selectedRowKeys: selectedKeys,
|
selectedRowKeys: selectedKeys,
|
||||||
onChange: setSelectedKeys,
|
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={{
|
pagination={{
|
||||||
current: page,
|
current: page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -295,14 +474,25 @@ export default function StoreBillsPage() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Drawer title="门店对账单明细" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}>
|
<Drawer
|
||||||
{detail && (
|
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 column={1} size="small" bordered>
|
||||||
<Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item>
|
<Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item>
|
||||||
<Descriptions.Item label="账单日">{String(detail.billDate || '').slice(0, 10)}</Descriptions.Item>
|
<Descriptions.Item label="账单日">
|
||||||
<Descriptions.Item label="应付">¥{Number(detail.payoutAmount ?? 0).toFixed(2)}</Descriptions.Item>
|
{String(detail.billDate || '').slice(0, 10)}
|
||||||
<Descriptions.Item label="状态">{STATUS_LABELS[String(detail.status)] || String(detail.status)}</Descriptions.Item>
|
</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="打款时间">
|
<Descriptions.Item label="打款时间">
|
||||||
{detail.paidAt ? fmtTime(String(detail.paidAt)) : '—'}
|
{detail.paidAt ? fmtTime(String(detail.paidAt)) : '—'}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
@@ -318,7 +508,8 @@ export default function StoreBillsPage() {
|
|||||||
columns={[
|
columns={[
|
||||||
{
|
{
|
||||||
title: '核销单号',
|
title: '核销单号',
|
||||||
render: (_, r) => String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
render: (_, r) =>
|
||||||
|
String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '金额',
|
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>
|
</Drawer>
|
||||||
</div>
|
</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 { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Steps,
|
Steps,
|
||||||
|
Switch,
|
||||||
Table,
|
Table,
|
||||||
Tabs,
|
Tabs,
|
||||||
Tag,
|
Tag,
|
||||||
@@ -20,6 +21,7 @@ import {
|
|||||||
message,
|
message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import type { FormInstance } from 'antd/es/form';
|
||||||
import { FilePdfOutlined, LinkOutlined, EnvironmentOutlined } from '@ant-design/icons';
|
import { FilePdfOutlined, LinkOutlined, EnvironmentOutlined } from '@ant-design/icons';
|
||||||
import { request, type Paginated } from '../lib/api';
|
import { request, type Paginated } from '../lib/api';
|
||||||
import {
|
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 = {
|
type StoreRow = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -287,6 +372,8 @@ type StoreRow = {
|
|||||||
intro: string | null;
|
intro: string | null;
|
||||||
coverUrl: string | null;
|
coverUrl: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
visibilityPhones?: string[];
|
||||||
cityRef?: { name: string; code: string };
|
cityRef?: { name: string; code: string };
|
||||||
partner?: { companyName: string };
|
partner?: { companyName: string };
|
||||||
account?: {
|
account?: {
|
||||||
@@ -504,6 +591,10 @@ export default function StoresPage() {
|
|||||||
bankAccountName: account?.bankAccountName || undefined,
|
bankAccountName: account?.bankAccountName || undefined,
|
||||||
bankAccountNo: account?.bankAccountNo || undefined,
|
bankAccountNo: account?.bankAccountNo || undefined,
|
||||||
bankBranch: account?.bankBranch || undefined,
|
bankBranch: account?.bankBranch || undefined,
|
||||||
|
visibilityWhitelistEnabled: !!d.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: Array.isArray(d.visibilityPhones)
|
||||||
|
? (d.visibilityPhones as string[])
|
||||||
|
: [],
|
||||||
});
|
});
|
||||||
setDrawerOpen(true);
|
setDrawerOpen(true);
|
||||||
}
|
}
|
||||||
@@ -543,6 +634,10 @@ export default function StoresPage() {
|
|||||||
bankAccountName: v.bankAccountName ?? null,
|
bankAccountName: v.bankAccountName ?? null,
|
||||||
bankAccountNo: v.bankAccountNo ?? null,
|
bankAccountNo: v.bankAccountNo ?? null,
|
||||||
bankBranch: v.bankBranch ?? 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
|
...(hasCoords
|
||||||
? { latitude: Number(v.latitude), longitude: Number(v.longitude) }
|
? { latitude: Number(v.latitude), longitude: Number(v.longitude) }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -632,6 +727,8 @@ export default function StoresPage() {
|
|||||||
openTime2: undefined,
|
openTime2: undefined,
|
||||||
closeTime2: undefined,
|
closeTime2: undefined,
|
||||||
avgPrice: undefined,
|
avgPrice: undefined,
|
||||||
|
visibilityWhitelistEnabled: false,
|
||||||
|
visibilityPhones: [],
|
||||||
});
|
});
|
||||||
setCreateStep(0);
|
setCreateStep(0);
|
||||||
setCreateError('');
|
setCreateError('');
|
||||||
@@ -713,6 +810,10 @@ export default function StoresPage() {
|
|||||||
bankAccountNo: values.bankAccountNo.replace(/\s/g, ''),
|
bankAccountNo: values.bankAccountNo.replace(/\s/g, ''),
|
||||||
bankBranch: values.bankBranch.trim(),
|
bankBranch: values.bankBranch.trim(),
|
||||||
settlementRate: Number(values.settlementRate ?? 60) / 100,
|
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('门店已创建');
|
message.success('门店已创建');
|
||||||
@@ -766,13 +867,23 @@ export default function StoresPage() {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 120 },
|
{ 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: 'intro', width: 160, ellipsis: true, render: (v) => v || '—' },
|
||||||
{ title: '店长', dataIndex: ['account', 'name'], width: 90, render: (v) => v || '—' },
|
{ title: '店长', dataIndex: ['account', 'name'], width: 90, render: (v) => v || '—' },
|
||||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
{
|
{
|
||||||
title: '操作', width: 80,
|
title: '操作', width: 140,
|
||||||
render: (_, row) => (
|
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 }} />
|
<Input type="time" style={{ width: 140 }} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Space>
|
</Space>
|
||||||
|
<StoreVisibilityWhitelistFields form={editForm} />
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -1276,6 +1388,7 @@ export default function StoresPage() {
|
|||||||
>
|
>
|
||||||
<Input.TextArea rows={3} placeholder="选填,最多1000字" showCount maxLength={1000} />
|
<Input.TextArea rows={3} placeholder="选填,最多1000字" showCount maxLength={1000} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<StoreVisibilityWhitelistFields form={createForm} />
|
||||||
</div>
|
</div>
|
||||||
<div style={{ display: createStep === 1 ? 'block' : 'none' }}>
|
<div style={{ display: createStep === 1 ? 'block' : 'none' }}>
|
||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
|
|||||||
@@ -151,6 +151,22 @@ export default function ProxyOrderPage() {
|
|||||||
autoReceive,
|
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(() => {
|
useEffect(() => {
|
||||||
if (!productId || quantity < 1) {
|
if (!productId || quantity < 1) {
|
||||||
setPreview(null);
|
setPreview(null);
|
||||||
@@ -169,8 +185,14 @@ export default function ProxyOrderPage() {
|
|||||||
}),
|
}),
|
||||||
silent: true,
|
silent: true,
|
||||||
})
|
})
|
||||||
.then(setPreview)
|
.then((data) => {
|
||||||
.catch(() => setPreview(null))
|
setPreview(data);
|
||||||
|
setMsg('');
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
setPreview(null);
|
||||||
|
setMsg(e instanceof Error ? e.message : '费用预览失败');
|
||||||
|
})
|
||||||
.finally(() => setPreviewLoading(false));
|
.finally(() => setPreviewLoading(false));
|
||||||
}, 300);
|
}, 300);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
@@ -180,11 +202,14 @@ export default function ProxyOrderPage() {
|
|||||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||||
if (!productId) return '请选择商品';
|
if (!productId) return '请选择商品';
|
||||||
if (deliveryMode === 'ADDRESS') {
|
if (deliveryMode === 'ADDRESS') {
|
||||||
|
if (!allowOnline) return '该商品不支持线上购买';
|
||||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||||
if (!addressDetail.trim()) return '请填写详细地址';
|
if (!addressDetail.trim()) return '请填写详细地址';
|
||||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||||
|
} else if (!allowOnSite) {
|
||||||
|
return '该商品不支持现场提货';
|
||||||
}
|
}
|
||||||
if (!preview) return '请等待费用计算完成';
|
if (!preview) return msg || '请等待费用计算完成';
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,7 +330,6 @@ export default function ProxyOrderPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
|
||||||
const deliveryLabel =
|
const deliveryLabel =
|
||||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||||
? '现场提货'
|
? '现场提货'
|
||||||
@@ -477,25 +501,37 @@ export default function ProxyOrderPage() {
|
|||||||
|
|
||||||
<section className="partner-form-section">
|
<section className="partner-form-section">
|
||||||
<label className="partner-form-label">履约方式</label>
|
<label className="partner-form-label">履约方式</label>
|
||||||
<div className="partner-proxy-mode-tabs">
|
{allowOnline && allowOnSite ? (
|
||||||
<button
|
<div className="partner-proxy-mode-tabs">
|
||||||
type="button"
|
<button
|
||||||
className={`partner-proxy-mode-tab${deliveryMode === 'ADDRESS' ? ' is-active' : ''}`}
|
type="button"
|
||||||
onClick={() => setDeliveryMode('ADDRESS')}
|
className={`partner-proxy-mode-tab${deliveryMode === 'ADDRESS' ? ' is-active' : ''}`}
|
||||||
>
|
onClick={() => setDeliveryMode('ADDRESS')}
|
||||||
配送到址
|
>
|
||||||
</button>
|
配送到址
|
||||||
<button
|
</button>
|
||||||
type="button"
|
<button
|
||||||
className={`partner-proxy-mode-tab${deliveryMode === 'ON_SITE_PICKUP' ? ' is-active' : ''}`}
|
type="button"
|
||||||
onClick={() => setDeliveryMode('ON_SITE_PICKUP')}
|
className={`partner-proxy-mode-tab${deliveryMode === 'ON_SITE_PICKUP' ? ' is-active' : ''}`}
|
||||||
>
|
onClick={() => setDeliveryMode('ON_SITE_PICKUP')}
|
||||||
现场提货
|
>
|
||||||
</button>
|
现场提货
|
||||||
</div>
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="label-md text-muted">
|
||||||
|
{!allowOnline && allowOnSite
|
||||||
|
? '该商品仅支持现场提货'
|
||||||
|
: allowOnline && !allowOnSite
|
||||||
|
? allowCrossCity
|
||||||
|
? '该商品仅支持配送到址(含跨城)'
|
||||||
|
: '该商品仅支持配送到址(不可跨城)'
|
||||||
|
: '该商品暂无可选履约方式'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{deliveryMode === 'ADDRESS' ? (
|
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||||
<>
|
<>
|
||||||
<section className="partner-form-section">
|
<section className="partner-form-section">
|
||||||
<label className="partner-form-label">收货人(选填)</label>
|
<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 { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
@@ -9,12 +9,30 @@ function fmtMoney(n: number) {
|
|||||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
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() {
|
export default function ProxyOrderProductsPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const selectedId = searchParams.get('selected') || '';
|
const selectedId = searchParams.get('selected') || '';
|
||||||
const [products, setProducts] = useState<PartnerProxyOrderProductOption[]>([]);
|
const [products, setProducts] = useState<PartnerProxyOrderProductOption[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const [filter, setFilter] = useState<FulfillmentFilter>('ALL');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
request<PartnerProxyOrderOptions>('PARTNER_H5', '/partner/proxy-orders/options')
|
request<PartnerProxyOrderOptions>('PARTNER_H5', '/partner/proxy-orders/options')
|
||||||
@@ -23,6 +41,15 @@ export default function ProxyOrderProductsPage() {
|
|||||||
.finally(() => setLoading(false));
|
.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) {
|
function pick(product: PartnerProxyOrderProductOption) {
|
||||||
navigate(`/proxy-order?productId=${encodeURIComponent(product.id)}`, { replace: true });
|
navigate(`/proxy-order?productId=${encodeURIComponent(product.id)}`, { replace: true });
|
||||||
}
|
}
|
||||||
@@ -30,12 +57,32 @@ export default function ProxyOrderProductsPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="page partner-proxy-order-page">
|
<div className="page partner-proxy-order-page">
|
||||||
<PageHeader title="选择酒品" onBack={() => navigate(-1)} />
|
<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">
|
<main className="partner-proxy-product-list">
|
||||||
{loading ? <p className="label-md text-muted">加载中…</p> : null}
|
{loading ? <p className="label-md text-muted">加载中…</p> : null}
|
||||||
{!loading && products.length === 0 ? (
|
{!loading && filtered.length === 0 ? (
|
||||||
<p className="label-md text-muted">暂无可售商品</p>
|
<p className="label-md text-muted">暂无符合条件的商品</p>
|
||||||
) : null}
|
) : null}
|
||||||
{products.map((p) => {
|
{filtered.map((p) => {
|
||||||
const benefit = p.benefitAmount != null ? Number(p.benefitAmount) : Number(p.price);
|
const benefit = p.benefitAmount != null ? Number(p.benefitAmount) : Number(p.price);
|
||||||
const active = p.id === selectedId;
|
const active = p.id === selectedId;
|
||||||
return (
|
return (
|
||||||
@@ -59,6 +106,11 @@ export default function ProxyOrderProductsPage() {
|
|||||||
</div>
|
</div>
|
||||||
<p className="partner-proxy-product-spec">{p.spec}</p>
|
<p className="partner-proxy-product-spec">{p.spec}</p>
|
||||||
<p className="partner-proxy-product-benefit">好客权益 ¥{fmtMoney(benefit)}</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>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3374,6 +3374,50 @@ body {
|
|||||||
color: var(--color-muted, #999);
|
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 {
|
.partner-proxy-product-list {
|
||||||
padding: 0 16px 24px;
|
padding: 0 16px 24px;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import RecordsPage from './pages/RecordsPage';
|
|||||||
import StatusPage from './pages/StatusPage';
|
import StatusPage from './pages/StatusPage';
|
||||||
import MinePage from './pages/MinePage';
|
import MinePage from './pages/MinePage';
|
||||||
import StaffPage from './pages/StaffPage';
|
import StaffPage from './pages/StaffPage';
|
||||||
|
import WithdrawPage from './pages/WithdrawPage';
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
@@ -22,6 +23,7 @@ export default function App() {
|
|||||||
<Route path="/legal/privacy-policy" element={<LegalPage docId="privacy-policy" />} />
|
<Route path="/legal/privacy-policy" element={<LegalPage docId="privacy-policy" />} />
|
||||||
<Route path="/select-store" element={<SelectStorePage />} />
|
<Route path="/select-store" element={<SelectStorePage />} />
|
||||||
<Route path="/staff" element={<StaffPage />} />
|
<Route path="/staff" element={<StaffPage />} />
|
||||||
|
<Route path="/withdraw" element={<WithdrawPage />} />
|
||||||
<Route path="/redeem" element={<RedeemConfirmPage />} />
|
<Route path="/redeem" element={<RedeemConfirmPage />} />
|
||||||
<Route path="/redeem/phone" element={<PhoneRedeemPage />} />
|
<Route path="/redeem/phone" element={<PhoneRedeemPage />} />
|
||||||
<Route path="/redeem/success" element={<RedeemSuccessPage />} />
|
<Route path="/redeem/success" element={<RedeemSuccessPage />} />
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ function formatScanError(e: unknown): string {
|
|||||||
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
||||||
}
|
}
|
||||||
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
||||||
return `${msg}(可在 URL 后加 ?wxdebug=1 开启 JSSDK 调试查看详情)`;
|
return '微信权限校验尚未完成,请等待 1~2 秒后再次点击扫码(首次绑定微信时较常见)';
|
||||||
}
|
}
|
||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
@@ -73,7 +73,7 @@ export default function HomePage() {
|
|||||||
};
|
};
|
||||||
}, [loadDashboard]);
|
}, [loadDashboard]);
|
||||||
|
|
||||||
async function runScan() {
|
async function runScan(opts?: { postAuthWarmup?: boolean }) {
|
||||||
if (!isWechatEnv()) {
|
if (!isWechatEnv()) {
|
||||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||||
return;
|
return;
|
||||||
@@ -81,8 +81,14 @@ export default function HomePage() {
|
|||||||
setScanning(true);
|
setScanning(true);
|
||||||
setScanMsg('');
|
setScanMsg('');
|
||||||
try {
|
try {
|
||||||
|
// 授权回跳后强制重签,避免沿用带 code 的旧签名态
|
||||||
|
if (opts?.postAuthWarmup) {
|
||||||
|
weixinSdk.reset();
|
||||||
|
}
|
||||||
await weixinSdk.init();
|
await weixinSdk.init();
|
||||||
const raw = await weixinSdk.scanQrCode();
|
const raw = await weixinSdk.scanQrCode(
|
||||||
|
opts?.postAuthWarmup ? { postAuthWarmup: true } : undefined,
|
||||||
|
);
|
||||||
if (!raw) {
|
if (!raw) {
|
||||||
void loadDashboard();
|
void loadDashboard();
|
||||||
return;
|
return;
|
||||||
@@ -111,12 +117,14 @@ export default function HomePage() {
|
|||||||
}
|
}
|
||||||
setAuthModalOpen(false);
|
setAuthModalOpen(false);
|
||||||
setAuthError('');
|
setAuthError('');
|
||||||
|
// 先清 OAuth 参数再扫,保证 JSSDK 签名 URL 与当前页一致
|
||||||
stripOAuthParamsFromLocation();
|
stripOAuthParamsFromLocation();
|
||||||
setSearchParams({}, { replace: true });
|
setSearchParams({}, { replace: true });
|
||||||
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
||||||
if (shouldScan) {
|
if (shouldScan) {
|
||||||
window.setTimeout(() => void runScan(), 0);
|
// OAuth 回跳后微信权限离线校验未完成;稍候再扫,失败可再点一次
|
||||||
|
window.setTimeout(() => void runScan({ postAuthWarmup: true }), 400);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
@@ -182,6 +190,9 @@ export default function HomePage() {
|
|||||||
<div className="shop-home-stat">
|
<div className="shop-home-stat">
|
||||||
<p className="shop-home-stat-label">今日核销笔数</p>
|
<p className="shop-home-stat-label">今日核销笔数</p>
|
||||||
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
||||||
|
<p className="shop-home-stat-sub">
|
||||||
|
扫码 {Number(dash?.todayScanCount || 0)} · 手机号 {Number(dash?.todayPhoneCount || 0)}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="shop-home-stat">
|
<div className="shop-home-stat">
|
||||||
<p className="shop-home-stat-label">今日到账金额</p>
|
<p className="shop-home-stat-label">今日到账金额</p>
|
||||||
|
|||||||
@@ -141,6 +141,10 @@ export default function MinePage() {
|
|||||||
切换门店
|
切换门店
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : 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 ? (
|
{profile?.isPrimary ? (
|
||||||
<button type="button" className="shop-mine-action" onClick={() => navigate('/staff')}>
|
<button type="button" className="shop-mine-action" onClick={() => navigate('/staff')}>
|
||||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>group</span>
|
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>group</span>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||||
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel, type RedeemStatsDto } from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
|
|
||||||
type RangeKey = 'today' | '7d' | '30d';
|
type RangeKey = 'today' | '7d' | '30d';
|
||||||
@@ -23,32 +24,59 @@ function inRange(dateStr: string, range: RangeKey) {
|
|||||||
return d >= start;
|
return d >= start;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function channelLabel(channel: unknown): string {
|
||||||
|
const key = channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||||
|
return REDEEM_CHANNEL_LABELS[key];
|
||||||
|
}
|
||||||
|
|
||||||
export default function RecordsPage() {
|
export default function RecordsPage() {
|
||||||
const [records, setRecords] = useState<Array<Record<string, unknown>>>([]);
|
const [records, setRecords] = useState<Array<Record<string, unknown>>>([]);
|
||||||
const [range, setRange] = useState<RangeKey>('today');
|
const [range, setRange] = useState<RangeKey>('today');
|
||||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||||
const [storeName, setStoreName] = useState('');
|
const [storeName, setStoreName] = useState('');
|
||||||
|
const [statsOpen, setStatsOpen] = useState(false);
|
||||||
|
const [statsLoading, setStatsLoading] = useState(false);
|
||||||
|
const [stats, setStats] = useState<RedeemStatsDto | null>(null);
|
||||||
|
|
||||||
const loadRecords = useCallback(() => {
|
const loadRecords = useCallback(() => {
|
||||||
return Promise.all([
|
return Promise.all([
|
||||||
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records').then((d) => {
|
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records?pageSize=200').then(
|
||||||
setRecords(d.list || []);
|
(d) => {
|
||||||
}),
|
setRecords(d.list || []);
|
||||||
|
},
|
||||||
|
),
|
||||||
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
||||||
.then((s) => setStoreName(String(s.name || '')))
|
.then((s) => setStoreName(String(s.name || '')))
|
||||||
.catch(() => {}),
|
.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(() => {
|
useEffect(() => {
|
||||||
void loadRecords();
|
void loadRecords();
|
||||||
}, [loadRecords]);
|
}, [loadRecords]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (statsOpen) void loadStats(range);
|
||||||
|
}, [statsOpen, range, loadStats]);
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
return records.filter((r) => {
|
return records.filter((r) => {
|
||||||
if (!inRange(String(r.createdAt), range)) return false;
|
if (!inRange(String(r.createdAt), range)) return false;
|
||||||
if (statusFilter === 'all') return true;
|
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;
|
if (statusFilter === 'paid') return isPaid;
|
||||||
return !isPaid;
|
return !isPaid;
|
||||||
});
|
});
|
||||||
@@ -70,11 +98,13 @@ export default function RecordsPage() {
|
|||||||
<div className="shop-records-main">
|
<div className="shop-records-main">
|
||||||
<nav className="shop-records-filters">
|
<nav className="shop-records-filters">
|
||||||
<div className="shop-records-range-tabs">
|
<div className="shop-records-range-tabs">
|
||||||
{([
|
{(
|
||||||
['today', '今日'],
|
[
|
||||||
['7d', '近7日'],
|
['today', '今日'],
|
||||||
['30d', '近30日'],
|
['7d', '近7日'],
|
||||||
] as const).map(([key, label]) => (
|
['30d', '近30日'],
|
||||||
|
] as const
|
||||||
|
).map(([key, label]) => (
|
||||||
<button
|
<button
|
||||||
key={key}
|
key={key}
|
||||||
type="button"
|
type="button"
|
||||||
@@ -85,21 +115,35 @@ export default function RecordsPage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="shop-records-status-chips">
|
<div className="shop-records-status-row">
|
||||||
{([
|
<div className="shop-records-status-chips">
|
||||||
['all', '全部'],
|
{(
|
||||||
['pending', '待打款'],
|
[
|
||||||
['paid', '已打款'],
|
['all', '全部'],
|
||||||
] as const).map(([key, label]) => (
|
['pending', '待打款'],
|
||||||
<button
|
['paid', '已打款'],
|
||||||
key={key}
|
] as const
|
||||||
type="button"
|
).map(([key, label]) => (
|
||||||
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
<button
|
||||||
onClick={() => setStatusFilter(key)}
|
key={key}
|
||||||
>
|
type="button"
|
||||||
{label}
|
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
||||||
</button>
|
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>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
@@ -115,7 +159,10 @@ export default function RecordsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="shop-records-summary-note">
|
<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
|
check_circle
|
||||||
</span>
|
</span>
|
||||||
结算比例: {summary.rate}% (按{summary.rate / 10}折结算)
|
结算比例: {summary.rate}% (按{summary.rate / 10}折结算)
|
||||||
@@ -134,17 +181,32 @@ export default function RecordsPage() {
|
|||||||
{filtered.map((r) => {
|
{filtered.map((r) => {
|
||||||
const amount = Number(r.amount || 0);
|
const amount = Number(r.amount || 0);
|
||||||
const settle = Number(r.settleAmount || 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 (
|
return (
|
||||||
<article key={String(r.id)} className="shop-record-card">
|
<article key={String(r.id)} className="shop-record-card">
|
||||||
<div className="shop-record-card-top">
|
<div className="shop-record-card-top">
|
||||||
<div>
|
<div>
|
||||||
<div className="shop-record-order">
|
<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>
|
<span>{r.redeemNo ? String(r.redeemNo) : '—'}</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="shop-record-time">
|
<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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className={`shop-record-badge ${paid ? 'paid' : 'pending'}`}>
|
<span className={`shop-record-badge ${paid ? 'paid' : 'pending'}`}>
|
||||||
@@ -162,10 +224,16 @@ export default function RecordsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="shop-record-footer">
|
<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 && (
|
{storeName && (
|
||||||
<span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
<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}
|
{storeName}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -183,6 +251,80 @@ export default function RecordsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</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>
|
</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;
|
line-height: 1.1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.shop-home-stat-sub {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: rgba(255, 255, 255, 0.75);
|
||||||
|
}
|
||||||
|
|
||||||
.shop-home-scan {
|
.shop-home-scan {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -1549,18 +1555,42 @@
|
|||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.shop-records-status-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
.shop-records-status-chips {
|
.shop-records-status-chips {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
padding: 8px 16px;
|
padding: 0;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
scrollbar-width: none;
|
scrollbar-width: none;
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.shop-records-status-chips::-webkit-scrollbar {
|
.shop-records-status-chips::-webkit-scrollbar {
|
||||||
display: none;
|
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 {
|
.shop-records-chip {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
border: none;
|
border: none;
|
||||||
@@ -1578,6 +1608,142 @@
|
|||||||
color: var(--color-on-primary);
|
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 {
|
.shop-records-main {
|
||||||
padding-top: 0;
|
padding-top: 0;
|
||||||
}
|
}
|
||||||
@@ -1714,6 +1880,46 @@
|
|||||||
color: var(--color-aged-amber);
|
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 {
|
.shop-record-amounts {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: 1fr 1fr;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import './lib/intl-polyfill';
|
||||||
import './lib/text-encoding-polyfill';
|
import './lib/text-encoding-polyfill';
|
||||||
import { PropsWithChildren, useRef } from 'react';
|
import { PropsWithChildren, useRef } from 'react';
|
||||||
import Taro, { useDidShow } from '@tarojs/taro';
|
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 { ClientApp } from '@dukang/shared-types';
|
||||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||||
import { resetStoresSessionBootstrap } from './stores-session';
|
import { resetStoresSessionBootstrap } from './stores-session';
|
||||||
|
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||||
|
|
||||||
function resolveApiBase(): string {
|
function resolveApiBase(): string {
|
||||||
const origin =
|
const origin =
|
||||||
@@ -57,8 +58,9 @@ export function isLoggedIn(): boolean {
|
|||||||
|
|
||||||
export function logout() {
|
export function logout() {
|
||||||
clearAuth();
|
clearAuth();
|
||||||
// 主动退出才重置门店「当次登录」会话;401 清 token 不要打断门店筛选
|
// 主动退出才重置门店/首页「当次登录」会话;401 清 token 不要打断筛选
|
||||||
resetStoresSessionBootstrap();
|
resetStoresSessionBootstrap();
|
||||||
|
resetHomeCatalogBootstrap();
|
||||||
Taro.reLaunch({ url: '/pages/home/index' });
|
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> {
|
export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, string | number> {
|
||||||
const pagePad = 20;
|
const pagePad = 20;
|
||||||
|
// 标题两侧取「右侧避让胶囊」宽度,保证相对屏幕视觉居中
|
||||||
|
const titlePad = Math.max(metrics.navBarPaddingRight, 72);
|
||||||
return {
|
return {
|
||||||
paddingTop: `${metrics.statusBarHeight}px`,
|
paddingTop: `${metrics.statusBarHeight}px`,
|
||||||
height: `${metrics.navBarHeight}px`,
|
height: `${metrics.navBarHeight}px`,
|
||||||
@@ -113,7 +115,7 @@ export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, strin
|
|||||||
'--nav-content-height': `${metrics.navContentHeight}px`,
|
'--nav-content-height': `${metrics.navContentHeight}px`,
|
||||||
'--nav-status-bar-height': `${metrics.statusBarHeight}px`,
|
'--nav-status-bar-height': `${metrics.statusBarHeight}px`,
|
||||||
'--nav-padding-left': `${pagePad}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 = {
|
export type StoresListCache = {
|
||||||
cityKey: string;
|
cityKey: string;
|
||||||
cityCode: string;
|
cityCode: string;
|
||||||
|
/** 登录态指纹:token 变化时需重新拉取(白名单) */
|
||||||
|
authKey: string;
|
||||||
listRegion: StoresSessionRegion;
|
listRegion: StoresSessionRegion;
|
||||||
items: unknown[];
|
items: unknown[];
|
||||||
filterRegion: StoresSessionRegion;
|
filterRegion: StoresSessionRegion;
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { useCallback, useMemo, useState } from 'react';
|
|||||||
import { View, Text, Image } from '@tarojs/components';
|
import { View, Text, Image } from '@tarojs/components';
|
||||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import ShareNavButton from '../../components/ShareNavButton';
|
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
@@ -13,6 +12,7 @@ import {
|
|||||||
DEFAULT_SHARE_TITLE,
|
DEFAULT_SHARE_TITLE,
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
|
import { formatMoney } from '../../lib/money';
|
||||||
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
||||||
|
|
||||||
type BenefitSummary = {
|
type BenefitSummary = {
|
||||||
@@ -31,9 +31,13 @@ type CouponItem = {
|
|||||||
sourceProduct: string;
|
sourceProduct: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatMoney(amount: number) {
|
type RedeemHistoryItem = {
|
||||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
id: string;
|
||||||
}
|
redeemNo: string;
|
||||||
|
amount: number;
|
||||||
|
storeName: string;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
function usagePercent(coupon: CouponItem) {
|
function usagePercent(coupon: CouponItem) {
|
||||||
const total = Number(coupon.totalAmount);
|
const total = Number(coupon.totalAmount);
|
||||||
@@ -46,11 +50,13 @@ export default function BenefitPage() {
|
|||||||
const [loggedIn, setLoggedIn] = useState(() => isLoggedIn());
|
const [loggedIn, setLoggedIn] = useState(() => isLoggedIn());
|
||||||
const [summary, setSummary] = useState<BenefitSummary | null>(null);
|
const [summary, setSummary] = useState<BenefitSummary | null>(null);
|
||||||
const [coupons, setCoupons] = useState<CouponItem[]>([]);
|
const [coupons, setCoupons] = useState<CouponItem[]>([]);
|
||||||
|
const [redeemHistory, setRedeemHistory] = useState<RedeemHistoryItem[]>([]);
|
||||||
const [tab, setTab] = useState<'available' | 'history'>('available');
|
const [tab, setTab] = useState<'available' | 'history'>('available');
|
||||||
|
|
||||||
const resetGuestState = useCallback(() => {
|
const resetGuestState = useCallback(() => {
|
||||||
setSummary(null);
|
setSummary(null);
|
||||||
setCoupons([]);
|
setCoupons([]);
|
||||||
|
setRedeemHistory([]);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const loadBenefit = useCallback(() => {
|
const loadBenefit = useCallback(() => {
|
||||||
@@ -58,10 +64,17 @@ export default function BenefitPage() {
|
|||||||
return Promise.all([
|
return Promise.all([
|
||||||
request<BenefitSummary>('/benefit/summary'),
|
request<BenefitSummary>('/benefit/summary'),
|
||||||
request<CouponItem[]>('/benefit/coupons'),
|
request<CouponItem[]>('/benefit/coupons'),
|
||||||
|
request<{ list?: RedeemHistoryItem[] } | RedeemHistoryItem[]>('/redeem/records?page=1&pageSize=50'),
|
||||||
])
|
])
|
||||||
.then(([s, list]) => {
|
.then(([s, list, records]) => {
|
||||||
setSummary(s);
|
setSummary(s);
|
||||||
setCoupons(Array.isArray(list) ? list : []);
|
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 : '加载失败'));
|
.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 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(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
@@ -123,9 +134,6 @@ export default function BenefitPage() {
|
|||||||
<View className="benefit-header-city-pin" />
|
<View className="benefit-header-city-pin" />
|
||||||
<Text>郑州市</Text>
|
<Text>郑州市</Text>
|
||||||
</View>
|
</View>
|
||||||
<View className="benefit-header__share page-nav-bar__right-slot">
|
|
||||||
<ShareNavButton payload={sharePayload} />
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
@@ -180,26 +188,26 @@ export default function BenefitPage() {
|
|||||||
</Text>
|
</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{visible.length === 0 ? (
|
{tab === 'available' ? (
|
||||||
<View className="u-empty">{tab === 'available' ? '暂无可用权益' : '暂无历史记录'}</View>
|
available.length === 0 ? (
|
||||||
) : (
|
<View className="u-empty">暂无可用权益</View>
|
||||||
visible.map((c) => (
|
) : (
|
||||||
<View key={c.id} className="benefit-coupon">
|
available.map((c) => (
|
||||||
<View className="benefit-coupon-notch" />
|
<View key={c.id} className="benefit-coupon">
|
||||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
<View className="benefit-coupon-notch" />
|
||||||
<View className="benefit-coupon-head">
|
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||||
<Text className="benefit-coupon-name">{c.sourceProduct || '好客权益'}</Text>
|
<View className="benefit-coupon-head">
|
||||||
<Text className="benefit-coupon-balance">¥{formatMoney(c.balance)}</Text>
|
<Text className="benefit-coupon-name">{c.sourceProduct || '好客权益'}</Text>
|
||||||
</View>
|
<Text className="benefit-coupon-balance">¥{formatMoney(c.balance)}</Text>
|
||||||
<Text className="benefit-coupon-no">NO. {c.couponNo}</Text>
|
</View>
|
||||||
<View className="benefit-progress">
|
<Text className="benefit-coupon-no">NO. {c.couponNo}</Text>
|
||||||
<View className="benefit-progress-bar" style={{ width: `${usagePercent(c)}%` }} />
|
<View className="benefit-progress">
|
||||||
</View>
|
<View className="benefit-progress-bar" style={{ width: `${usagePercent(c)}%` }} />
|
||||||
<View className="benefit-coupon-footer">
|
</View>
|
||||||
<Text className="benefit-coupon-meta">
|
<View className="benefit-coupon-footer">
|
||||||
已用 ¥{formatMoney(c.usedAmount)} / 总额 ¥{formatMoney(c.totalAmount)}
|
<Text className="benefit-coupon-meta">
|
||||||
</Text>
|
已用 ¥{formatMoney(c.usedAmount)} / 总额 ¥{formatMoney(c.totalAmount)}
|
||||||
{tab === 'available' ? (
|
</Text>
|
||||||
<Text
|
<Text
|
||||||
className="benefit-coupon-btn"
|
className="benefit-coupon-btn"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
@@ -210,7 +218,26 @@ export default function BenefitPage() {
|
|||||||
>
|
>
|
||||||
立即核销
|
立即核销
|
||||||
</Text>
|
</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>
|
||||||
</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 { 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 PageShell from '../../components/PageShell';
|
||||||
import TabMainHeader from '../../components/TabMainHeader';
|
import TabMainHeader from '../../components/TabMainHeader';
|
||||||
import CouponBadge from '../../components/CouponBadge';
|
import CouponBadge from '../../components/CouponBadge';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
import { 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 { ensurePayReady } from '../../lib/pay-ready';
|
||||||
import { capturePromoSceneAndTouchScan } from '../../lib/promo';
|
import { capturePromoSceneAndTouchScan } from '../../lib/promo';
|
||||||
import { getProductMainImage } from '../../lib/product-images';
|
import { getProductMainImage } from '../../lib/product-images';
|
||||||
|
import {
|
||||||
|
canBuyOnline,
|
||||||
|
canCrossCity,
|
||||||
|
canPickupOnSite,
|
||||||
|
normalizeFulfillmentFlags,
|
||||||
|
} from '../../lib/product-fulfillment';
|
||||||
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
DEFAULT_SHARE_TITLE,
|
DEFAULT_SHARE_TITLE,
|
||||||
toWeappShareMessage,
|
toWeappShareMessage,
|
||||||
} from '../../lib/wechat-share';
|
} from '../../lib/wechat-share';
|
||||||
|
|
||||||
type Product = {
|
type Product = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -29,8 +45,26 @@ type Product = {
|
|||||||
carouselUrls?: string[] | null;
|
carouselUrls?: string[] | null;
|
||||||
aromaType: string;
|
aromaType: string;
|
||||||
allowOnSitePickup?: boolean;
|
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 = {
|
type MiniHomeConfig = {
|
||||||
banners: string[];
|
banners: string[];
|
||||||
footerUrl: string | null;
|
footerUrl: string | null;
|
||||||
@@ -42,13 +76,26 @@ const AROMA_TABS = [
|
|||||||
{ key: 'NONGXIANG', label: '浓香型' },
|
{ key: 'NONGXIANG', label: '浓香型' },
|
||||||
] as const;
|
] 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() {
|
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 [products, setProducts] = useState<Product[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [displayCity, setDisplayCity] = useState('郑州市');
|
const [displayCity, setDisplayCity] = useState('郑州市');
|
||||||
const [cityCode, setCityCode] = useState('410100');
|
const [cityCode, setCityCode] = useState('410100');
|
||||||
const [miniHome, setMiniHome] = useState<MiniHomeConfig>({ banners: [], footerUrl: null });
|
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(() => {
|
const loadMiniHome = useCallback(() => {
|
||||||
return request<{ miniHome?: MiniHomeConfig }>('/common/client-config')
|
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(() => {
|
useDidShow(() => {
|
||||||
syncTabBarSelected(0);
|
syncTabBarSelected(0);
|
||||||
void capturePromoSceneAndTouchScan();
|
void capturePromoSceneAndTouchScan();
|
||||||
void loadMiniHome();
|
void loadMiniHome();
|
||||||
void resolveUserCity().then((resolved) => {
|
|
||||||
|
const authKey = getToken() || '';
|
||||||
|
void (async () => {
|
||||||
|
const resolved = await resolveUserCity();
|
||||||
|
const nextCode = getCityCodeForCatalog(resolved);
|
||||||
setDisplayCity(resolved.displayCity);
|
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(() => {
|
usePullDownRefresh(() => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
|
const authKey = getToken() || '';
|
||||||
const resolved = await resolveUserCity();
|
const resolved = await resolveUserCity();
|
||||||
setDisplayCity(resolved.displayCity);
|
setDisplayCity(resolved.displayCity);
|
||||||
const nextCode = getCityCodeForCatalog(resolved);
|
const nextCode = getCityCodeForCatalog(resolved);
|
||||||
@@ -101,7 +177,11 @@ export default function HomePage() {
|
|||||||
request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
|
request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
|
||||||
loadMiniHome(),
|
loadMiniHome(),
|
||||||
]);
|
]);
|
||||||
setProducts(Array.isArray(list) ? list : []);
|
applyProductList(
|
||||||
|
Array.isArray(list) ? list : [],
|
||||||
|
nextCode,
|
||||||
|
authKey,
|
||||||
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast(e instanceof Error ? e.message : '加载失败');
|
toast(e instanceof Error ? e.message : '加载失败');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -110,7 +190,6 @@ export default function HomePage() {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
});
|
});
|
||||||
|
|
||||||
function openProductDetail(id: string) {
|
function openProductDetail(id: string) {
|
||||||
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
||||||
}
|
}
|
||||||
@@ -126,7 +205,24 @@ export default function HomePage() {
|
|||||||
Taro.navigateTo({ url: returnPath });
|
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 banners = miniHome.banners;
|
||||||
const footerUrl = miniHome.footerUrl;
|
const footerUrl = miniHome.footerUrl;
|
||||||
|
|
||||||
@@ -147,6 +243,102 @@ export default function HomePage() {
|
|||||||
imageUrl: sharePayload.imgUrl,
|
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 (
|
return (
|
||||||
<PageShell variant="tab" className="home-page no-tab-header">
|
<PageShell variant="tab" className="home-page no-tab-header">
|
||||||
<WechatShareReady payload={sharePayload} />
|
<WechatShareReady payload={sharePayload} />
|
||||||
@@ -175,8 +367,8 @@ export default function HomePage() {
|
|||||||
{AROMA_TABS.map((t) => (
|
{AROMA_TABS.map((t) => (
|
||||||
<Text
|
<Text
|
||||||
key={t.key}
|
key={t.key}
|
||||||
className={`home-aroma-tab${tab === t.key ? ' home-aroma-tab--active' : ''}`}
|
className={`home-aroma-tab${activeAroma === t.key ? ' home-aroma-tab--active' : ''}`}
|
||||||
onClick={() => setTab(t.key)}
|
onClick={() => scrollToAroma(t.key)}
|
||||||
>
|
>
|
||||||
{t.label}
|
{t.label}
|
||||||
</Text>
|
</Text>
|
||||||
@@ -185,64 +377,38 @@ export default function HomePage() {
|
|||||||
<Text className="home-aroma-city">{displayCity}</Text>
|
<Text className="home-aroma-city">{displayCity}</Text>
|
||||||
</View>
|
</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">
|
<View className="home-product-list">
|
||||||
{loading ? <View className="home-empty">加载中…</View> : null}
|
{loading ? <View className="home-empty">加载中…</View> : null}
|
||||||
{!loading && products.length === 0 ? (
|
{!loading && products.length === 0 ? (
|
||||||
<View className="home-empty">当前城市暂无在售商品</View>
|
<View className="home-empty">当前城市暂无在售商品</View>
|
||||||
) : null}
|
) : null}
|
||||||
{!loading && products.length > 0 && filtered.length === 0 ? (
|
{!loading && products.length > 0 && filteredProducts.length === 0 ? (
|
||||||
<View className="home-empty">该香型暂未上线</View>
|
<View className="home-empty">暂无符合履约方式的商品</View>
|
||||||
) : null}
|
) : null}
|
||||||
{!loading &&
|
{!loading &&
|
||||||
filtered.map((p) => {
|
filteredProducts.length > 0 &&
|
||||||
const thumb = getProductMainImage(p);
|
AROMA_TABS.map((t) => {
|
||||||
const spec = p.subtitle || p.spec || '';
|
const list = productsByAroma[t.key];
|
||||||
return (
|
return (
|
||||||
<View key={p.id} className="home-product-card">
|
<View key={t.key} id={aromaSectionId(t.key)} className="home-aroma-section">
|
||||||
<View
|
<Text className="home-aroma-section-title">{t.label}</Text>
|
||||||
className="home-product-card-inner"
|
{list.length === 0 ? (
|
||||||
onClick={() => openProductDetail(p.id)}
|
<View className="home-empty home-empty--section">该香型暂未上线</View>
|
||||||
>
|
) : (
|
||||||
<View className="home-product-thumb-wrap">
|
list.map((p) => renderProductCard(p))
|
||||||
{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>
|
</View>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import iconStores from '../../assets/icons/可用门店.png';
|
|||||||
import iconCs from '../../assets/icons/联系客服.png';
|
import iconCs from '../../assets/icons/联系客服.png';
|
||||||
import iconQualification from '../../assets/icons/资质公示.png';
|
import iconQualification from '../../assets/icons/资质公示.png';
|
||||||
import iconAbout from '../../assets/icons/关于我们.png';
|
import iconAbout from '../../assets/icons/关于我们.png';
|
||||||
|
import { formatMoney } from '../../lib/money';
|
||||||
|
|
||||||
const ORDER_SHORTCUTS = [
|
const ORDER_SHORTCUTS = [
|
||||||
{ tab: 'pending_pay', icon: iconPendingPay, label: '待付款' },
|
{ tab: 'pending_pay', icon: iconPendingPay, label: '待付款' },
|
||||||
@@ -54,10 +55,6 @@ const SERVICES = [
|
|||||||
|
|
||||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||||
|
|
||||||
function formatMoney(amount: number) {
|
|
||||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function MinePage() {
|
export default function MinePage() {
|
||||||
const [authed, setAuthed] = useState(() => isLoggedIn());
|
const [authed, setAuthed] = useState(() => isLoggedIn());
|
||||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||||
@@ -221,7 +218,10 @@ export default function MinePage() {
|
|||||||
|
|
||||||
/** 点击头像:绑定账号后用 chooseAvatar + nickname 获取头像昵称 */
|
/** 点击头像:绑定账号后用 chooseAvatar + nickname 获取头像昵称 */
|
||||||
async function handleAvatarTap() {
|
async function handleAvatarTap() {
|
||||||
if (bindingWx || savingProfile) return;
|
if (bindingWx || savingProfile) {
|
||||||
|
toast(savingProfile ? '资料保存中…' : '请稍候…');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!isLoggedIn()) {
|
if (!isLoggedIn()) {
|
||||||
goLogin('/pages/mine/index');
|
goLogin('/pages/mine/index');
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { goLogin } from '../../lib/auth-nav';
|
|||||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||||
import { ensurePayReady } from '../../lib/pay-ready';
|
import { ensurePayReady } from '../../lib/pay-ready';
|
||||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||||
import { request } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
import { getProductMainImage } from '../../lib/product-images';
|
import { getProductMainImage } from '../../lib/product-images';
|
||||||
|
|
||||||
type PreviewProduct = {
|
type PreviewProduct = {
|
||||||
@@ -75,7 +75,14 @@ export default function OrderConfirmPickupPage() {
|
|||||||
const canSubmit = !!preview && quantityOk && !loading && !previewLoading;
|
const canSubmit = !!preview && quantityOk && !loading && !previewLoading;
|
||||||
|
|
||||||
function updateQuantity(next: number) {
|
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);
|
setQuantity(next);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,8 +102,12 @@ export default function OrderConfirmPickupPage() {
|
|||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
if (!canSubmit) {
|
if (!canSubmit) {
|
||||||
if (!quantityOk) setMsg(`现场提货至少购买 ${minQty} 瓶`);
|
if (!quantityOk) {
|
||||||
return;
|
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||||
|
setMsg(tip);
|
||||||
|
toast(tip);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=${quantity}`;
|
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=${quantity}`;
|
||||||
@@ -185,8 +196,8 @@ export default function OrderConfirmPickupPage() {
|
|||||||
<Text>购买数量</Text>
|
<Text>购买数量</Text>
|
||||||
<View className="order-qty-controls">
|
<View className="order-qty-controls">
|
||||||
<View
|
<View
|
||||||
className={`order-qty-btn${quantity <= minQty ? ' order-qty-btn--disabled' : ''}`}
|
className="order-qty-btn"
|
||||||
onClick={() => updateQuantity(Math.max(minQty, quantity - 1))}
|
onClick={() => updateQuantity(quantity - 1)}
|
||||||
>
|
>
|
||||||
<Text>−</Text>
|
<Text>−</Text>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import { tryGetClientGpsLocation } from '../../lib/client-location';
|
|||||||
import { maskPhone } from '../../lib/phone';
|
import { maskPhone } from '../../lib/phone';
|
||||||
import { ensurePayReady } from '../../lib/pay-ready';
|
import { ensurePayReady } from '../../lib/pay-ready';
|
||||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||||
import { request } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
||||||
import { getProductMainImage } from '../../lib/product-images';
|
import { getProductMainImage } from '../../lib/product-images';
|
||||||
|
|
||||||
type Address = {
|
type Address = {
|
||||||
@@ -31,6 +32,8 @@ type PreviewProduct = {
|
|||||||
price: number;
|
price: number;
|
||||||
mainImageUrl?: string | null;
|
mainImageUrl?: string | null;
|
||||||
carouselUrls?: string[] | null;
|
carouselUrls?: string[] | null;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type OrderPreview = {
|
type OrderPreview = {
|
||||||
@@ -41,12 +44,18 @@ type OrderPreview = {
|
|||||||
freightPayType: 'COD' | null;
|
freightPayType: 'COD' | null;
|
||||||
payAmount: number;
|
payAmount: number;
|
||||||
benefitAmount: number;
|
benefitAmount: number;
|
||||||
city?: { localMinQty: number; crossMinQty: number };
|
city?: { name?: string; localMinQty: number; crossMinQty: number };
|
||||||
quantityOk?: boolean;
|
quantityOk?: boolean;
|
||||||
quantityMessage?: string | null;
|
quantityMessage?: string | null;
|
||||||
|
addressOk?: boolean;
|
||||||
|
addressMessage?: string | null;
|
||||||
minQty?: number;
|
minQty?: number;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const CROSS_CITY_BLOCK_MSG = '该商品不支持跨城配送,请更换为开城城市内的收货地址';
|
||||||
|
|
||||||
function formatAddress(a: Address) {
|
function formatAddress(a: Address) {
|
||||||
return `${a.province}${a.city}${a.district}${a.detail}`;
|
return `${a.province}${a.city}${a.district}${a.detail}`;
|
||||||
}
|
}
|
||||||
@@ -64,6 +73,7 @@ export default function OrderConfirmPage() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [msg, setMsg] = useState('');
|
const [msg, setMsg] = useState('');
|
||||||
const phonePromptSkipped = useRef(false);
|
const phonePromptSkipped = useRef(false);
|
||||||
|
const toastedAddressBlockRef = useRef('');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
request<Address[]>('/user/addresses')
|
request<Address[]>('/user/addresses')
|
||||||
@@ -94,7 +104,24 @@ export default function OrderConfirmPage() {
|
|||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
setPreview(data);
|
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) => {
|
.catch((e) => {
|
||||||
@@ -117,15 +144,39 @@ export default function OrderConfirmPage() {
|
|||||||
[addresses, addressId],
|
[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 =
|
const minQty =
|
||||||
preview?.minQty ??
|
preview?.minQty ??
|
||||||
(isCross ? (preview?.city?.crossMinQty ?? 6) : (preview?.city?.localMinQty ?? 2));
|
(isCross ? (preview?.city?.crossMinQty ?? 6) : (preview?.city?.localMinQty ?? 2));
|
||||||
const quantityOk = preview ? preview.quantityOk !== false && quantity >= minQty : false;
|
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) {
|
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);
|
setQuantity(next);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,12 +213,18 @@ export default function OrderConfirmPage() {
|
|||||||
setMsg('请选择收货地址');
|
setMsg('请选择收货地址');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!addressOk) {
|
||||||
|
const tip = addressHint || CROSS_CITY_BLOCK_MSG;
|
||||||
|
setMsg(tip);
|
||||||
|
toast(tip);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!quantityOk) {
|
if (!quantityOk) {
|
||||||
setMsg(
|
const tip = isCross
|
||||||
isCross
|
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
: `同城配送至少购买 ${minQty} 瓶`;
|
||||||
: `同城配送至少购买 ${minQty} 瓶`,
|
setMsg(tip);
|
||||||
);
|
toast(tip);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -219,9 +276,12 @@ export default function OrderConfirmPage() {
|
|||||||
? '提交中…'
|
? '提交中…'
|
||||||
: !addressId
|
: !addressId
|
||||||
? '请选择地址'
|
? '请选择地址'
|
||||||
: !quantityOk
|
: !addressOk
|
||||||
? `至少购买 ${minQty} 瓶`
|
? '请更换地址'
|
||||||
: '提交订单';
|
: !quantityOk
|
||||||
|
? `至少购买 ${minQty} 瓶`
|
||||||
|
: '提交订单';
|
||||||
|
const displayMsg = msg || addressHint;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="sub" className="order-confirm-page" hasFixedFooter>
|
<PageShell variant="sub" className="order-confirm-page" hasFixedFooter>
|
||||||
@@ -254,7 +314,13 @@ export default function OrderConfirmPage() {
|
|||||||
)}
|
)}
|
||||||
</View>
|
</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">
|
<View className="order-card">
|
||||||
<Text className="u-muted">
|
<Text className="u-muted">
|
||||||
该地址超出同城配送范围,将由总部物流发货,运费到付
|
该地址超出同城配送范围,将由总部物流发货,运费到付
|
||||||
@@ -286,7 +352,7 @@ export default function OrderConfirmPage() {
|
|||||||
<Text>购买数量</Text>
|
<Text>购买数量</Text>
|
||||||
<View className="order-qty-controls">
|
<View className="order-qty-controls">
|
||||||
<View
|
<View
|
||||||
className={`order-qty-btn${quantity <= 1 ? ' order-qty-btn--disabled' : ''}`}
|
className="order-qty-btn"
|
||||||
onClick={() => updateQuantity(quantity - 1)}
|
onClick={() => updateQuantity(quantity - 1)}
|
||||||
>
|
>
|
||||||
<Text>−</Text>
|
<Text>−</Text>
|
||||||
@@ -333,9 +399,9 @@ export default function OrderConfirmPage() {
|
|||||||
{!previewLoading && !preview && productId ? (
|
{!previewLoading && !preview && productId ? (
|
||||||
<View className="u-empty">无法加载商品信息</View>
|
<View className="u-empty">无法加载商品信息</View>
|
||||||
) : null}
|
) : null}
|
||||||
{msg ? (
|
{displayMsg ? (
|
||||||
<Text className="u-muted" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
<Text className="order-warn-text" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
||||||
{msg}
|
{displayMsg}
|
||||||
</Text>
|
</Text>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -180,6 +180,17 @@ export default function OrderDetailPage() {
|
|||||||
<WechatShareReady payload={sharePayload} />
|
<WechatShareReady payload={sharePayload} />
|
||||||
<SubPageHeader
|
<SubPageHeader
|
||||||
title="订单详情"
|
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} />}
|
right={<ShareNavButton payload={sharePayload} />}
|
||||||
/>
|
/>
|
||||||
<View className="sub-page-body">
|
<View className="sub-page-body">
|
||||||
|
|||||||
@@ -93,7 +93,14 @@ export default function OrdersPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<PageShell variant="sub" className="orders-page">
|
<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">
|
<View className="order-tabs">
|
||||||
{TABS.map((t) => (
|
{TABS.map((t) => (
|
||||||
<Text
|
<Text
|
||||||
|
|||||||
@@ -144,10 +144,10 @@ export default function PayPage() {
|
|||||||
toast('支付成功', 'success');
|
toast('支付成功', 'success');
|
||||||
}
|
}
|
||||||
if (deliveryType === 'ON_SITE_PICKUP') {
|
if (deliveryType === 'ON_SITE_PICKUP') {
|
||||||
// 现场提货支付即完成 → 订单详情(已完成)
|
// 现场提货支付即完成 → 订单详情;from=pay 返回强制回首页,避免 navigateBack 退出小程序
|
||||||
Taro.redirectTo({ url: `/pages/order-detail/index?id=${orderId}` });
|
Taro.reLaunch({ url: `/pages/order-detail/index?id=${orderId}&from=pay` });
|
||||||
} else {
|
} else {
|
||||||
Taro.redirectTo({ url: '/pages/orders/index?tab=paid' });
|
Taro.reLaunch({ url: '/pages/orders/index?tab=paid&from=pay' });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isWechatAuthRequiredError(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 { 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 type { ProductDetailContentDto } from '@dukang/shared-types';
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import PageNavBar from '../../components/PageNavBar';
|
import PageNavBar from '../../components/PageNavBar';
|
||||||
@@ -16,6 +22,11 @@ import {
|
|||||||
getProductMainImage,
|
getProductMainImage,
|
||||||
type ProductImageSource,
|
type ProductImageSource,
|
||||||
} from '../../lib/product-images';
|
} from '../../lib/product-images';
|
||||||
|
import {
|
||||||
|
canBuyOnline,
|
||||||
|
canPickupOnSite,
|
||||||
|
normalizeFulfillmentFlags,
|
||||||
|
} from '../../lib/product-fulfillment';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
DEFAULT_SHARE_TITLE,
|
DEFAULT_SHARE_TITLE,
|
||||||
@@ -31,6 +42,9 @@ type Product = ProductImageSource & {
|
|||||||
benefitAmount?: number;
|
benefitAmount?: number;
|
||||||
benefitDisplay?: number;
|
benefitDisplay?: number;
|
||||||
detailContent?: ProductDetailContentDto | null;
|
detailContent?: ProductDetailContentDto | null;
|
||||||
|
allowOnSitePickup?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function ProductDetailPage() {
|
export default function ProductDetailPage() {
|
||||||
@@ -43,13 +57,32 @@ export default function ProductDetailPage() {
|
|||||||
setHeaderSolid(scrollTop > 100);
|
setHeaderSolid(scrollTop > 100);
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
const loadProduct = useCallback(() => {
|
||||||
if (!productId) return;
|
if (!productId) return;
|
||||||
request<Product>(`/catalog/products/${productId}`)
|
request<Product | null>(`/catalog/products/${productId}`)
|
||||||
.then(setProduct)
|
.then((p) => {
|
||||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
if (!p) {
|
||||||
|
setProduct(null);
|
||||||
|
toast('商品不存在或暂未开放');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setProduct(normalizeFulfillmentFlags(p));
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
setProduct(null);
|
||||||
|
toast(e instanceof Error ? e.message : '加载失败');
|
||||||
|
});
|
||||||
}, [productId]);
|
}, [productId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadProduct();
|
||||||
|
}, [loadProduct]);
|
||||||
|
|
||||||
|
// 登录后返回详情须带 token 重拉,否则白名单商品会一直空白
|
||||||
|
useDidShow(() => {
|
||||||
|
loadProduct();
|
||||||
|
});
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
title: product?.name || DEFAULT_SHARE_TITLE,
|
title: product?.name || DEFAULT_SHARE_TITLE,
|
||||||
@@ -92,6 +125,18 @@ export default function ProductDetailPage() {
|
|||||||
Taro.navigateTo({ url: returnPath });
|
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) {
|
if (!product) {
|
||||||
return (
|
return (
|
||||||
<PageShell variant="scroll" className="product-detail-page">
|
<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 benefit = Number(product.benefitDisplay ?? product.benefitAmount ?? product.price);
|
||||||
const carouselImages = getProductCarouselImages(product);
|
const carouselImages = getProductCarouselImages(product);
|
||||||
const detailImages = getProductDetailImages(product);
|
const detailImages = getProductDetailImages(product);
|
||||||
@@ -199,9 +246,21 @@ export default function ProductDetailPage() {
|
|||||||
<Image className="product-detail-bar-home-icon" src={iconHome} mode="aspectFit" />
|
<Image className="product-detail-bar-home-icon" src={iconHome} mode="aspectFit" />
|
||||||
<Text className="product-detail-bar-home-label">首页</Text>
|
<Text className="product-detail-bar-home-label">首页</Text>
|
||||||
</View>
|
</View>
|
||||||
<View className="product-detail-buy-btn" onClick={() => void goBuy()}>
|
{allowOnSite ? (
|
||||||
<Text className="product-detail-buy-btn-text">立即购买</Text>
|
<View className="product-detail-pickup-btn" onClick={() => void goOnSitePickup()}>
|
||||||
</View>
|
<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>
|
</View>
|
||||||
</PageShell>
|
</PageShell>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import PageShell from '../../components/PageShell';
|
|||||||
import RedeemQrCode from '../../components/RedeemQrCode';
|
import RedeemQrCode from '../../components/RedeemQrCode';
|
||||||
import SubPageHeader from '../../components/SubPageHeader';
|
import SubPageHeader from '../../components/SubPageHeader';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import { formatMoney } from '../../lib/money';
|
||||||
|
|
||||||
const POLL_INTERVAL_MS = 2500;
|
const POLL_INTERVAL_MS = 2500;
|
||||||
const LAST_REDEEM_RECORD_KEY = 'lastRedeemRecordId';
|
const LAST_REDEEM_RECORD_KEY = 'lastRedeemRecordId';
|
||||||
@@ -26,10 +27,6 @@ type RedeemTokenStatus =
|
|||||||
}
|
}
|
||||||
| { status: 'EXPIRED' };
|
| { status: 'EXPIRED' };
|
||||||
|
|
||||||
function formatMoney(amount: number) {
|
|
||||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTimer(seconds: number) {
|
function formatTimer(seconds: number) {
|
||||||
const mins = Math.floor(seconds / 60);
|
const mins = Math.floor(seconds / 60);
|
||||||
const secs = seconds % 60;
|
const secs = seconds % 60;
|
||||||
@@ -44,6 +41,20 @@ export default function RedeemCodePage() {
|
|||||||
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
||||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
const successHandled = useRef(false);
|
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(() => {
|
const stopTimer = useCallback(() => {
|
||||||
if (timerRef.current != null) {
|
if (timerRef.current != null) {
|
||||||
@@ -144,9 +155,10 @@ export default function RedeemCodePage() {
|
|||||||
<Text className="u-muted">待核销金额</Text>
|
<Text className="u-muted">待核销金额</Text>
|
||||||
<Text className="redeem-code-amount">¥ {formatMoney(amount)}</Text>
|
<Text className="redeem-code-amount">¥ {formatMoney(amount)}</Text>
|
||||||
{token ? (
|
{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-label">核销码编号(供追查)</Text>
|
||||||
<Text className="redeem-code-token">{token}</Text>
|
<Text className="redeem-code-token">{token}</Text>
|
||||||
|
<Text className="redeem-code-token-hint">双击复制</Text>
|
||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { View, Text } from '@tarojs/components';
|
import { View, Text } from '@tarojs/components';
|
||||||
import Taro, { useRouter } from '@tarojs/taro';
|
import Taro, { useRouter } from '@tarojs/taro';
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import SubPageHeader from '../../components/SubPageHeader';
|
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';
|
const LAST_REDEEM_RESULT_KEY = 'lastRedeemResult';
|
||||||
|
|
||||||
@@ -15,12 +18,43 @@ type RedeemRecord = {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatMoney(amount: number) {
|
/** 与权益「历史记录」一致:2026-08-03 13:53:03(Asia/Shanghai) */
|
||||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
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() {
|
export default function RedeemSuccessPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const [serviceScore, setServiceScore] = useState(5);
|
||||||
|
const [envScore, setEnvScore] = useState(5);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
const record = useMemo<RedeemRecord | null>(() => {
|
const record = useMemo<RedeemRecord | null>(() => {
|
||||||
try {
|
try {
|
||||||
@@ -34,18 +68,51 @@ export default function RedeemSuccessPage() {
|
|||||||
const amount = Number(record?.amount ?? router.params.amount ?? 0);
|
const amount = Number(record?.amount ?? router.params.amount ?? 0);
|
||||||
const storeName = record?.storeName || '门店';
|
const storeName = record?.storeName || '门店';
|
||||||
const redeemNo = record?.redeemNo || '—';
|
const redeemNo = record?.redeemNo || '—';
|
||||||
const redeemedAt = record?.createdAt
|
const redeemedAt = formatChinaDateTime(record?.createdAt);
|
||||||
? new Date(record.createdAt).toLocaleString('zh-CN')
|
|
||||||
: new Date().toLocaleString('zh-CN');
|
function clearCache() {
|
||||||
|
try {
|
||||||
|
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function goBenefit() {
|
function goBenefit() {
|
||||||
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
clearCache();
|
||||||
Taro.switchTab({ url: '/pages/benefit/index' });
|
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 (
|
return (
|
||||||
<PageShell variant="sub" className="redeem-success-page">
|
<PageShell variant="sub" className="redeem-success-page">
|
||||||
<SubPageHeader title="核销成功" />
|
<SubPageHeader title="核销成功" onBack={goBenefit} />
|
||||||
<View className="sub-page-body">
|
<View className="sub-page-body">
|
||||||
<View className="redeem-success-icon">
|
<View className="redeem-success-icon">
|
||||||
<Text>✓</Text>
|
<Text>✓</Text>
|
||||||
@@ -69,14 +136,21 @@ export default function RedeemSuccessPage() {
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="redeem-submit" onClick={goBenefit}>
|
<View className="redeem-success-rating">
|
||||||
<Text>返回权益</Text>
|
<Text className="redeem-success-rating-title">为门店服务评分</Text>
|
||||||
|
<StarRating label="服务态度" value={serviceScore} onChange={setServiceScore} />
|
||||||
|
<StarRating label="用餐环境" value={envScore} onChange={setEnvScore} />
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View
|
<View
|
||||||
className="u-btn u-btn--ghost u-btn--block"
|
className={`redeem-submit${loading ? ' redeem-submit--disabled' : ''}`}
|
||||||
style={{ margin: '0 20px', boxSizing: 'border-box' }}
|
onClick={() => {
|
||||||
onClick={() => Taro.switchTab({ url: '/pages/home/index' })}
|
if (!loading) void submitRatingAndFinish();
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
|
<Text>{loading ? '提交中…' : '提交评价并返回'}</Text>
|
||||||
|
</View>
|
||||||
|
<View className="redeem-cancel-btn" onClick={goHome}>
|
||||||
<Text>回到首页</Text>
|
<Text>回到首页</Text>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import PageShell from '../../components/PageShell';
|
|||||||
import SubPageHeader from '../../components/SubPageHeader';
|
import SubPageHeader from '../../components/SubPageHeader';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||||
|
import { formatMoney } from '../../lib/money';
|
||||||
|
|
||||||
type BenefitSummary = {
|
type BenefitSummary = {
|
||||||
totalBalance: number;
|
totalBalance: number;
|
||||||
@@ -13,10 +14,6 @@ type BenefitSummary = {
|
|||||||
|
|
||||||
const MIN_REDEEM_AMOUNT = 0.01;
|
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 { 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 PageShell from '../../components/PageShell';
|
||||||
import PageNavBar from '../../components/PageNavBar';
|
import PageNavBar from '../../components/PageNavBar';
|
||||||
import ProductCarousel from '../../components/ProductCarousel';
|
import ProductCarousel from '../../components/ProductCarousel';
|
||||||
import ShareNavButton from '../../components/ShareNavButton';
|
import ShareNavButton from '../../components/ShareNavButton';
|
||||||
|
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
DEFAULT_SHARE_TITLE,
|
DEFAULT_SHARE_TITLE,
|
||||||
@@ -43,6 +52,13 @@ type Store = {
|
|||||||
category?: { name: string } | null;
|
category?: { name: string } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type RecentRedeem = {
|
||||||
|
userLabel: string;
|
||||||
|
amount: number | string;
|
||||||
|
createdAt: string;
|
||||||
|
text?: string;
|
||||||
|
};
|
||||||
|
|
||||||
function uniqueUrls(urls: Array<string | null | undefined>) {
|
function uniqueUrls(urls: Array<string | null | undefined>) {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const out: string[] = [];
|
const out: string[] = [];
|
||||||
@@ -68,30 +84,145 @@ function fullAddress(store: Store) {
|
|||||||
return `${store.province || ''}${city}${store.district || ''}${store.address || ''}`.trim();
|
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() {
|
export default function StoreDetailPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const storeId = router.params.id ?? '';
|
const [storeId, setStoreId] = useState(() => pickStoreId(router.params.id));
|
||||||
const [store, setStore] = useState<Store | null>(null);
|
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 [headerSolid, setHeaderSolid] = useState(false);
|
||||||
|
const storeRef = useRef<Store | null>(null);
|
||||||
|
storeRef.current = store;
|
||||||
|
|
||||||
usePageScroll(({ scrollTop }) => {
|
usePageScroll(({ scrollTop }) => {
|
||||||
setHeaderSolid(scrollTop > 100);
|
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(() => {
|
useEffect(() => {
|
||||||
if (!storeId) return;
|
const fromRouter = pickStoreId(router.params.id);
|
||||||
request<Store>(`/stores/${storeId}`)
|
if (fromRouter && fromRouter !== storeId) {
|
||||||
.then(setStore)
|
bootstrap(fromRouter);
|
||||||
.catch(() => {
|
}
|
||||||
request<Store[]>('/stores')
|
}, [router.params.id, storeId, bootstrap]);
|
||||||
.then((list) => {
|
|
||||||
const found = (Array.isArray(list) ? list : []).find((s) => s.id === storeId);
|
// 登录态变化后回到本页:重拉详情与走马灯
|
||||||
if (found) setStore(found);
|
useDidShow(() => {
|
||||||
else toast('门店不存在');
|
const id = pickStoreId(storeId || router.params.id);
|
||||||
})
|
if (!id) return;
|
||||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
void loadStore(id);
|
||||||
});
|
void loadRecentRedeems(id);
|
||||||
}, [storeId]);
|
});
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => {
|
() => {
|
||||||
@@ -106,6 +237,11 @@ export default function StoreDetailPage() {
|
|||||||
[store, storeId],
|
[store, storeId],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const marqueeLines = useMemo(
|
||||||
|
() => recentRedeems.map(formatRecentRedeemLine).filter(Boolean),
|
||||||
|
[recentRedeems],
|
||||||
|
);
|
||||||
|
|
||||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||||
useShareTimeline(() => ({
|
useShareTimeline(() => ({
|
||||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
||||||
@@ -161,7 +297,9 @@ export default function StoreDetailPage() {
|
|||||||
return (
|
return (
|
||||||
<PageShell variant="scroll" className="store-detail-page">
|
<PageShell variant="scroll" className="store-detail-page">
|
||||||
<PageNavBar title="门店详情" solid onBack={goBack} />
|
<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>
|
</PageShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -245,6 +383,12 @@ export default function StoreDetailPage() {
|
|||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
|
{marqueeLines.length > 0 ? (
|
||||||
|
<View className="store-detail-marquee-wrap">
|
||||||
|
<StoreRedeemMarquee key={marqueeLines.join('|')} lines={marqueeLines} />
|
||||||
|
</View>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{intro ? (
|
{intro ? (
|
||||||
<View className="store-detail-section">
|
<View className="store-detail-section">
|
||||||
<Text className="store-detail-section-title">门店详情</Text>
|
<Text className="store-detail-section-title">门店详情</Text>
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ import {
|
|||||||
} from '../../lib/user-location';
|
} from '../../lib/user-location';
|
||||||
import { FALLBACK_CITY_CODE } from '../../lib/product-images';
|
import { FALLBACK_CITY_CODE } from '../../lib/product-images';
|
||||||
import { formatDistanceMeters } from '../../lib/geo';
|
import { formatDistanceMeters } from '../../lib/geo';
|
||||||
import { request, toast } from '../../lib/api';
|
import { getToken, request, toast } from '../../lib/api';
|
||||||
import {
|
import {
|
||||||
getStoresListCache,
|
getStoresListCache,
|
||||||
isStoresSessionBootstrapped,
|
isStoresSessionBootstrapped,
|
||||||
@@ -143,6 +143,7 @@ export default function StoresPage() {
|
|||||||
setStoresListCache({
|
setStoresListCache({
|
||||||
cityKey,
|
cityKey,
|
||||||
cityCode: nextCode,
|
cityCode: nextCode,
|
||||||
|
authKey: getToken() || '',
|
||||||
listRegion: toCityWideRegion(listRegion),
|
listRegion: toCityWideRegion(listRegion),
|
||||||
items,
|
items,
|
||||||
filterRegion,
|
filterRegion,
|
||||||
@@ -160,12 +161,38 @@ export default function StoresPage() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 首次进入:弹窗 + 定位 + 拉列表。
|
* 首次进入:弹窗 + 定位 + 拉列表。
|
||||||
* 同次再切回:只同步 tab 选中态,不改筛选、不拉接口、不 setState。
|
* 同次再切回:只同步 tab 选中态(登录态未变)。
|
||||||
|
* 登录/退出后 token 变化:按缓存失效重新拉列表(白名单)。
|
||||||
*/
|
*/
|
||||||
useDidShow(() => {
|
useDidShow(() => {
|
||||||
syncTabBarSelected(1);
|
syncTabBarSelected(1);
|
||||||
|
|
||||||
|
const authKey = getToken() || '';
|
||||||
|
const cache = getStoresListCache();
|
||||||
if (isStoresSessionBootstrapped()) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
markStoresSessionBootstrapped();
|
markStoresSessionBootstrapped();
|
||||||
|
|||||||
@@ -103,6 +103,30 @@
|
|||||||
border-bottom-color: var(--color-heritage-red);
|
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 {
|
.home-product-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -110,6 +134,32 @@
|
|||||||
padding: 8px var(--space-page) 12px;
|
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 {
|
.home-product-card {
|
||||||
background: var(--color-card);
|
background: var(--color-card);
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
|
|||||||
@@ -10,9 +10,10 @@
|
|||||||
|
|
||||||
.mine-header {
|
.mine-header {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
z-index: 2;
|
||||||
padding: 16px var(--space-page) 44px;
|
padding: 16px var(--space-page) 44px;
|
||||||
background: linear-gradient(135deg, #820012 0%, var(--color-heritage-red) 40%, #d4a373 100%);
|
background: linear-gradient(135deg, #820012 0%, var(--color-heritage-red) 40%, #d4a373 100%);
|
||||||
overflow: hidden;
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mine-header-texture {
|
.mine-header-texture {
|
||||||
@@ -33,11 +34,12 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
z-index: 1;
|
z-index: 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
.mine-avatar-wrap {
|
.mine-avatar-wrap {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
z-index: 4;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
margin-right: 12px;
|
margin-right: 12px;
|
||||||
}
|
}
|
||||||
@@ -160,7 +162,7 @@
|
|||||||
.mine-main {
|
.mine-main {
|
||||||
margin-top: -28px;
|
margin-top: -28px;
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 2;
|
z-index: 1;
|
||||||
padding: 0 var(--space-page) 0;
|
padding: 0 var(--space-page) 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -203,7 +203,8 @@
|
|||||||
height: var(--nav-content-height);
|
height: var(--nav-content-height);
|
||||||
line-height: var(--nav-content-height);
|
line-height: var(--nav-content-height);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 0 88px 0 56px;
|
/* 左右等宽留白,避免右侧分享/胶囊导致标题视觉偏左 */
|
||||||
|
padding: 0 max(72px, var(--nav-padding-right, 96px));
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
|
|||||||
@@ -81,6 +81,19 @@
|
|||||||
box-shadow: var(--shadow-card);
|
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 {
|
.order-card-title {
|
||||||
display: block;
|
display: block;
|
||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
|
|||||||
@@ -301,6 +301,25 @@
|
|||||||
color: var(--color-on-surface-variant);
|
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 {
|
.product-detail-buy-btn {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
height: 48px;
|
height: 48px;
|
||||||
@@ -312,6 +331,12 @@
|
|||||||
box-shadow: 0 8px 24px rgba(166, 29, 36, 0.2);
|
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 {
|
.product-detail-buy-btn-text {
|
||||||
color: #fff;
|
color: #fff;
|
||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
|
|||||||
@@ -304,9 +304,19 @@
|
|||||||
display: block;
|
display: block;
|
||||||
font-family: ui-monospace, monospace;
|
font-family: ui-monospace, monospace;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
word-break: break-all;
|
|
||||||
color: var(--color-on-surface);
|
color: var(--color-on-surface);
|
||||||
line-height: 1.5;
|
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 {
|
.redeem-success-icon {
|
||||||
@@ -378,6 +388,49 @@
|
|||||||
word-break: break-all;
|
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 {
|
.ledger-item {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
|
|||||||
@@ -127,6 +127,36 @@
|
|||||||
font-size: 11px;
|
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 {
|
.store-detail-section {
|
||||||
background: var(--color-card);
|
background: var(--color-card);
|
||||||
margin: 0 var(--space-page) 16px;
|
margin: 0 var(--space-page) 16px;
|
||||||
|
|||||||
+2
-1
@@ -169,10 +169,11 @@ git fetch "\$GIT_REMOTE"
|
|||||||
git checkout "\$GIT_BRANCH"
|
git checkout "\$GIT_BRANCH"
|
||||||
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
|
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
|
||||||
|
|
||||||
|
# 无额外参数时执行 DB 同步;无 schema 变更请显式传 -- --skip-db
|
||||||
if [[ -n "\$RELEASE_ARGS" ]]; then
|
if [[ -n "\$RELEASE_ARGS" ]]; then
|
||||||
bash deploy/remote-release.sh \$RELEASE_ARGS
|
bash deploy/remote-release.sh \$RELEASE_ARGS
|
||||||
else
|
else
|
||||||
bash deploy/remote-release.sh --skip-db
|
bash deploy/remote-release.sh
|
||||||
fi
|
fi
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ import {
|
|||||||
classifyRedeemClientError,
|
classifyRedeemClientError,
|
||||||
generateRedeemPendingNo,
|
generateRedeemPendingNo,
|
||||||
REDEEM_WEAKNET_FAIL_THRESHOLD,
|
REDEEM_WEAKNET_FAIL_THRESHOLD,
|
||||||
|
sumUnbilledPayoutAmount,
|
||||||
|
validateStoreWithdraw,
|
||||||
|
pickPayoutsForWithdrawAmount,
|
||||||
} from './index';
|
} from './index';
|
||||||
|
|
||||||
describe('calcBenefitAmount', () => {
|
describe('calcBenefitAmount', () => {
|
||||||
@@ -235,3 +238,53 @@ describe('generateRedeemPendingNo', () => {
|
|||||||
expect(REDEEM_WEAKNET_FAIL_THRESHOLD).toBe(5);
|
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;
|
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)$/;
|
const TIME_HM_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
||||||
|
|
||||||
export type BusinessHoursSegment = { open: string; close: string };
|
export type BusinessHoursSegment = { open: string; close: string };
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ export interface ProductDto {
|
|||||||
detailContent?: ProductDetailContentDto | null;
|
detailContent?: ProductDetailContentDto | null;
|
||||||
/** 是否允许现场取货下单 */
|
/** 是否允许现场取货下单 */
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
/** 是否允许配送到址(同城线上购买) */
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
/** 是否允许跨城配送 */
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductDetailFeatureDto {
|
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`;
|
export const QUALIFICATION_DISCLOSURE_URL = `${MINI_USER_STATIC_OSS_BASE}qualification-disclosure.png`;
|
||||||
|
|
||||||
/** 总部客服电话(C 端联系客服) */
|
/** 总部客服电话(C 端联系客服) */
|
||||||
export const CUSTOMER_SERVICE_PHONE = '400-888-1234';
|
export const CUSTOMER_SERVICE_PHONE = '13203801799';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 企业微信「微信客服」链接(C 端「在线客服」;微信内网页点击后进入原生客服会话)
|
* 企业微信「微信客服」链接(C 端「在线客服」;微信内网页点击后进入原生客服会话)
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export const HQ_PERMISSION_CATALOG = [
|
|||||||
{ key: 'system_settings_app', label: '应用链接', group: '系统设置' },
|
{ key: 'system_settings_app', label: '应用链接', group: '系统设置' },
|
||||||
{ key: 'system_settings_deploy', label: '发布部署', group: '系统设置' },
|
{ key: 'system_settings_deploy', label: '发布部署', group: '系统设置' },
|
||||||
{ key: 'system_settings_winery_bank', label: '酒厂银行账户', group: '系统设置' },
|
{ key: 'system_settings_winery_bank', label: '酒厂银行账户', group: '系统设置' },
|
||||||
|
{ key: 'system_settings_finance', label: '财务结算', group: '系统设置' },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type HqPermissionKey = (typeof HQ_PERMISSION_CATALOG)[number]['key'];
|
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',
|
app: 'system_settings_app',
|
||||||
deploy: 'system_settings_deploy',
|
deploy: 'system_settings_deploy',
|
||||||
winery_bank: 'system_settings_winery_bank',
|
winery_bank: 'system_settings_winery_bank',
|
||||||
|
finance: 'system_settings_finance',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const SYSTEM_SETTINGS_PERMISSION_KEYS = Object.values(
|
export const SYSTEM_SETTINGS_PERMISSION_KEYS = Object.values(
|
||||||
@@ -127,6 +129,7 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
|
|||||||
'invoices',
|
'invoices',
|
||||||
'logs',
|
'logs',
|
||||||
'system_settings_winery_bank',
|
'system_settings_winery_bank',
|
||||||
|
'system_settings_finance',
|
||||||
],
|
],
|
||||||
CUSTOMER_SERVICE: [
|
CUSTOMER_SERVICE: [
|
||||||
'dashboard',
|
'dashboard',
|
||||||
|
|||||||
@@ -19,14 +19,39 @@ export interface RedeemPreviewDto {
|
|||||||
boundStoreId?: string | null;
|
boundStoreId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 门店核销方式 */
|
||||||
|
export type RedeemChannel = 'SCAN' | 'PHONE';
|
||||||
|
|
||||||
|
export const REDEEM_CHANNEL_LABELS: Record<RedeemChannel, string> = {
|
||||||
|
SCAN: '扫码核销',
|
||||||
|
PHONE: '手机号核销',
|
||||||
|
};
|
||||||
|
|
||||||
export interface RedeemRecordDto {
|
export interface RedeemRecordDto {
|
||||||
id: string;
|
id: string;
|
||||||
redeemNo: string;
|
redeemNo: string;
|
||||||
amount: number;
|
amount: number;
|
||||||
settleAmount: number;
|
settleAmount: number;
|
||||||
|
/** 核销方式:扫码 SCAN / 手机号 PHONE */
|
||||||
|
channel?: RedeemChannel;
|
||||||
createdAt: string;
|
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 {
|
export interface RedeemPhoneBalanceDto {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
totalBalance: number;
|
totalBalance: number;
|
||||||
|
|||||||
@@ -1,5 +1,86 @@
|
|||||||
export type FinancePayStatus = 'UNPAID' | 'PAID';
|
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 {
|
export interface StorePayoutDto {
|
||||||
id: string;
|
id: string;
|
||||||
redeemAmount: number;
|
redeemAmount: number;
|
||||||
@@ -30,6 +111,19 @@ export const FINANCE_PAY_STATUS_LABELS: Record<FinancePayStatus, string> = {
|
|||||||
PAID: '已打款',
|
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 {
|
export interface PartnerBillDto {
|
||||||
id: string;
|
id: string;
|
||||||
billNo: string;
|
billNo: string;
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ export type PartnerProxyOrderProductOption = {
|
|||||||
benefitAmount: number | null;
|
benefitAmount: number | null;
|
||||||
coverUrl?: string | null;
|
coverUrl?: string | null;
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PartnerProxyOrderPromoOption = {
|
export type PartnerProxyOrderPromoOption = {
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export function createWeixinSdk(config: WeixinSdkConfig) {
|
|||||||
getPhoneNumber: () => getWechatPhoneNumber(config),
|
getPhoneNumber: () => getWechatPhoneNumber(config),
|
||||||
getLocation: () => getWechatLocation(config),
|
getLocation: () => getWechatLocation(config),
|
||||||
getLocationDetailed: () => getWechatLocationDetailed(config),
|
getLocationDetailed: () => getWechatLocationDetailed(config),
|
||||||
scanQrCode: () => scanQrCode(config),
|
scanQrCode: (options?: Parameters<typeof scanQrCode>[1]) => scanQrCode(config, options),
|
||||||
chooseImages: (options?: Parameters<typeof chooseWechatImages>[1]) =>
|
chooseImages: (options?: Parameters<typeof chooseWechatImages>[1]) =>
|
||||||
chooseWechatImages(config, options),
|
chooseWechatImages(config, options),
|
||||||
pay: (prepay: Parameters<typeof invokeWechatPay>[0]) =>
|
pay: (prepay: Parameters<typeof invokeWechatPay>[0]) =>
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { getRuntimePlatform, isIosDevice, isWechatDevTools } from './env';
|
import { getRuntimePlatform, isIosDevice, isWechatDevTools } from './env';
|
||||||
import { ensureJssdkReady } from './jssdk';
|
import {
|
||||||
|
ensureJssdkReady,
|
||||||
|
getJssdkSignUrl,
|
||||||
|
initWechatJssdk,
|
||||||
|
resetJssdkConfig,
|
||||||
|
} from './jssdk';
|
||||||
import type { WeixinSdkConfig } from './types';
|
import type { WeixinSdkConfig } from './types';
|
||||||
|
|
||||||
function delay(ms: number): Promise<void> {
|
function delay(ms: number): Promise<void> {
|
||||||
@@ -11,7 +16,7 @@ export function formatScanFailMessage(errMsg: string): string {
|
|||||||
const msg = errMsg.trim() || '扫码失败';
|
const msg = errMsg.trim() || '扫码失败';
|
||||||
if (/cancel/i.test(msg)) return '';
|
if (/cancel/i.test(msg)) return '';
|
||||||
|
|
||||||
// iOS 常见:JSSDK 权限离线校验尚未完成,并非系统相机权限
|
// iOS / 授权回调后常见:JSSDK 权限离线校验尚未完成,并非系统相机权限
|
||||||
if (/offline verifying|permission value is offline/i.test(msg)) {
|
if (/offline verifying|permission value is offline/i.test(msg)) {
|
||||||
return '微信权限验证中,请稍候再试或刷新页面后重新扫码';
|
return '微信权限验证中,请稍候再试或刷新页面后重新扫码';
|
||||||
}
|
}
|
||||||
@@ -33,6 +38,47 @@ export function formatScanFailMessage(errMsg: string): string {
|
|||||||
return msg;
|
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> {
|
function invokeScanQrCode(): Promise<string | null> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
window.wx!.scanQRCode!({
|
window.wx!.scanQRCode!({
|
||||||
@@ -52,8 +98,16 @@ function invokeScanQrCode(): Promise<string | null> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 调起扫码(返回二维码/条码内容,失败返回 null) */
|
export type ScanQrCodeOptions = {
|
||||||
export async function scanQrCode(config: WeixinSdkConfig): Promise<string | null> {
|
/** OAuth / 首次绑定后权限离线校验更慢,加长预热 */
|
||||||
|
postAuthWarmup?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 调起扫码(返回二维码/条码内容,取消返回 null) */
|
||||||
|
export async function scanQrCode(
|
||||||
|
config: WeixinSdkConfig,
|
||||||
|
options: ScanQrCodeOptions = {},
|
||||||
|
): Promise<string | null> {
|
||||||
const platform = getRuntimePlatform();
|
const platform = getRuntimePlatform();
|
||||||
|
|
||||||
if (platform === 'mini' && window.wx?.scanCode) {
|
if (platform === 'mini' && window.wx?.scanCode) {
|
||||||
@@ -68,32 +122,42 @@ export async function scanQrCode(config: WeixinSdkConfig): Promise<string | null
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (platform === 'wechat-h5') {
|
if (platform === 'wechat-h5') {
|
||||||
await ensureJssdkReady({
|
const jssdkOptions = {
|
||||||
apiBase: config.apiBase ?? '/api/v1',
|
apiBase: config.apiBase ?? '/api/v1',
|
||||||
clientApp: config.clientApp,
|
clientApp: config.clientApp,
|
||||||
getAccessToken: config.getAccessToken,
|
getAccessToken: config.getAccessToken,
|
||||||
});
|
jsApiList: ['scanQRCode', 'checkJsApi'],
|
||||||
|
};
|
||||||
|
|
||||||
|
await ensureScanJssdk(config);
|
||||||
if (!window.wx?.scanQRCode) {
|
if (!window.wx?.scanQRCode) {
|
||||||
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
||||||
}
|
}
|
||||||
|
|
||||||
// iOS 在 wx.ready 后立即调 scanQRCode 可能触发 offline verifying
|
// wx.ready ≠ 权限离线校验完成;授权回跳后更明显
|
||||||
if (isIosDevice() && !isWechatDevTools()) {
|
const warmupMs = options.postAuthWarmup
|
||||||
await delay(500);
|
? 1200
|
||||||
}
|
: isIosDevice() && !isWechatDevTools()
|
||||||
|
? 800
|
||||||
|
: 300;
|
||||||
|
await delay(warmupMs);
|
||||||
|
|
||||||
const maxAttempts = 2;
|
const maxAttempts = options.postAuthWarmup ? 3 : 2;
|
||||||
let lastError: Error | null = null;
|
let lastError: Error | null = null;
|
||||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||||
if (attempt > 0) {
|
if (attempt > 0) {
|
||||||
await delay(800);
|
if (lastError && isScanPermissionWarmupError(lastError.message)) {
|
||||||
|
resetJssdkConfig();
|
||||||
|
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
||||||
|
await checkJsApi('scanQRCode');
|
||||||
|
}
|
||||||
|
await delay(700 + attempt * 500);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await invokeScanQrCode();
|
return await invokeScanQrCode();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
lastError = e instanceof Error ? e : new Error('扫码失败');
|
lastError = e instanceof Error ? e : new Error('扫码失败');
|
||||||
const raw = lastError.message;
|
const retryable = isScanPermissionWarmupError(lastError.message);
|
||||||
const retryable = /offline verifying|权限验证中|接口未就绪/i.test(raw);
|
|
||||||
if (attempt < maxAttempts - 1 && retryable) continue;
|
if (attempt < maxAttempts - 1 && retryable) continue;
|
||||||
throw lastError;
|
throw lastError;
|
||||||
}
|
}
|
||||||
|
|||||||
+69
-10
@@ -135,38 +135,97 @@ async function main() {
|
|||||||
'/shop/auth/login/sms',
|
'/shop/auth/login/sms',
|
||||||
'/shop/auth/sms/send',
|
'/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');
|
if (!shopMe?.phone) throw new Error('Shop /shop/auth/me failed');
|
||||||
const refreshed = await req('SHOP_H5', '/shop/auth/token/refresh', {
|
const refreshed = await req('SHOP_H5', '/shop/auth/token/refresh', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ refreshToken: shopLogin.refreshToken }),
|
body: JSON.stringify({ refreshToken: shopLogin.refreshToken }),
|
||||||
});
|
});
|
||||||
if (!refreshed?.accessToken) throw new Error('Shop token refresh failed');
|
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', {
|
const preview = await req('SHOP_H5', '/shop/redeem/preview', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
token: shopLogin.accessToken,
|
token: shopToken,
|
||||||
body: JSON.stringify({ token: directToken.token }),
|
body: JSON.stringify({ token: directToken.token }),
|
||||||
});
|
});
|
||||||
if (!preview.amount) throw new Error('Redeem preview failed');
|
if (!preview.amount) throw new Error('Redeem preview failed');
|
||||||
await req('SHOP_H5', '/shop/redeem/confirm', {
|
await req('SHOP_H5', '/shop/redeem/confirm', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
token: shopLogin.accessToken,
|
token: shopToken,
|
||||||
body: JSON.stringify({ token: directToken.token }),
|
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 admin = await adminLogin();
|
||||||
const payouts = await req('HQ_WEB', '/admin/store-payouts?status=PENDING', {
|
const shopStoreId = shopMe.storeId || shopMe.stores?.[0]?.storeId;
|
||||||
token: admin.accessToken,
|
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');
|
if (!(withdrawSummary.availableAmount > 0)) {
|
||||||
const payoutId = payouts.items[0].id;
|
throw new Error('Expected available withdraw amount after redeem');
|
||||||
await req('HQ_WEB', `/admin/store-payouts/${payoutId}/confirm`, {
|
}
|
||||||
|
|
||||||
|
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',
|
method: 'POST',
|
||||||
token: admin.accessToken,
|
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');
|
console.log('10. Refund ticket flow');
|
||||||
const order2 = await req('USER_H5', '/trade/orders', {
|
const order2 = await req('USER_H5', '/trade/orders', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -52,6 +52,12 @@ enum RedeemPendingStatus {
|
|||||||
REJECTED
|
REJECTED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Redeem channel: SCAN or PHONE
|
||||||
|
enum RedeemChannel {
|
||||||
|
SCAN
|
||||||
|
PHONE
|
||||||
|
}
|
||||||
|
|
||||||
enum ResourceMediaType {
|
enum ResourceMediaType {
|
||||||
IMAGE
|
IMAGE
|
||||||
VIDEO
|
VIDEO
|
||||||
@@ -314,6 +320,12 @@ enum StorePayoutStatus {
|
|||||||
PAID
|
PAID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum StoreWithdrawStatus {
|
||||||
|
PENDING_REVIEW
|
||||||
|
REJECTED
|
||||||
|
PAID
|
||||||
|
}
|
||||||
|
|
||||||
enum ThirdPartyProvider {
|
enum ThirdPartyProvider {
|
||||||
WECHAT_PAY
|
WECHAT_PAY
|
||||||
WECHAT_REFUND
|
WECHAT_REFUND
|
||||||
@@ -593,6 +605,10 @@ model CommonProductItem {
|
|||||||
status ProductStatus @default(DRAFT)
|
status ProductStatus @default(DRAFT)
|
||||||
sortOrder Int @default(0) @map("sort_order")
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
allowOnSitePickup Boolean @default(false) @map("allow_on_site_pickup")
|
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
|
/// Online test: only listed phones can see/buy when enabled
|
||||||
visibilityWhitelistEnabled Boolean @default(false) @map("visibility_whitelist_enabled")
|
visibilityWhitelistEnabled Boolean @default(false) @map("visibility_whitelist_enabled")
|
||||||
coverResourceId BigInt? @map("cover_resource_id") @db.UnsignedBigInt
|
coverResourceId BigInt? @map("cover_resource_id") @db.UnsignedBigInt
|
||||||
@@ -1058,6 +1074,10 @@ model Store {
|
|||||||
openTime2 String? @map("open_time_2") @db.VarChar(8)
|
openTime2 String? @map("open_time_2") @db.VarChar(8)
|
||||||
closeTime2 String? @map("close_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)
|
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)
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
@@ -1071,6 +1091,8 @@ model Store {
|
|||||||
ratings StoreRating[]
|
ratings StoreRating[]
|
||||||
payouts StorePayout[]
|
payouts StorePayout[]
|
||||||
storeBills StoreBill[]
|
storeBills StoreBill[]
|
||||||
|
withdrawRequests StoreWithdrawRequest[]
|
||||||
|
visibilityPhones StoreVisibilityPhone[]
|
||||||
|
|
||||||
@@index([cityId, status])
|
@@index([cityId, status])
|
||||||
@@index([partnerAccountId])
|
@@index([partnerAccountId])
|
||||||
@@ -1078,6 +1100,20 @@ model Store {
|
|||||||
@@map("store_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 {
|
model StoreAccount {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
phone String @unique @db.VarChar(20)
|
phone String @unique @db.VarChar(20)
|
||||||
@@ -1100,6 +1136,7 @@ model StoreAccount {
|
|||||||
childAccounts StoreAccount[] @relation("StoreAccountHierarchy")
|
childAccounts StoreAccount[] @relation("StoreAccountHierarchy")
|
||||||
bindings StoreAccountStore[]
|
bindings StoreAccountStore[]
|
||||||
redeemPendingRecords RedeemPendingRecord[]
|
redeemPendingRecords RedeemPendingRecord[]
|
||||||
|
withdrawRequests StoreWithdrawRequest[]
|
||||||
|
|
||||||
@@index([parentAccountId])
|
@@index([parentAccountId])
|
||||||
@@map("store_account")
|
@@map("store_account")
|
||||||
@@ -1287,14 +1324,16 @@ model BenefitCoupon {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model RedeemRecord {
|
model RedeemRecord {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
redeemNo String @unique @map("redeem_no") @db.VarChar(32)
|
redeemNo String @unique @map("redeem_no") @db.VarChar(32)
|
||||||
userId BigInt @map("user_id") @db.UnsignedBigInt
|
userId BigInt @map("user_id") @db.UnsignedBigInt
|
||||||
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
|
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
|
||||||
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
storeId BigInt @map("store_id") @db.UnsignedBigInt
|
||||||
amount Decimal @db.Decimal(10, 2)
|
amount Decimal @db.Decimal(10, 2)
|
||||||
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
|
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
/// 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)
|
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||||
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
|
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
|
||||||
@@ -1305,6 +1344,7 @@ model RedeemRecord {
|
|||||||
allocations RedeemRecordAllocation[]
|
allocations RedeemRecordAllocation[]
|
||||||
|
|
||||||
@@index([storeId, createdAt])
|
@@index([storeId, createdAt])
|
||||||
|
@@index([storeId, channel, createdAt])
|
||||||
@@map("user_redeem_record")
|
@@map("user_redeem_record")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1411,12 +1451,52 @@ model StorePayout {
|
|||||||
redeemRecord RedeemRecord @relation(fields: [redeemRecordId], references: [id], onDelete: Restrict)
|
redeemRecord RedeemRecord @relation(fields: [redeemRecordId], references: [id], onDelete: Restrict)
|
||||||
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
||||||
storeBill StoreBill? @relation(fields: [storeBillId], references: [id], onDelete: SetNull)
|
storeBill StoreBill? @relation(fields: [storeBillId], references: [id], onDelete: SetNull)
|
||||||
|
withdrawItem StoreWithdrawPayoutItem?
|
||||||
|
|
||||||
@@index([storeId, status])
|
@@index([storeId, status])
|
||||||
@@index([storeBillId])
|
@@index([storeBillId])
|
||||||
@@map("store_payout")
|
@@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 {
|
model WineryBill {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
billNo String @unique @map("bill_no") @db.VarChar(32)
|
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 { CLIENT_APP_ACTOR_MAP, ClientApp } from '@dukang/shared-types';
|
||||||
import type { AuthUser } from './jwt-auth.guard';
|
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()
|
@Injectable()
|
||||||
export class OptionalJwtAuthGuard implements CanActivate {
|
export class OptionalJwtAuthGuard implements CanActivate {
|
||||||
constructor(private readonly jwtService: JwtService) {}
|
constructor(private readonly jwtService: JwtService) {}
|
||||||
@@ -20,7 +29,7 @@ export class OptionalJwtAuthGuard implements CanActivate {
|
|||||||
try {
|
try {
|
||||||
const payload = this.jwtService.verify(auth.slice(7));
|
const payload = this.jwtService.verify(auth.slice(7));
|
||||||
const clientApp = req.headers['x-client-app'] as ClientApp;
|
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];
|
const expectedActor = CLIENT_APP_ACTOR_MAP[clientApp];
|
||||||
if (payload.actorType !== expectedActor) return true;
|
if (payload.actorType !== expectedActor) return true;
|
||||||
req.user = {
|
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_PAYOUT_BATCH_CONFIRM: 'STORE_PAYOUT_BATCH_CONFIRM',
|
||||||
STORE_BILL_CONFIRM: 'STORE_BILL_CONFIRM',
|
STORE_BILL_CONFIRM: 'STORE_BILL_CONFIRM',
|
||||||
STORE_BILL_BATCH_CONFIRM: 'STORE_BILL_BATCH_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_GENERATE: 'PARTNER_BILL_GENERATE',
|
||||||
PARTNER_BILL_SEND: 'PARTNER_BILL_SEND',
|
PARTNER_BILL_SEND: 'PARTNER_BILL_SEND',
|
||||||
PARTNER_BILL_BATCH_SEND: 'PARTNER_BILL_BATCH_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_PAYOUT_BATCH_CONFIRM]: '批量门店打款',
|
||||||
[HqOperationAction.STORE_BILL_CONFIRM]: '门店对账单确认打款',
|
[HqOperationAction.STORE_BILL_CONFIRM]: '门店对账单确认打款',
|
||||||
[HqOperationAction.STORE_BILL_BATCH_CONFIRM]: '批量门店对账单打款',
|
[HqOperationAction.STORE_BILL_BATCH_CONFIRM]: '批量门店对账单打款',
|
||||||
|
[HqOperationAction.STORE_WITHDRAW_APPROVE]: '门店提现审核通过',
|
||||||
|
[HqOperationAction.STORE_WITHDRAW_REJECT]: '门店提现驳回',
|
||||||
[HqOperationAction.PARTNER_BILL_GENERATE]: '生成合伙人账单',
|
[HqOperationAction.PARTNER_BILL_GENERATE]: '生成合伙人账单',
|
||||||
[HqOperationAction.PARTNER_BILL_SEND]: '发送合伙人账单',
|
[HqOperationAction.PARTNER_BILL_SEND]: '发送合伙人账单',
|
||||||
[HqOperationAction.PARTNER_BILL_BATCH_SEND]: '批量发送合伙人账单',
|
[HqOperationAction.PARTNER_BILL_BATCH_SEND]: '批量发送合伙人账单',
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export const SYSTEM_CONFIG_GROUPS: SystemConfigGroupMeta[] = [
|
|||||||
{ key: 'app', label: '应用链接' },
|
{ key: 'app', label: '应用链接' },
|
||||||
{ key: 'deploy', label: '发布部署' },
|
{ key: 'deploy', label: '发布部署' },
|
||||||
{ key: 'winery_bank', label: '酒厂银行账户' },
|
{ key: 'winery_bank', label: '酒厂银行账户' },
|
||||||
|
{ key: 'finance', label: '财务结算' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const G = {
|
const G = {
|
||||||
@@ -21,6 +22,7 @@ const G = {
|
|||||||
app: 'app',
|
app: 'app',
|
||||||
deploy: 'deploy',
|
deploy: 'deploy',
|
||||||
winery_bank: 'winery_bank',
|
winery_bank: 'winery_bank',
|
||||||
|
finance: 'finance',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** HQ 可维护字段(不含 NODE_ENV / DATABASE_URL / JWT 等基础设施项) */
|
/** HQ 可维护字段(不含 NODE_ENV / DATABASE_URL / JWT 等基础设施项) */
|
||||||
@@ -187,6 +189,15 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
type: 'string',
|
type: 'string',
|
||||||
requiresRestart: false,
|
requiresRestart: false,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'STORE_WITHDRAW_DAILY_LIMIT',
|
||||||
|
label: '门店未出账提现单日上限(元)',
|
||||||
|
group: G.finance,
|
||||||
|
type: 'number',
|
||||||
|
requiresRestart: false,
|
||||||
|
description: 'FIN-002:单店单日提现上限,默认 5000',
|
||||||
|
placeholder: '5000',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/** 已从 HQ 配置移除、仅保留在 .env 的键(启动时从 DB 清理) */
|
/** 已从 HQ 配置移除、仅保留在 .env 的键(启动时从 DB 清理) */
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ export const WECOM_HANDBOOK_ENTRIES: HandbookEntry[] = [
|
|||||||
body: [
|
body: [
|
||||||
'门店账单:核销×60%,T+1 出账;HQ 确认打款。',
|
'门店账单:核销×60%,T+1 出账;HQ 确认打款。',
|
||||||
'合伙人月账独立确认打款。',
|
'合伙人月账独立确认打款。',
|
||||||
'未出账提现受白名单/单日上限等 FIN 护栏。',
|
'门店可对未出账核销主动提现(受单日上限);申请后锁定明细不进入次日出账,HQ 审后打款并企微提醒。',
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { AlertService } from '../common/alert/alert.service';
|
|||||||
* 财务对账单定时任务(Asia/Shanghai)
|
* 财务对账单定时任务(Asia/Shanghai)
|
||||||
* - 每日 08:00:酒厂日账单 + 门店日账单(统计昨日 00:00~今日 00:00)
|
* - 每日 08:00:酒厂日账单 + 门店日账单(统计昨日 00:00~今日 00:00)
|
||||||
* - 每月 1 日 08:00:合伙人上一自然月账单 + 物流承运商上一自然月对账
|
* - 每月 1 日 08:00:合伙人上一自然月账单 + 物流承运商上一自然月对账
|
||||||
|
* - 工作日 18:05:门店提现 T+0 审完预警(FIN-003)
|
||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SettlementScheduler {
|
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' })
|
@Cron('0 8 1 * *', { timeZone: 'Asia/Shanghai' })
|
||||||
async handleMonthlyPartnerBills() {
|
async handleMonthlyPartnerBills() {
|
||||||
this.logger.log('Monthly partner bills job start');
|
this.logger.log('Monthly partner bills job start');
|
||||||
|
|||||||
@@ -119,7 +119,29 @@ export class BenefitService {
|
|||||||
where: benefitLedgerWhere(userId, couponId),
|
where: benefitLedgerWhere(userId, couponId),
|
||||||
orderBy: { createdAt: 'desc' },
|
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) {
|
async getCoupon(userId: bigint, couponId: bigint) {
|
||||||
|
|||||||
@@ -81,11 +81,9 @@ export class CatalogService {
|
|||||||
return serializeBigInt(
|
return serializeBigInt(
|
||||||
visible.map((p) => {
|
visible.map((p) => {
|
||||||
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
||||||
const { visibilityPhones, ...rest } = p;
|
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = p;
|
||||||
return {
|
return {
|
||||||
...rest,
|
...rest,
|
||||||
visibilityWhitelistEnabled: p.visibilityWhitelistEnabled,
|
|
||||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
|
||||||
benefitAmount: p.benefitAmount ?? p.price,
|
benefitAmount: p.benefitAmount ?? p.price,
|
||||||
price: Number(p.price),
|
price: Number(p.price),
|
||||||
benefitDisplay: Number(p.benefitAmount ?? p.price),
|
benefitDisplay: Number(p.benefitAmount ?? p.price),
|
||||||
@@ -119,11 +117,9 @@ export class CatalogService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const media = mapProductMedia(product, resources);
|
const media = mapProductMedia(product, resources);
|
||||||
const { visibilityPhones, ...rest } = product;
|
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = product;
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
...rest,
|
...rest,
|
||||||
visibilityWhitelistEnabled: product.visibilityWhitelistEnabled,
|
|
||||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
|
||||||
benefitAmount: product.benefitAmount ?? product.price,
|
benefitAmount: product.benefitAmount ?? product.price,
|
||||||
price: Number(product.price),
|
price: Number(product.price),
|
||||||
...media,
|
...media,
|
||||||
|
|||||||
@@ -23,6 +23,14 @@ export class ClientErrorService {
|
|||||||
const stack = dto.stack?.trim().slice(0, 4000);
|
const stack = dto.stack?.trim().slice(0, 4000);
|
||||||
const pagePath = dto.pagePath?.trim().slice(0, 128);
|
const pagePath = dto.pagePath?.trim().slice(0, 128);
|
||||||
const fingerprint = `${dto.level}|${dto.category}|${message.slice(0, 120)}`;
|
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 = {
|
const logLine = {
|
||||||
level: dto.level,
|
level: dto.level,
|
||||||
@@ -34,6 +42,7 @@ export class ClientErrorService {
|
|||||||
actorId: user?.actorId != null ? String(user.actorId) : undefined,
|
actorId: user?.actorId != null ? String(user.actorId) : undefined,
|
||||||
stack: stack?.slice(0, 800),
|
stack: stack?.slice(0, 800),
|
||||||
extra: dto.extra,
|
extra: dto.extra,
|
||||||
|
skipWecom,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (dto.level === 'fatal') {
|
if (dto.level === 'fatal') {
|
||||||
@@ -61,6 +70,7 @@ export class ClientErrorService {
|
|||||||
actorType: user?.actorType ?? null,
|
actorType: user?.actorType ?? null,
|
||||||
actorId: user?.actorId != null ? String(user.actorId) : null,
|
actorId: user?.actorId != null ? String(user.actorId) : null,
|
||||||
storeId: user?.storeId != null ? String(user.storeId) : null,
|
storeId: user?.storeId != null ? String(user.storeId) : null,
|
||||||
|
skipWecom,
|
||||||
...(dto.extra && typeof dto.extra === 'object' ? { clientExtra: dto.extra } : {}),
|
...(dto.extra && typeof dto.extra === 'object' ? { clientExtra: dto.extra } : {}),
|
||||||
} as Prisma.InputJsonValue,
|
} 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';
|
const alertLevel: AlertLevel = dto.level === 'fatal' ? 'P0' : 'P1';
|
||||||
this.alert.notify({
|
this.alert.notify({
|
||||||
level: alertLevel,
|
level: alertLevel,
|
||||||
@@ -91,12 +101,56 @@ export class ClientErrorService {
|
|||||||
dedupeKey: `client_error|${fingerprint}`,
|
dedupeKey: `client_error|${fingerprint}`,
|
||||||
dedupeTtlSec: 600,
|
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 };
|
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 {
|
function isClientApp(v: string): v is ClientApp {
|
||||||
return [
|
return [
|
||||||
'USER_MINI',
|
'USER_MINI',
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
|||||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||||
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
||||||
import { ShopStoreGuard } from '../../common/guards/shop-store.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 { StoreMembershipService } from '../../common/guards/store-membership.service';
|
||||||
import {
|
import {
|
||||||
HqPermissionGuard,
|
HqPermissionGuard,
|
||||||
@@ -63,6 +64,7 @@ import { CommonModule } from '../common/common.module';
|
|||||||
PartnerPrimaryGuard,
|
PartnerPrimaryGuard,
|
||||||
PartnerPermissionGuard,
|
PartnerPermissionGuard,
|
||||||
ShopStoreGuard,
|
ShopStoreGuard,
|
||||||
|
ShopPrimaryGuard,
|
||||||
HqPermissionsResolver,
|
HqPermissionsResolver,
|
||||||
HqPermissionGuard,
|
HqPermissionGuard,
|
||||||
],
|
],
|
||||||
@@ -80,6 +82,7 @@ import { CommonModule } from '../common/common.module';
|
|||||||
PartnerPrimaryGuard,
|
PartnerPrimaryGuard,
|
||||||
PartnerPermissionGuard,
|
PartnerPermissionGuard,
|
||||||
ShopStoreGuard,
|
ShopStoreGuard,
|
||||||
|
ShopPrimaryGuard,
|
||||||
HqPermissionsResolver,
|
HqPermissionsResolver,
|
||||||
HqPermissionGuard,
|
HqPermissionGuard,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -40,6 +40,21 @@ function num(v: Prisma.Decimal | number | string | null | undefined): number {
|
|||||||
return typeof v === 'number' ? v : Number(v);
|
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()
|
@Injectable()
|
||||||
export class AdminDashboardService {
|
export class AdminDashboardService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
@@ -63,6 +78,7 @@ export class AdminDashboardService {
|
|||||||
pendingBills,
|
pendingBills,
|
||||||
pendingPartnerDraftBills,
|
pendingPartnerDraftBills,
|
||||||
openTickets,
|
openTickets,
|
||||||
|
pendingWithdrawRows,
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
this.prisma.user.count({ where: { status: 1, mergedIntoUserId: null } }),
|
this.prisma.user.count({ where: { status: 1, mergedIntoUserId: null } }),
|
||||||
this.prisma.user.count({
|
this.prisma.user.count({
|
||||||
@@ -85,8 +101,18 @@ export class AdminDashboardService {
|
|||||||
this.prisma.partnerBill.count({ where: { status: 'UNPAID' } }),
|
this.prisma.partnerBill.count({ where: { status: 'UNPAID' } }),
|
||||||
this.prisma.partnerBill.count({ where: { status: 'PENDING_REVIEW' } }),
|
this.prisma.partnerBill.count({ where: { status: 'PENDING_REVIEW' } }),
|
||||||
this.prisma.commonTicket.count({ where: { status: { in: ['PENDING', 'OPEN'] } } }),
|
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 {
|
return {
|
||||||
usersTotal,
|
usersTotal,
|
||||||
guestUsers,
|
guestUsers,
|
||||||
@@ -101,6 +127,8 @@ export class AdminDashboardService {
|
|||||||
pendingBills,
|
pendingBills,
|
||||||
pendingPartnerDraftBills,
|
pendingPartnerDraftBills,
|
||||||
openTickets,
|
openTickets,
|
||||||
|
pendingStoreWithdrawals,
|
||||||
|
overdueStoreWithdrawals,
|
||||||
ordersByStatus: ordersByStatus.map((row) => ({
|
ordersByStatus: ordersByStatus.map((row) => ({
|
||||||
status: row.status,
|
status: row.status,
|
||||||
count: row._count.status,
|
count: row._count.status,
|
||||||
|
|||||||
@@ -24,6 +24,37 @@ function normalizePhones(phones?: string[]): string[] {
|
|||||||
return out;
|
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()
|
@Injectable()
|
||||||
export class AdminProductsService {
|
export class AdminProductsService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
@@ -96,39 +127,44 @@ export class AdminProductsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async create(dto: CreateProductDto) {
|
async create(dto: CreateProductDto) {
|
||||||
const exists = await this.prisma.commonProductItem.findFirst({
|
const barcodeExists = await this.prisma.commonProductItem.findFirst({
|
||||||
where: { OR: [{ skuCode: dto.skuCode }, { barcode69: dto.barcode69 }] },
|
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 phones = normalizePhones(dto.visibilityPhones);
|
||||||
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
||||||
|
|
||||||
const product = await this.prisma.commonProductItem.create({
|
const product = await this.createWithGeneratedSku({
|
||||||
data: {
|
barcode69: dto.barcode69,
|
||||||
skuCode: dto.skuCode,
|
name: dto.name,
|
||||||
barcode69: dto.barcode69,
|
subtitle: dto.subtitle,
|
||||||
name: dto.name,
|
aromaType: dto.aromaType as 'QINGXIANG' | 'JIANGXIANG' | 'NONGXIANG',
|
||||||
subtitle: dto.subtitle,
|
spec: dto.spec,
|
||||||
aromaType: dto.aromaType as 'QINGXIANG' | 'JIANGXIANG' | 'NONGXIANG',
|
price: dto.price,
|
||||||
spec: dto.spec,
|
benefitAmount: dto.benefitAmount ?? dto.price,
|
||||||
price: dto.price,
|
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
||||||
benefitAmount: dto.benefitAmount ?? dto.price,
|
sortOrder: dto.sortOrder ?? 0,
|
||||||
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
allowOnSitePickup: flags.allowOnSitePickup,
|
||||||
sortOrder: dto.sortOrder ?? 0,
|
allowOnlinePurchase: flags.allowOnlinePurchase,
|
||||||
allowOnSitePickup: dto.allowOnSitePickup ?? false,
|
allowCrossCityDelivery: flags.allowCrossCityDelivery,
|
||||||
visibilityWhitelistEnabled: whitelistEnabled,
|
visibilityWhitelistEnabled: whitelistEnabled,
|
||||||
...(dto.detailContent !== undefined
|
...(dto.detailContent !== undefined
|
||||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||||
: {}),
|
: {}),
|
||||||
...(phones.length
|
...(phones.length
|
||||||
? {
|
? {
|
||||||
visibilityPhones: {
|
visibilityPhones: {
|
||||||
create: phones.map((phone) => ({ phone })),
|
create: phones.map((phone) => ({ phone })),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (dto.coverUrl) {
|
if (dto.coverUrl) {
|
||||||
@@ -143,7 +179,26 @@ export class AdminProductsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async update(id: bigint, dto: UpdateProductDto) {
|
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({
|
await this.prisma.commonProductItem.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
@@ -154,7 +209,13 @@ export class AdminProductsService {
|
|||||||
...(dto.benefitAmount !== undefined ? { benefitAmount: dto.benefitAmount } : {}),
|
...(dto.benefitAmount !== undefined ? { benefitAmount: dto.benefitAmount } : {}),
|
||||||
...(dto.status !== undefined ? { status: dto.status as 'DRAFT' | 'ON_SALE' | 'OFF_SALE' } : {}),
|
...(dto.status !== undefined ? { status: dto.status as 'DRAFT' | 'ON_SALE' | 'OFF_SALE' } : {}),
|
||||||
...(dto.sortOrder !== undefined ? { sortOrder: dto.sortOrder } : {}),
|
...(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
|
...(dto.visibilityWhitelistEnabled !== undefined
|
||||||
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||||
: {}),
|
: {}),
|
||||||
@@ -196,6 +257,46 @@ export class AdminProductsService {
|
|||||||
return { ok: true };
|
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[]) {
|
private async syncVisibilityPhones(productId: bigint, phones: string[]) {
|
||||||
await this.prisma.$transaction(async (tx) => {
|
await this.prisma.$transaction(async (tx) => {
|
||||||
await tx.commonProductVisibilityPhone.deleteMany({ where: { productId } });
|
await tx.commonProductVisibilityPhone.deleteMany({ where: { productId } });
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ export class AdminRedeemService {
|
|||||||
if (query.redeemNo) where.redeemNo = { contains: query.redeemNo };
|
if (query.redeemNo) where.redeemNo = { contains: query.redeemNo };
|
||||||
if (query.storeId) where.storeId = BigInt(query.storeId);
|
if (query.storeId) where.storeId = BigInt(query.storeId);
|
||||||
if (query.userId) where.userId = BigInt(query.userId);
|
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([
|
const [items, total] = await Promise.all([
|
||||||
this.prisma.redeemRecord.findMany({
|
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;
|
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()
|
@Injectable()
|
||||||
export class AdminStoresService {
|
export class AdminStoresService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -64,19 +82,23 @@ export class AdminStoresService {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
coverResource: { select: { id: true, url: true } },
|
coverResource: { select: { id: true, url: true } },
|
||||||
|
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
this.prisma.store.count({ where }),
|
this.prisma.store.count({ where }),
|
||||||
]);
|
]);
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
items: items.map((s) =>
|
items: items.map((s) => {
|
||||||
mapStoreCompat({
|
const { visibilityPhones, ...rest } = s;
|
||||||
...s,
|
return mapStoreCompat({
|
||||||
|
...rest,
|
||||||
|
visibilityWhitelistEnabled: s.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||||
partner: s.partnerAccount,
|
partner: s.partnerAccount,
|
||||||
account: s.bindings[0]?.storeAccount ?? null,
|
account: s.bindings[0]?.storeAccount ?? null,
|
||||||
bindings: undefined,
|
bindings: undefined,
|
||||||
}),
|
});
|
||||||
),
|
}),
|
||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -96,6 +118,7 @@ export class AdminStoresService {
|
|||||||
include: { storeAccount: true },
|
include: { storeAccount: true },
|
||||||
},
|
},
|
||||||
coverResource: true,
|
coverResource: true,
|
||||||
|
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||||
_count: { select: { redeemRecords: true, ratings: true } },
|
_count: { select: { redeemRecords: true, ratings: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -111,8 +134,12 @@ export class AdminStoresService {
|
|||||||
take: 5,
|
take: 5,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
const { visibilityPhones, ...rest } = store;
|
||||||
return serializeBigInt(mapStoreCompat({
|
return serializeBigInt(mapStoreCompat({
|
||||||
...store,
|
...rest,
|
||||||
|
visibilityWhitelistEnabled: store.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: visibilityPhones.map((p) => p.phone),
|
||||||
|
partner: store.partnerAccount,
|
||||||
account: store.bindings[0]?.storeAccount ?? null,
|
account: store.bindings[0]?.storeAccount ?? null,
|
||||||
/** 门店端登录手机号(store_account.phone),与 store.phone 应对齐 */
|
/** 门店端登录手机号(store_account.phone),与 store.phone 应对齐 */
|
||||||
loginPhone: store.bindings[0]?.storeAccount?.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;
|
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 =
|
const bankTouched =
|
||||||
dto.bankAccountName !== undefined ||
|
dto.bankAccountName !== undefined ||
|
||||||
dto.bankAccountNo !== undefined ||
|
dto.bankAccountNo !== undefined ||
|
||||||
@@ -307,10 +354,23 @@ export class AdminStoresService {
|
|||||||
...(dto.openTime2 !== undefined ? { openTime2: dto.openTime2 || null } : {}),
|
...(dto.openTime2 !== undefined ? { openTime2: dto.openTime2 || null } : {}),
|
||||||
...(dto.closeTime2 !== undefined ? { closeTime2: dto.closeTime2 || null } : {}),
|
...(dto.closeTime2 !== undefined ? { closeTime2: dto.closeTime2 || null } : {}),
|
||||||
...(dto.avgPrice !== undefined ? { avgPrice: dto.avgPrice } : {}),
|
...(dto.avgPrice !== undefined ? { avgPrice: dto.avgPrice } : {}),
|
||||||
|
...(dto.visibilityWhitelistEnabled !== undefined
|
||||||
|
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||||
|
: {}),
|
||||||
...(latitude != null && longitude != null ? { latitude, longitude } : {}),
|
...(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 (dto.coverUrl) {
|
||||||
if (current.coverResourceId) {
|
if (current.coverResourceId) {
|
||||||
await tx.commonResource.update({
|
await tx.commonResource.update({
|
||||||
@@ -430,6 +490,12 @@ export class AdminStoresService {
|
|||||||
throw new BadRequestException('好客权益券使用规则最多 1000 字');
|
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({
|
const store = await this.prisma.store.create({
|
||||||
data: {
|
data: {
|
||||||
cityId: city.id,
|
cityId: city.id,
|
||||||
@@ -449,11 +515,19 @@ export class AdminStoresService {
|
|||||||
closeTime,
|
closeTime,
|
||||||
openTime2: openTime2 || null,
|
openTime2: openTime2 || null,
|
||||||
closeTime2: closeTime2 || null,
|
closeTime2: closeTime2 || null,
|
||||||
|
visibilityWhitelistEnabled: whitelistEnabled,
|
||||||
...(latitude != null && longitude != null ? { latitude, longitude } : {}),
|
...(latitude != null && longitude != null ? { latitude, longitude } : {}),
|
||||||
status: 'OPEN',
|
status: 'OPEN',
|
||||||
auditStatus: 'APPROVED',
|
auditStatus: 'APPROVED',
|
||||||
auditedAt: new Date(),
|
auditedAt: new Date(),
|
||||||
rejectReason: null,
|
rejectReason: null,
|
||||||
|
...(visibilityPhones.length
|
||||||
|
? {
|
||||||
|
visibilityPhones: {
|
||||||
|
create: visibilityPhones.map((phone) => ({ phone })),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -127,6 +127,17 @@ export class CreateStoreDto {
|
|||||||
@IsNumber()
|
@IsNumber()
|
||||||
@Min(0)
|
@Min(0)
|
||||||
avgPrice?: number;
|
avgPrice?: number;
|
||||||
|
|
||||||
|
/** 开启后仅白名单手机号在 C 端可见 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
|
||||||
|
/** 可见白名单手机号列表 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
visibilityPhones?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateStoreDto {
|
export class UpdateStoreDto {
|
||||||
@@ -215,6 +226,17 @@ export class UpdateStoreDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
bankBranch?: string | null;
|
bankBranch?: string | null;
|
||||||
|
|
||||||
|
/** 开启后仅白名单手机号在 C 端可见 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
|
||||||
|
/** 可见白名单手机号列表 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
visibilityPhones?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CreateStoreAccountDto {
|
export class CreateStoreAccountDto {
|
||||||
@@ -1068,9 +1090,10 @@ export class SaveHqAccountPermissionsDto {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class CreateProductDto {
|
export class CreateProductDto {
|
||||||
|
/** 可选;创建时由服务端自增生成,忽略客户端传入 */
|
||||||
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsNotEmpty()
|
skuCode?: string;
|
||||||
skuCode: string;
|
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
@@ -1110,6 +1133,14 @@ export class CreateProductDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
|
|
||||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
@@ -1173,6 +1204,14 @@ export class UpdateProductDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
allowOnlinePurchase?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
allowCrossCityDelivery?: boolean;
|
||||||
|
|
||||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
|
|||||||
@@ -242,6 +242,21 @@ export class AdminRedeemRecordsQueryDto extends PaginationQueryDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
userId?: string;
|
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 {
|
export class AdminDeliveriesQueryDto extends PaginationQueryDto {
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import { AdminBenefitCouponsController, AdminBenefitLedgersController } from './
|
|||||||
import { AdminBenefitService } from './admin-benefit.service';
|
import { AdminBenefitService } from './admin-benefit.service';
|
||||||
import { AdminRedeemRecordsController, AdminDeliveriesController } from './admin-redeem.controller';
|
import { AdminRedeemRecordsController, AdminDeliveriesController } from './admin-redeem.controller';
|
||||||
import { AdminRedeemService, AdminDeliveriesService } from './admin-redeem.service';
|
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 { AdminHqAccountsController } from './admin-hq-accounts.controller';
|
||||||
import { AdminHqAccountsService } from './admin-hq-accounts.service';
|
import { AdminHqAccountsService } from './admin-hq-accounts.service';
|
||||||
import { AdminProductsController } from './admin-products.controller';
|
import { AdminProductsController } from './admin-products.controller';
|
||||||
@@ -90,6 +92,7 @@ import { AdminFulfillmentProvidersController } from './admin-fulfillment-provide
|
|||||||
AdminBenefitCouponsController,
|
AdminBenefitCouponsController,
|
||||||
AdminBenefitLedgersController,
|
AdminBenefitLedgersController,
|
||||||
AdminRedeemRecordsController,
|
AdminRedeemRecordsController,
|
||||||
|
AdminStoreRatingsController,
|
||||||
AdminDeliveriesController,
|
AdminDeliveriesController,
|
||||||
AdminHqAccountsController,
|
AdminHqAccountsController,
|
||||||
AdminProductsController,
|
AdminProductsController,
|
||||||
@@ -122,6 +125,7 @@ import { AdminFulfillmentProvidersController } from './admin-fulfillment-provide
|
|||||||
AdminCitiesService,
|
AdminCitiesService,
|
||||||
AdminBenefitService,
|
AdminBenefitService,
|
||||||
AdminRedeemService,
|
AdminRedeemService,
|
||||||
|
AdminStoreRatingsService,
|
||||||
AdminDeliveriesService,
|
AdminDeliveriesService,
|
||||||
AdminHqAccountsService,
|
AdminHqAccountsService,
|
||||||
AdminProductsService,
|
AdminProductsService,
|
||||||
|
|||||||
@@ -36,6 +36,19 @@ export class UserRedeemController {
|
|||||||
rating(@CurrentUser() user: AuthUser, @Body() body: Record<string, unknown>) {
|
rating(@CurrentUser() user: AuthUser, @Body() body: Record<string, unknown>) {
|
||||||
return this.redeemService.submitRating(user.actorId, body as never);
|
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')
|
@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')
|
@Post('phone/send-lookup-sms')
|
||||||
sendPhoneLookupSms(@CurrentUser() user: AuthUser, @Body() body: RedeemPhoneSendLookupSmsDto) {
|
sendPhoneLookupSms(@CurrentUser() user: AuthUser, @Body() body: RedeemPhoneSendLookupSmsDto) {
|
||||||
return this.redeemService.sendPhoneLookupSms(user.actorId, user.storeId!, body.phone);
|
return this.redeemService.sendPhoneLookupSms(user.actorId, user.storeId!, body.phone);
|
||||||
|
|||||||
@@ -38,6 +38,15 @@ type TokenPayload = {
|
|||||||
allocations?: Array<{ couponId: string; amount: number }>;
|
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 & {
|
type PendingSnapshot = TokenPayload & {
|
||||||
redeemType: 'DIRECT' | 'COUPON';
|
redeemType: 'DIRECT' | 'COUPON';
|
||||||
};
|
};
|
||||||
@@ -169,6 +178,7 @@ export class RedeemService {
|
|||||||
) {
|
) {
|
||||||
const settlementRate = Number(account.store.settlementRate);
|
const settlementRate = Number(account.store.settlementRate);
|
||||||
const settleAmount = calcRedeemSettleAmount(amount, settlementRate);
|
const settleAmount = calcRedeemSettleAmount(amount, settlementRate);
|
||||||
|
const redeemChannel = analyticsExtra?.channel === 'phone' ? 'PHONE' : 'SCAN';
|
||||||
|
|
||||||
let record;
|
let record;
|
||||||
try {
|
try {
|
||||||
@@ -183,6 +193,7 @@ export class RedeemService {
|
|||||||
storeId: account.storeId,
|
storeId: account.storeId,
|
||||||
amount,
|
amount,
|
||||||
settleAmount,
|
settleAmount,
|
||||||
|
channel: redeemChannel,
|
||||||
allocations: {
|
allocations: {
|
||||||
create: normalizedAllocations.map((item, index) => ({
|
create: normalizedAllocations.map((item, index) => ({
|
||||||
couponId: BigInt(item.couponId),
|
couponId: BigInt(item.couponId),
|
||||||
@@ -1070,6 +1081,51 @@ export class RedeemService {
|
|||||||
return { list: serializeBigInt(list), total, page, pageSize };
|
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) {
|
async getShopDashboard(storeAccountId: bigint, storeId: bigint) {
|
||||||
const binding = await this.prisma.storeAccountStore.findUniqueOrThrow({
|
const binding = await this.prisma.storeAccountStore.findUniqueOrThrow({
|
||||||
where: { storeAccountId_storeId: { storeAccountId, storeId } },
|
where: { storeAccountId_storeId: { storeAccountId, storeId } },
|
||||||
@@ -1082,6 +1138,8 @@ export class RedeemService {
|
|||||||
});
|
});
|
||||||
const todayCount = records.length;
|
const todayCount = records.length;
|
||||||
const todayAmount = records.reduce((sum, r) => sum + Number(r.amount), 0);
|
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({
|
const recent = await this.prisma.redeemRecord.findMany({
|
||||||
where: { storeId },
|
where: { storeId },
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
@@ -1091,15 +1149,102 @@ export class RedeemService {
|
|||||||
store: binding.store,
|
store: binding.store,
|
||||||
todayCount,
|
todayCount,
|
||||||
todayAmount,
|
todayAmount,
|
||||||
|
todayScanCount,
|
||||||
|
todayPhoneCount,
|
||||||
recentRecords: recent,
|
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 }) {
|
async submitRating(userId: bigint, body: { redeemRecordId: string; serviceScore: number; envScore: number }) {
|
||||||
const record = await this.prisma.redeemRecord.findFirst({
|
const record = await this.prisma.redeemRecord.findFirst({
|
||||||
where: { id: BigInt(body.redeemRecordId), userId },
|
where: { id: BigInt(body.redeemRecordId), userId },
|
||||||
});
|
});
|
||||||
if (!record) throw new NotFoundException('核销记录不存在');
|
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({
|
const rating = await this.prisma.storeRating.create({
|
||||||
data: {
|
data: {
|
||||||
redeemRecordId: record.id,
|
redeemRecordId: record.id,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { SettlementService } from './settlement.service';
|
|||||||
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||||
import { ShopStoreGuard } from '../../common/guards/shop-store.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 { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
@@ -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')
|
@Controller('admin/store-payouts')
|
||||||
@UseGuards(HqAuthGuard)
|
@UseGuards(HqAuthGuard)
|
||||||
export class AdminStorePayoutController {
|
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')
|
@Controller('admin/store-bills')
|
||||||
@UseGuards(HqAuthGuard)
|
@UseGuards(HqAuthGuard)
|
||||||
export class AdminStoreBillController {
|
export class AdminStoreBillController {
|
||||||
|
|||||||
@@ -9,10 +9,13 @@ import {
|
|||||||
AdminPartnerBillController,
|
AdminPartnerBillController,
|
||||||
AdminStoreBillController,
|
AdminStoreBillController,
|
||||||
AdminStorePayoutController,
|
AdminStorePayoutController,
|
||||||
|
AdminStoreSettlementController,
|
||||||
|
AdminStoreWithdrawController,
|
||||||
AdminWineryBillController,
|
AdminWineryBillController,
|
||||||
PartnerMeController,
|
PartnerMeController,
|
||||||
SettlementController,
|
SettlementController,
|
||||||
ShopPayoutController,
|
ShopPayoutController,
|
||||||
|
ShopWithdrawController,
|
||||||
} from './settlement.controller';
|
} from './settlement.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -21,7 +24,10 @@ import {
|
|||||||
SettlementController,
|
SettlementController,
|
||||||
PartnerMeController,
|
PartnerMeController,
|
||||||
ShopPayoutController,
|
ShopPayoutController,
|
||||||
|
ShopWithdrawController,
|
||||||
|
AdminStoreWithdrawController,
|
||||||
AdminStorePayoutController,
|
AdminStorePayoutController,
|
||||||
|
AdminStoreSettlementController,
|
||||||
AdminStoreBillController,
|
AdminStoreBillController,
|
||||||
AdminPartnerBillController,
|
AdminPartnerBillController,
|
||||||
AdminWineryBillController,
|
AdminWineryBillController,
|
||||||
|
|||||||
@@ -1,9 +1,20 @@
|
|||||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { DEFAULT_XFX_LOGISTICS_PRICING, WINERY_SETTLEMENT_RATE } from '@dukang/shared-types';
|
import {
|
||||||
import { calcLogisticsFeeByBottles, type LogisticsPricingRule } from '@dukang/domain';
|
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 { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
|
import { AlertService } from '../../common/alert/alert.service';
|
||||||
import { AnalyticsService } from '../analytics/analytics.service';
|
import { AnalyticsService } from '../analytics/analytics.service';
|
||||||
import { PartnerCityService } from '../city-scope/partner-city.service';
|
import { PartnerCityService } from '../city-scope/partner-city.service';
|
||||||
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
import { FulfillmentProviderService } from '../fulfillment/fulfillment-provider.service';
|
||||||
@@ -33,6 +44,28 @@ function round2(n: number) {
|
|||||||
return Math.round(n * 100) / 100;
|
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()
|
@Injectable()
|
||||||
export class SettlementService {
|
export class SettlementService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -40,6 +73,7 @@ export class SettlementService {
|
|||||||
private readonly analyticsService: AnalyticsService,
|
private readonly analyticsService: AnalyticsService,
|
||||||
private readonly partnerCityService: PartnerCityService,
|
private readonly partnerCityService: PartnerCityService,
|
||||||
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
private readonly fulfillmentProviderService: FulfillmentProviderService,
|
||||||
|
private readonly alert: AlertService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// ─── Store payout (line) ─────────────────────────────
|
// ─── Store payout (line) ─────────────────────────────
|
||||||
@@ -99,6 +133,476 @@ export class SettlementService {
|
|||||||
return serializeBigInt({ items, total, page, pageSize });
|
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: {
|
async listAdminStorePayouts(query: {
|
||||||
page?: number;
|
page?: number;
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
@@ -277,6 +781,9 @@ export class SettlementService {
|
|||||||
where: {
|
where: {
|
||||||
storeBillId: null,
|
storeBillId: null,
|
||||||
createdAt: { gte: start, lt: end },
|
createdAt: { gte: start, lt: end },
|
||||||
|
// 排除已锁定在待审提现单中的明细,避免出账与提现双占
|
||||||
|
withdrawItem: null,
|
||||||
|
status: 'PENDING',
|
||||||
},
|
},
|
||||||
include: { store: { select: { id: true, settlementRate: true } } },
|
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 };
|
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: {
|
async listAdminStoreBills(query: {
|
||||||
page?: number;
|
page?: number;
|
||||||
pageSize?: number;
|
pageSize?: number;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { StoreService } from './store.service';
|
|||||||
import { StoreCategoryService } from './store-category.service';
|
import { StoreCategoryService } from './store-category.service';
|
||||||
import { RedeemService } from '../redeem/redeem.service';
|
import { RedeemService } from '../redeem/redeem.service';
|
||||||
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
|
import { OptionalJwtAuthGuard } from '../../common/guards/optional-jwt-auth.guard';
|
||||||
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
|
||||||
import { RequirePartnerPermissions } from '../../common/decorators/partner-permission.decorator';
|
import { RequirePartnerPermissions } from '../../common/decorators/partner-permission.decorator';
|
||||||
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
import { PartnerPermissionGuard } from '../../common/guards/partner-permission.guard';
|
||||||
@@ -11,22 +12,53 @@ import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
|||||||
|
|
||||||
@Controller('stores')
|
@Controller('stores')
|
||||||
export class PublicStoreController {
|
export class PublicStoreController {
|
||||||
constructor(private readonly storeService: StoreService) {}
|
constructor(
|
||||||
|
private readonly storeService: StoreService,
|
||||||
|
private readonly redeemService: RedeemService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
|
async list(
|
||||||
|
@CurrentUser() user: AuthUser | undefined,
|
||||||
@Query('cityCode') cityCode?: string,
|
@Query('cityCode') cityCode?: string,
|
||||||
@Query('lat') lat?: string,
|
@Query('lat') lat?: string,
|
||||||
@Query('lng') lng?: string,
|
@Query('lng') lng?: string,
|
||||||
) {
|
) {
|
||||||
const userLat = lat != null && lat !== '' ? Number(lat) : undefined;
|
const userLat = lat != null && lat !== '' ? Number(lat) : undefined;
|
||||||
const userLng = lng != null && lng !== '' ? Number(lng) : 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')
|
@Get(':id')
|
||||||
detail(@Param('id') id: string) {
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
return this.storeService.getStore(BigInt(id));
|
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;
|
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 {
|
function parseOptionalCoord(value: unknown, kind: 'lat' | 'lng' = 'lng'): number | null {
|
||||||
if (value == null || value === '') return null;
|
if (value == null || value === '') return null;
|
||||||
const n = typeof value === 'number' ? value : Number(value);
|
const n = typeof value === 'number' ? value : Number(value);
|
||||||
@@ -96,7 +107,34 @@ export class StoreService {
|
|||||||
return { latitude: geo.latitude, longitude: geo.longitude };
|
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' };
|
const where: Record<string, unknown> = { status: 'OPEN' };
|
||||||
if (cityCode) {
|
if (cityCode) {
|
||||||
const city = await this.prisma.commonCity.findFirst({ where: { code: 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({
|
const stores = await this.prisma.store.findMany({
|
||||||
where: where as never,
|
where: where as never,
|
||||||
include: { category: true, coverResource: true },
|
include: {
|
||||||
|
category: true,
|
||||||
|
coverResource: true,
|
||||||
|
visibilityPhones: { select: { phone: true } },
|
||||||
|
},
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const visible = stores.filter((s) => this.isVisibleToViewer(s, viewer));
|
||||||
|
|
||||||
const hasUser =
|
const hasUser =
|
||||||
userLat != null &&
|
userLat != null &&
|
||||||
userLng != null &&
|
userLng != null &&
|
||||||
@@ -121,10 +165,11 @@ export class StoreService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const items: StoreListItem[] = [];
|
const items: StoreListItem[] = [];
|
||||||
for (const store of stores) {
|
for (const store of visible) {
|
||||||
const coords = await this.ensureStoreCoordinates(store);
|
const coords = await this.ensureStoreCoordinates(store);
|
||||||
|
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||||
const mapped = mapStoreCompat({
|
const mapped = mapStoreCompat({
|
||||||
...store,
|
...rest,
|
||||||
latitude: coords?.latitude ?? store.latitude,
|
latitude: coords?.latitude ?? store.latitude,
|
||||||
longitude: coords?.longitude ?? store.longitude,
|
longitude: coords?.longitude ?? store.longitude,
|
||||||
});
|
});
|
||||||
@@ -146,20 +191,27 @@ export class StoreService {
|
|||||||
return serializeBigInt(items);
|
return serializeBigInt(items);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getStore(id: bigint) {
|
async getStore(id: bigint, viewer?: StoreViewer) {
|
||||||
const store = await this.prisma.store.findFirst({
|
const store = await this.prisma.store.findFirst({
|
||||||
where: { id, status: 'OPEN' },
|
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 coords = await this.ensureStoreCoordinates(store);
|
||||||
const media = await this.prisma.commonResource.findMany({
|
const media = await this.prisma.commonResource.findMany({
|
||||||
where: { ownerType: 'STORE', ownerId: id, status: 'ACTIVE', bizType: 'ENV' },
|
where: { ownerType: 'STORE', ownerId: id, status: 'ACTIVE', bizType: 'ENV' },
|
||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
});
|
});
|
||||||
|
const { visibilityPhones: _phones, visibilityWhitelistEnabled: _wl, ...rest } = store;
|
||||||
return serializeBigInt(
|
return serializeBigInt(
|
||||||
mapStoreCompat({
|
mapStoreCompat({
|
||||||
...store,
|
...rest,
|
||||||
latitude: coords?.latitude ?? store.latitude,
|
latitude: coords?.latitude ?? store.latitude,
|
||||||
longitude: coords?.longitude ?? store.longitude,
|
longitude: coords?.longitude ?? store.longitude,
|
||||||
media,
|
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(
|
const check = validateMinPurchase(
|
||||||
deliveryType,
|
deliveryType,
|
||||||
body.quantity,
|
body.quantity,
|
||||||
@@ -121,8 +140,13 @@ export class TradeService {
|
|||||||
/** 起购未满足时仍返回预览,供确认页改数量;下单接口仍会硬校验 */
|
/** 起购未满足时仍返回预览,供确认页改数量;下单接口仍会硬校验 */
|
||||||
quantityOk: check.ok,
|
quantityOk: check.ok,
|
||||||
quantityMessage: check.ok ? null : (check.message ?? null),
|
quantityMessage: check.ok ? null : (check.message ?? null),
|
||||||
|
/** 地址/履约未满足时仍返回预览,供确认页提示换地址;下单接口仍会硬校验 */
|
||||||
|
addressOk,
|
||||||
|
addressMessage,
|
||||||
minQty,
|
minQty,
|
||||||
onSitePickup,
|
onSitePickup,
|
||||||
|
allowCrossCityDelivery: product.allowCrossCityDelivery !== false,
|
||||||
|
allowOnlinePurchase: product.allowOnlinePurchase !== false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,6 +165,9 @@ export class TradeService {
|
|||||||
if (preview.quantityOk === false) {
|
if (preview.quantityOk === false) {
|
||||||
throw new BadRequestException(preview.quantityMessage || '购买数量不满足起购要求');
|
throw new BadRequestException(preview.quantityMessage || '购买数量不满足起购要求');
|
||||||
}
|
}
|
||||||
|
if (preview.addressOk === false) {
|
||||||
|
throw new BadRequestException(preview.addressMessage || '收货地址不可用');
|
||||||
|
}
|
||||||
|
|
||||||
const onSitePickup = !!body.onSitePickup || preview.deliveryType === 'ON_SITE_PICKUP';
|
const onSitePickup = !!body.onSitePickup || preview.deliveryType === 'ON_SITE_PICKUP';
|
||||||
let receiverName = '现场取货';
|
let receiverName = '现场取货';
|
||||||
@@ -1121,6 +1148,9 @@ export class TradeService {
|
|||||||
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
||||||
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
||||||
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
||||||
|
allowOnlinePurchase: (p as { allowOnlinePurchase?: boolean }).allowOnlinePurchase !== false,
|
||||||
|
allowCrossCityDelivery:
|
||||||
|
(p as { allowCrossCityDelivery?: boolean }).allowCrossCityDelivery !== false,
|
||||||
})),
|
})),
|
||||||
promoCodes,
|
promoCodes,
|
||||||
stores: stores.map((s) => ({
|
stores: stores.map((s) => ({
|
||||||
@@ -1166,6 +1196,19 @@ export class TradeService {
|
|||||||
if (receiverCity && receiverCity !== city.name && receiverCity !== '郑州市') {
|
if (receiverCity && receiverCity !== city.name && receiverCity !== '郑州市') {
|
||||||
deliveryType = 'CROSS_CITY';
|
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(
|
const check = validateMinPurchase(
|
||||||
@@ -1486,6 +1529,9 @@ export class TradeService {
|
|||||||
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
benefitAmount: p.benefitAmount != null ? Number(p.benefitAmount) : null,
|
||||||
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
coverUrl: (p as { mainImageUrl?: string | null }).mainImageUrl ?? null,
|
||||||
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
allowOnSitePickup: !!(p as { allowOnSitePickup?: boolean }).allowOnSitePickup,
|
||||||
|
allowOnlinePurchase: (p as { allowOnlinePurchase?: boolean }).allowOnlinePurchase !== false,
|
||||||
|
allowCrossCityDelivery:
|
||||||
|
(p as { allowCrossCityDelivery?: boolean }).allowCrossCityDelivery !== false,
|
||||||
})),
|
})),
|
||||||
promoCodes,
|
promoCodes,
|
||||||
stores: [],
|
stores: [],
|
||||||
|
|||||||
Reference in New Issue
Block a user