Compare commits
89 Commits
| 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 | |||
| 5deffbdbfb | |||
| ad757e9ba8 | |||
| 07fbb74485 | |||
| ca6fa2244b | |||
| e63b57db19 | |||
| 205c1110c2 | |||
| fb4432b307 | |||
| 3328c52cb4 | |||
| ab44515e8b | |||
| cb6ecaaba6 | |||
| 78365d648c | |||
| 4ba51c502b | |||
| e9eddbb26e | |||
| ab3b230d01 | |||
| c00ca3620d | |||
| 45d3d8164d | |||
| defdcb409f | |||
| 4d76ee6d0e | |||
| bdc9dbde8d | |||
| 3fc2f23e10 | |||
| 09e732bfa3 | |||
| 50ba6e9c56 | |||
| 6a23e79f4c | |||
| 2dbe665bdc | |||
| 8d6c0f9ac0 | |||
| 51f2b5fbfa | |||
| 2cd4e25682 | |||
| 1a0afb6d39 | |||
| 05dffbfa15 | |||
| a0a6c14758 | |||
| ed7fd4e013 | |||
| bf9cd1bffd | |||
| ca621c9db8 | |||
| 507a21a318 | |||
| f396cb1fef | |||
| 2b85f63e2b | |||
| e742f1e88b | |||
| 2ccadce34a | |||
| b0ff254cd8 | |||
| c3362851ff | |||
| 804054df33 | |||
| 1bc3bec977 | |||
| 81a6e3674b |
@@ -29,4 +29,5 @@ chore(shared-types): add OrderStatus enum
|
||||
## Agent 行为
|
||||
|
||||
- **仅用户明确要求时** 才执行 git commit / push
|
||||
- 不 amend 已推送的 commit,不 force push main/master
|
||||
- 不 amend 已推送的 commit,不 force push main/master/dev
|
||||
- 发版:`dev`→测试(staging),`main`→生产;用户只说「发布/发版」默认发**生产**(见 dukang-release skill);明确说「发测试」才发 staging
|
||||
|
||||
@@ -1,89 +1,91 @@
|
||||
---
|
||||
name: dukang-release
|
||||
description: >-
|
||||
杜康好客生产发布流程:dev_jacy 提交合并到 dev,并用 deploy.sh 发版。
|
||||
Use when the user says 发布、上传、deploy、上线、发版, or @杜康发布 / @dukang-release.
|
||||
杜康好客发布流程:dev→测试(staging),main→生产;同机双栈。
|
||||
Use when the user says 发布、上传、deploy、上线、发版、发测试、发生产,
|
||||
or @杜康发布 / @dukang-release.
|
||||
---
|
||||
|
||||
# 杜康发布
|
||||
|
||||
将已完成改动发到生产(`aliyun-smarthr`)。**仅用户明确要求发布时执行。**
|
||||
同机双栈:`/opt/dukang-staging`(测试)与 `/opt/dukang`(生产)。**仅用户明确要求发布时执行。**
|
||||
|
||||
## 分支约定
|
||||
## 分支与环境
|
||||
|
||||
| 分支 | 用途 |
|
||||
|------|------|
|
||||
| `dev_jacy` | 日常开发 / 提交 |
|
||||
| `dev` | **发布分支**(服务器拉这个) |
|
||||
| 分支 | 环境 | 目录 | 端口 | 域名 |
|
||||
|------|------|------|------|------|
|
||||
| `dev_jacy` | 日常开发 | 本机 | — | — |
|
||||
| `dev` | **staging 测试** | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||
| `main` | **production 生产** | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||
|
||||
默认:`dev_jacy` → merge → `dev` → 部署。勿 force push `main`/`dev`。
|
||||
默认:`dev_jacy` → merge → `dev` → merge → `main` → **发生产**。勿 force push `main`/`dev`。
|
||||
|
||||
> **团队约定(2026-08)**:用户说「发布 / 发版 / 直接发版」且**未特别强调**时 → **发生产(production)**。
|
||||
> 仅当用户明确说「发测试 / staging / 测试环境」时 → 发 staging。
|
||||
|
||||
用户说「发生产 / 上线生产 / 发版」→ 用 `deploy-prod.sh`。
|
||||
用户说「发测试」→ 用 `deploy-staging.sh`。
|
||||
|
||||
## 标准流程(Windows)
|
||||
|
||||
PowerShell 下 **分支名必须加引号**(否则 `checkout` 与 `dev` 会被粘成 `checkoutdev`)。
|
||||
PowerShell 下 **分支名必须加引号**。
|
||||
|
||||
### 1. 提交(在 `dev_jacy`)
|
||||
|
||||
```powershell
|
||||
git status -sb
|
||||
git add <files>
|
||||
git commit -m @"
|
||||
fix(scope): summary
|
||||
|
||||
Optional body.
|
||||
"@
|
||||
```
|
||||
|
||||
- Conventional Commits;不提交 `.env` / `dist` / `node_modules`
|
||||
- 用户未要求 commit 时不要擅自提交
|
||||
|
||||
### 2. 推送并合并到 `dev`
|
||||
### A. 发测试(日常)
|
||||
|
||||
```powershell
|
||||
# 1. 在 dev_jacy 提交(用户要求时)
|
||||
git push -u origin HEAD
|
||||
git checkout "dev"
|
||||
git pull origin "dev"
|
||||
git merge "dev_jacy" -m "merge(dev_jacy): <简述>"
|
||||
git push origin "dev"
|
||||
git checkout "dev_jacy"
|
||||
|
||||
# 2. 发 staging
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy-staging.sh" -- --skip-db
|
||||
```
|
||||
|
||||
### 3. 远程发版
|
||||
|
||||
本机无 WSL bash 时用 **Git Bash**:
|
||||
### B. 发生产(验收后)
|
||||
|
||||
```powershell
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy.sh" --branch "dev" -- --skip-db
|
||||
git checkout "main"
|
||||
git pull origin "main"
|
||||
git merge "dev" -m "merge(dev): <简述>"
|
||||
git push origin "main"
|
||||
git checkout "dev_jacy"
|
||||
|
||||
& "C:\Program Files\Git\bin\bash.exe" "<repo>/deploy/deploy-prod.sh" -- --skip-db
|
||||
```
|
||||
|
||||
- 默认加 `--skip-db`(无迁移时)
|
||||
- 有 Prisma 迁移时去掉 `--skip-db`,按用户确认是否 `--seed` / `--accept-data-loss`
|
||||
- `deploy/deploy.env` 提供 `DEPLOY_HOST` 等(勿提交密钥)
|
||||
- 有 Prisma 迁移:先在 **staging** 跑通(可 `--seed` / `--accept-data-loss`),再生产去掉 `--skip-db`
|
||||
- Staging 微信:正式号 + 全 Mock(`.env.staging`)
|
||||
- `deploy/deploy.env` 提供 `DEPLOY_HOST`、`STAGING_APP_ROOT`、`PROD_APP_ROOT`(勿提交密钥)
|
||||
|
||||
### 4. 等待完成
|
||||
### 首次启用 Staging
|
||||
|
||||
后台跑部署时轮询终端输出,成功标志:
|
||||
服务器一次性:`bash deploy/bootstrap-staging.sh`(见脚本说明)→ 配 `.env.staging` → DNS `*-test` → nginx → `deploy-staging.sh -- --seed`
|
||||
|
||||
### 同步环境变量
|
||||
|
||||
```powershell
|
||||
bash deploy/sync-api-env.sh staging
|
||||
bash deploy/sync-api-env.sh production
|
||||
```
|
||||
|
||||
## 等待完成
|
||||
|
||||
- 出现 `发版完成`
|
||||
- `exit_code: 0`
|
||||
- `mini-user(h5): 200`(或对应前端 200)
|
||||
- `mini-user(h5): 200` / `api: 200`
|
||||
|
||||
说明:API 健康检查短暂 `FAIL`/`000` 多为重启中,以 `发版完成` + `exit_code: 0` 为准。
|
||||
## 回复用户
|
||||
|
||||
### 5. 回复用户
|
||||
|
||||
一句说明:已合并 commit、发版结果、建议微信强刷验证。
|
||||
|
||||
## 常用变体
|
||||
|
||||
| 场景 | 做法 |
|
||||
|------|------|
|
||||
| 仅部署已推送的 `dev` | 跳过 commit/merge,直接跑 `deploy.sh --branch "dev" -- --skip-db` |
|
||||
| 检查服务器 | `deploy.sh --branch "dev" --check` |
|
||||
| 含 DB | `deploy.sh --branch "dev" --`(无 skip-db)或按用户给 seed 参数 |
|
||||
说明:环境(测试/生产)、commit、建议硬刷验证。测试后台有橙色「测试环境」条。
|
||||
|
||||
## 禁止
|
||||
|
||||
- 不 amend 已推送 commit;不 force push `main`/`master`/`dev`
|
||||
- 不把 `.env` / 私钥打进仓库
|
||||
- 用户只说「修好」未说发布时 → **只改代码,不发版**
|
||||
- 不 amend 已推送 commit;不 force push `main`/`dev`
|
||||
- 不把 `.env*` 私钥打进仓库
|
||||
- **禁止**再用 `dev` 直发生产
|
||||
- 用户只说「修好」未说发布 → 只改代码,不发版
|
||||
|
||||
@@ -8,7 +8,13 @@ server/dukang-api/.env
|
||||
server/dukang-api/.env.development
|
||||
server/dukang-api/.env.production
|
||||
server/dukang-api/.env.production.local
|
||||
server/dukang-api/.env.staging
|
||||
server/dukang-api/.env.staging.local
|
||||
deploy/deploy.env
|
||||
deploy/.staging-mysql.pass
|
||||
deploy/_ops-*.log
|
||||
deploy/_ops-*.sh
|
||||
|
||||
.DS_Store
|
||||
coverage/
|
||||
*.tsbuildinfo
|
||||
|
||||
@@ -137,6 +137,19 @@ C 端门店仅 status=OPEN
|
||||
订单 Tab:待付款 | 已付款 | 已完成
|
||||
```
|
||||
|
||||
## 环境与发版
|
||||
|
||||
| 环境 | 分支 | 目录 | 端口 | 域名 |
|
||||
|------|------|------|------|------|
|
||||
| local | `dev_jacy` | 本机 Docker 6016/6017 | API `:3000` | — |
|
||||
| **staging 测试** | `dev` | `/opt/dukang-staging` | 8190–8194 | `*-test.dukanghaoke.com` |
|
||||
| **production 生产** | `main` | `/opt/dukang` | 8090–8094 | `*.dukanghaoke.com` |
|
||||
|
||||
- 日常发布 → `deploy/deploy-staging.sh`(`dev`)
|
||||
- 生产发布 → `deploy/deploy-prod.sh`(`main`,验收后)
|
||||
- Staging:正式微信 + 全 Mock;配置见 `.env.staging.example`
|
||||
- 详情:`@dukang-release` / `.cursor/skills/dukang-release/SKILL.md`
|
||||
|
||||
## 提交与 PR
|
||||
|
||||
- Conventional Commits:`feat(trade):`、`fix(redeem):`;scope = 端或模块
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -13,6 +13,8 @@
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"antd": "^5.22.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
@@ -6,6 +6,7 @@ import DashboardPage from './pages/DashboardPage';
|
||||
import UsersPage from './pages/UsersPage';
|
||||
import OrdersPage from './pages/OrdersPage';
|
||||
import StoresPage from './pages/StoresPage';
|
||||
import StoreRatingsPage from './pages/StoreRatingsPage';
|
||||
import StoreAccountsPage from './pages/StoreAccountsPage';
|
||||
import BenefitCouponsPage from './pages/BenefitCouponsPage';
|
||||
import BenefitLedgersPage from './pages/BenefitLedgersPage';
|
||||
@@ -78,6 +79,7 @@ export default function App() {
|
||||
<Route path="/products" element={<ProductsPage />} />
|
||||
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||
<Route path="/stores" element={<StoresPage />} />
|
||||
<Route path="/store-ratings" element={<StoreRatingsPage />} />
|
||||
<Route path="/store-categories" element={<StoreCategoriesPage />} />
|
||||
<Route path="/store-accounts" element={<StoreAccountsPage />} />
|
||||
<Route path="/store-media" element={<StoreMediaPage />} />
|
||||
@@ -94,11 +96,19 @@ export default function App() {
|
||||
<Route path="/redeem-pending" element={<PendingRedeemPage />} />
|
||||
<Route path="/redeem/debug" element={<RedeemDebugPage />} />
|
||||
<Route path="/finance/store-bills" element={<StoreBillsPage />} />
|
||||
<Route
|
||||
path="/finance/store-withdrawals"
|
||||
element={<Navigate to="/finance/store-bills?kind=WITHDRAW" replace />}
|
||||
/>
|
||||
<Route path="/finance/partner-bills" element={<PartnerBillsPage />} />
|
||||
<Route path="/finance/winery-bills" element={<WineryBillsPage />} />
|
||||
<Route path="/finance/logistics-bills" element={<LogisticsBillsPage />} />
|
||||
<Route path="/store-bills" element={<Navigate to="/finance/store-bills" replace />} />
|
||||
<Route path="/store-payouts" element={<Navigate to="/finance/store-bills" replace />} />
|
||||
<Route
|
||||
path="/store-withdrawals"
|
||||
element={<Navigate to="/finance/store-bills?kind=WITHDRAW" replace />}
|
||||
/>
|
||||
<Route path="/partner-bills" element={<Navigate to="/finance/partner-bills" replace />} />
|
||||
<Route path="/tickets" element={<TicketsPage />} />
|
||||
<Route path="/tickets/support" element={<SupportTicketsPage />} />
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
QRCode,
|
||||
Radio,
|
||||
Select,
|
||||
Space,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import type {
|
||||
HqProxyOrderCreateRequest,
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
} from '@dukang/shared-types';
|
||||
import ChinaRegionCascader from './ChinaRegionCascader';
|
||||
import { parseRegionCodes } from '../lib/china-region';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
type ProxyOrderModalProps = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: (order: { id: string; orderNo: string }) => void;
|
||||
};
|
||||
|
||||
type PayStatus = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payStatus: string;
|
||||
};
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrderModalProps) {
|
||||
const [options, setOptions] = useState<PartnerProxyOrderOptions | null>(null);
|
||||
const [loadingOptions, setLoadingOptions] = useState(false);
|
||||
const [phone, setPhone] = useState('');
|
||||
const [receiverName, setReceiverName] = useState('');
|
||||
const [regionCodes, setRegionCodes] = useState<string[]>([]);
|
||||
const [addressDetail, setAddressDetail] = useState('');
|
||||
const [productId, setProductId] = useState<string>();
|
||||
const [quantity, setQuantity] = useState(2);
|
||||
const [promoCodeId, setPromoCodeId] = useState<string>();
|
||||
const [deliveryMode, setDeliveryMode] = useState<PartnerProxyDeliveryMode>('ADDRESS');
|
||||
const [autoReceive, setAutoReceive] = useState(false);
|
||||
const [preview, setPreview] = useState<PartnerProxyOrderPreviewResult | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [payLoading, setPayLoading] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setLoadingOptions(true);
|
||||
request<PartnerProxyOrderOptions>('/admin/proxy-orders/options')
|
||||
.then((data) => {
|
||||
setOptions(data);
|
||||
if (data.products[0]) setProductId(data.products[0].id);
|
||||
})
|
||||
.catch((e) => message.error(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoadingOptions(false));
|
||||
}, [open]);
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const allowOnline = selectedProduct ? selectedProduct.allowOnlinePurchase !== false : true;
|
||||
const allowOnSite = !!selectedProduct?.allowOnSitePickup;
|
||||
const allowCrossCity = selectedProduct ? selectedProduct.allowCrossCityDelivery !== false : true;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !selectedProduct) return;
|
||||
if (!allowOnline && allowOnSite && deliveryMode !== 'ON_SITE_PICKUP') {
|
||||
setDeliveryMode('ON_SITE_PICKUP');
|
||||
return;
|
||||
}
|
||||
if (allowOnline && !allowOnSite && deliveryMode !== 'ADDRESS') {
|
||||
setDeliveryMode('ADDRESS');
|
||||
}
|
||||
}, [open, selectedProduct, allowOnline, allowOnSite, deliveryMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !productId || quantity < 1 || step !== 'form') {
|
||||
if (step === 'form') setPreview(null);
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
setPreviewLoading(true);
|
||||
request<PartnerProxyOrderPreviewResult>('/admin/proxy-orders/preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
productId,
|
||||
quantity,
|
||||
deliveryMode,
|
||||
receiverCity: deliveryMode === 'ADDRESS' ? region?.city || undefined : undefined,
|
||||
receiverDistrict: deliveryMode === 'ADDRESS' ? region?.district || undefined : undefined,
|
||||
}),
|
||||
})
|
||||
.then(setPreview)
|
||||
.catch(() => setPreview(null))
|
||||
.finally(() => setPreviewLoading(false));
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [open, productId, quantity, deliveryMode, region?.city, region?.district, step]);
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
function resetForm() {
|
||||
stopPoll();
|
||||
setPhone('');
|
||||
setReceiverName('');
|
||||
setRegionCodes([]);
|
||||
setAddressDetail('');
|
||||
setQuantity(2);
|
||||
setPromoCodeId(undefined);
|
||||
setDeliveryMode('ADDRESS');
|
||||
setAutoReceive(false);
|
||||
setPreview(null);
|
||||
setProductId(options?.products[0]?.id);
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
setCodeUrl(null);
|
||||
setPayLoading(false);
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
resetForm();
|
||||
onClose();
|
||||
}
|
||||
|
||||
function validateForm(): string | null {
|
||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||
if (!productId) return '请选择商品';
|
||||
if (deliveryMode === 'ADDRESS') {
|
||||
if (!allowOnline) return '该商品不支持线上购买';
|
||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||
if (!addressDetail.trim()) return '请填写详细地址';
|
||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||
} else if (!allowOnSite) {
|
||||
return '该商品不支持现场提货';
|
||||
}
|
||||
if (!preview) return '请等待费用计算完成';
|
||||
return null;
|
||||
}
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<PayStatus>(`/admin/proxy-orders/${orderId}/pay-status`)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
message.success(`支付成功:${st.orderNo}`);
|
||||
const payload = { id: st.id, orderNo: st.orderNo };
|
||||
resetForm();
|
||||
onSuccess(payload);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const err = validateForm();
|
||||
if (err) {
|
||||
message.warning(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: HqProxyOrderCreateRequest = {
|
||||
phone: phone.trim(),
|
||||
deliveryMode,
|
||||
autoReceive: deliveryMode === 'ADDRESS' ? true : undefined,
|
||||
receiverName: receiverName.trim() || undefined,
|
||||
province: deliveryMode === 'ADDRESS' ? region?.province : undefined,
|
||||
city: deliveryMode === 'ADDRESS' ? region?.city : undefined,
|
||||
district: deliveryMode === 'ADDRESS' ? region?.district : undefined,
|
||||
addressDetail: deliveryMode === 'ADDRESS' ? addressDetail.trim() : undefined,
|
||||
productId: productId!,
|
||||
quantity,
|
||||
promoCodeId: promoCodeId || undefined,
|
||||
};
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<ProxyOrderCreateResponse>('/admin/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setPayLoading(true);
|
||||
const pay = await request<ProxyOrderPayResponse>(`/admin/proxy-orders/${order.id}/pay`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: 'NATIVE' }),
|
||||
});
|
||||
setCodeUrl(pay.codeUrl ?? null);
|
||||
startPoll(order.id);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '下单失败');
|
||||
setStep('form');
|
||||
setCreated(null);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setPayLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryLabel =
|
||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '现场提货'
|
||||
: preview?.deliveryType === 'CROSS_CITY'
|
||||
? '跨城配送'
|
||||
: '同城配送';
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={step === 'pay' ? '代下单 · 待支付' : '代下单'}
|
||||
open={open}
|
||||
onCancel={handleClose}
|
||||
width={640}
|
||||
destroyOnClose
|
||||
footer={
|
||||
step === 'pay' ? (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>关闭</Button>
|
||||
</Space>
|
||||
) : (
|
||||
<Space>
|
||||
<Button onClick={handleClose}>取消</Button>
|
||||
<Button type="primary" loading={submitting || loadingOptions} onClick={() => void submit()}>
|
||||
提交并收款
|
||||
</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
>
|
||||
{step === 'pay' && created ? (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16, textAlign: 'left' }}
|
||||
message={`订单 ${created.orderNo} 待支付 ¥${fmtMoney(created.payAmount)},请扫码支付`}
|
||||
description={
|
||||
created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付完成后订单即为已完成,并发放好客权益'
|
||||
: '支付完成后将进入待发货,由总部履约发货'
|
||||
}
|
||||
/>
|
||||
{payLoading && !codeUrl ? (
|
||||
<Typography.Text type="secondary">正在生成收款码…</Typography.Text>
|
||||
) : codeUrl ? (
|
||||
<Space direction="vertical" size={12} align="center">
|
||||
<QRCode value={codeUrl} size={200} />
|
||||
<Typography.Text type="secondary">请使用微信扫一扫完成支付,成功后自动关闭</Typography.Text>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, wordBreak: 'break-all' }}>
|
||||
{codeUrl}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
) : (
|
||||
<Typography.Text type="danger">收款码生成失败,请关闭后重试</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="提交后生成微信收款码,支付成功后发放好客权益;配送单进入待发货"
|
||||
/>
|
||||
|
||||
<Form layout="vertical">
|
||||
<Form.Item label="用户手机号" required>
|
||||
<Input
|
||||
placeholder="11 位手机号"
|
||||
value={phone}
|
||||
maxLength={11}
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="酒品" required>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
loading={loadingOptions}
|
||||
placeholder="选择商品"
|
||||
value={productId}
|
||||
onChange={setProductId}
|
||||
options={(options?.products ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.name} · ${p.spec} · ¥${fmtMoney(p.price)}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="数量" required>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={quantity}
|
||||
onChange={(v) => setQuantity(Math.max(1, Number(v) || 1))}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{(options?.promoCodes.length ?? 0) > 0 ? (
|
||||
<Form.Item label="绑定推广码(选填)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不绑定"
|
||||
value={promoCodeId}
|
||||
onChange={setPromoCodeId}
|
||||
options={(options?.promoCodes ?? []).map((p) => ({
|
||||
value: p.id,
|
||||
label: `${p.code} · ${p.name}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
|
||||
<Form.Item label="履约方式" required>
|
||||
{allowOnline && allowOnSite ? (
|
||||
<Radio.Group
|
||||
value={deliveryMode}
|
||||
onChange={(e) => {
|
||||
setDeliveryMode(e.target.value);
|
||||
if (e.target.value !== 'ADDRESS') setAutoReceive(false);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ADDRESS', label: '配送到址' },
|
||||
{ value: 'ON_SITE_PICKUP', label: '现场提货' },
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Typography.Text type="secondary">
|
||||
{!allowOnline && allowOnSite
|
||||
? '该商品仅支持现场提货'
|
||||
: allowOnline && !allowOnSite
|
||||
? allowCrossCity
|
||||
? '该商品仅支持配送到址(含跨城)'
|
||||
: '该商品仅支持配送到址(不可跨城)'
|
||||
: '该商品暂无可选履约方式'}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</Form.Item>
|
||||
|
||||
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||
<>
|
||||
<Form.Item label="收货人(选填)">
|
||||
<Input
|
||||
placeholder="默认:用户+手机尾号"
|
||||
value={receiverName}
|
||||
maxLength={32}
|
||||
onChange={(e) => setReceiverName(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="省市区" required>
|
||||
<ChinaRegionCascader value={regionCodes} onChange={setRegionCodes} />
|
||||
</Form.Item>
|
||||
<Form.Item label="详细地址" required>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="街道门牌等"
|
||||
value={addressDetail}
|
||||
maxLength={256}
|
||||
onChange={(e) => setAddressDetail(e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Checkbox checked={autoReceive} onChange={(e) => setAutoReceive(e.target.checked)}>
|
||||
同意自动收货(配送到址必选)
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div style={{ background: '#fafafa', borderRadius: 8, padding: 12 }}>
|
||||
<Typography.Text type="secondary">费用预览</Typography.Text>
|
||||
{previewLoading ? (
|
||||
<div>计算中…</div>
|
||||
) : preview ? (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%', marginTop: 8 }}>
|
||||
<div>履约:{deliveryLabel}</div>
|
||||
<div>商品金额:¥{fmtMoney(preview.productAmount)}</div>
|
||||
<div>实付:¥{fmtMoney(preview.payAmount)}</div>
|
||||
<div>好客权益:¥{fmtMoney(preview.benefitAmount)}</div>
|
||||
</Space>
|
||||
) : (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Typography.Text type="secondary">请完善商品与数量</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -51,6 +51,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
label: '门店',
|
||||
children: [
|
||||
{ key: '/stores', label: '门店列表' },
|
||||
{ key: '/store-ratings', label: '门店评价' },
|
||||
{ key: '/store-categories', label: '门店分类' },
|
||||
{ key: '/store-accounts', label: '门店账户' },
|
||||
{ key: '/store-media', label: '门店资源' },
|
||||
@@ -145,6 +146,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/knowledge-bases': 'knowledge_bases',
|
||||
'stores-group': 'stores',
|
||||
'/stores': 'stores',
|
||||
'/store-ratings': 'stores',
|
||||
'/store-categories': 'stores',
|
||||
'/store-accounts': 'stores',
|
||||
'/store-media': 'stores',
|
||||
@@ -155,6 +157,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/fulfillment-providers': 'partners',
|
||||
'finance-group': 'finance',
|
||||
'/finance/store-bills': 'finance',
|
||||
'/finance/store-withdrawals': 'finance',
|
||||
'/finance/partner-bills': 'finance',
|
||||
'/finance/winery-bills': 'finance',
|
||||
'/finance/logistics-bills': 'finance',
|
||||
@@ -204,6 +207,8 @@ function filterMenuItems(items: MenuProps['items'], permissionKeys: string[]): M
|
||||
.filter(Boolean) as MenuProps['items'];
|
||||
}
|
||||
|
||||
const IS_STAGING = import.meta.env.VITE_APP_ENV === 'staging';
|
||||
|
||||
export default function AdminLayout() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
@@ -239,16 +244,35 @@ export default function AdminLayout() {
|
||||
|
||||
return (
|
||||
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
|
||||
{IS_STAGING ? (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
zIndex: 1100,
|
||||
background: '#d48806',
|
||||
color: '#fff',
|
||||
textAlign: 'center',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
lineHeight: '28px',
|
||||
}}
|
||||
>
|
||||
测试环境 · staging · 数据与生产隔离 · Mock 开启
|
||||
</div>
|
||||
) : null}
|
||||
<Sider
|
||||
breakpoint="lg"
|
||||
collapsedWidth={64}
|
||||
theme="dark"
|
||||
width={220}
|
||||
style={{ height: '100vh', overflow: 'hidden' }}
|
||||
style={{ height: '100vh', overflow: 'hidden', marginTop: IS_STAGING ? 28 : 0 }}
|
||||
>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: IS_STAGING ? 'calc(100vh - 28px)' : '100vh' }}>
|
||||
<div style={{ flexShrink: 0, padding: '16px', color: '#fff', fontWeight: 600 }}>
|
||||
杜康 HQ
|
||||
杜康 HQ{IS_STAGING ? ' · 测试' : ''}
|
||||
</div>
|
||||
<div className="admin-sider-menu-scroll" style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
|
||||
<Menu
|
||||
@@ -264,7 +288,15 @@ export default function AdminLayout() {
|
||||
</div>
|
||||
</div>
|
||||
</Sider>
|
||||
<Layout style={{ height: '100vh', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
|
||||
<Layout
|
||||
style={{
|
||||
height: IS_STAGING ? 'calc(100vh - 28px)' : '100vh',
|
||||
marginTop: IS_STAGING ? 28 : 0,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Header
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
|
||||
@@ -85,9 +85,56 @@ export type DashboardStats = {
|
||||
pendingBills?: number;
|
||||
pendingPartnerDraftBills?: number;
|
||||
openTickets?: number;
|
||||
pendingStoreWithdrawals?: number;
|
||||
overdueStoreWithdrawals?: number;
|
||||
ordersByStatus: Array<{ status: string; count: number }>;
|
||||
};
|
||||
|
||||
export type DashboardAnalytics = {
|
||||
summary: {
|
||||
users: number;
|
||||
orders: number;
|
||||
payingUsers: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
byDate: Array<{
|
||||
date: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
byCity: Array<{
|
||||
cityId: string;
|
||||
cityName: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
byPromo: Array<{
|
||||
promoCodeId: string | null;
|
||||
code: string;
|
||||
name: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
}>;
|
||||
byPartner: Array<{
|
||||
partnerAccountId: string;
|
||||
companyName: string;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
export type SystemVersion = {
|
||||
id: string;
|
||||
gitTag: string | null;
|
||||
@@ -148,6 +195,10 @@ export type AdminOrderRow = {
|
||||
fulfillmentWarehouse?: { id: string; name: string } | null;
|
||||
fulfillmentHold?: boolean;
|
||||
fulfillmentHoldReason?: string | null;
|
||||
orderType?: string;
|
||||
isProxyOrder?: boolean;
|
||||
proxyPartnerName?: string | null;
|
||||
proxyPartnerPhone?: string | null;
|
||||
user?: { id: string; userNo: string; phone: string | null; nickname: string | null };
|
||||
delivery?: {
|
||||
provider: string;
|
||||
|
||||
@@ -19,6 +19,17 @@ export const ORDER_STATUS_LABELS: Record<string, string> = {
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
/** 订单状态流转操作人(common_event.param3) */
|
||||
export const ORDER_STATUS_OPERATOR_LABELS: Record<string, string> = {
|
||||
USER: '用户',
|
||||
USER_ON_SITE: '用户·现场取货',
|
||||
USER_WECHAT_CONFIRM: '用户·微信确认收货',
|
||||
WECHAT_TRADE_MANAGE: '微信结算同步',
|
||||
MOCK: 'Mock',
|
||||
MOCK_PAY: 'Mock 支付',
|
||||
SYSTEM: '系统',
|
||||
};
|
||||
|
||||
/** 订单状态 Tag 颜色(Ant Design preset) */
|
||||
export const ORDER_STATUS_COLORS: Record<string, string> = {
|
||||
PENDING_PAY: 'red',
|
||||
|
||||
@@ -27,6 +27,8 @@ export type StoreCreateForm = {
|
||||
bankAccountNo: string;
|
||||
bankBranch: string;
|
||||
settlementRate?: number;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
};
|
||||
|
||||
const PHONE_RE = /^1\d{10}$/;
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Button, Card, Col, Descriptions, Modal, Row, Space, Statistic, Table, Typography, message,
|
||||
Button, Card, Col, DatePicker, Descriptions, Form, Modal, Row, Select, Space, Statistic, Table, Typography, message,
|
||||
} from 'antd';
|
||||
import { CloudUploadOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import {
|
||||
request,
|
||||
type DashboardAnalytics,
|
||||
type DashboardStats,
|
||||
type DeployTriggerResult,
|
||||
type HqProfile,
|
||||
type Paginated,
|
||||
type SystemVersion,
|
||||
} from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
@@ -31,6 +36,26 @@ const DEPLOYED_BY_LABELS: Record<string, string> = {
|
||||
admin: 'Admin 发布',
|
||||
};
|
||||
|
||||
type CityOption = { id: string; name: string; code: string };
|
||||
type PromoOption = { id: string; code: string; name: string };
|
||||
|
||||
type AnalyticsFilters = {
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
};
|
||||
|
||||
function buildAnalyticsQs(f: AnalyticsFilters) {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('dateFrom', f.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('dateTo', f.range[1].format('YYYY-MM-DD'));
|
||||
if (f.cityId) qs.set('cityId', f.cityId);
|
||||
if (f.promoCodeId) qs.set('promoCodeId', f.promoCodeId);
|
||||
if (f.partnerAccountId) qs.set('partnerAccountId', f.partnerAccountId);
|
||||
return qs.toString();
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||
const [version, setVersion] = useState<SystemVersion | null>(null);
|
||||
@@ -40,6 +65,21 @@ export default function DashboardPage() {
|
||||
const [deploying, setDeploying] = useState(false);
|
||||
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
||||
|
||||
const [filterForm] = Form.useForm<{
|
||||
range: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}>();
|
||||
const [filters, setFilters] = useState<AnalyticsFilters>({
|
||||
range: [dayjs().subtract(29, 'day'), dayjs()],
|
||||
});
|
||||
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
|
||||
const [analyticsLoading, setAnalyticsLoading] = useState(true);
|
||||
const [cities, setCities] = useState<CityOption[]>([]);
|
||||
const [promos, setPromos] = useState<PromoOption[]>([]);
|
||||
const [partners, setPartners] = useState<Array<{ id: string; companyName?: string | null; name: string }>>([]);
|
||||
|
||||
const loadVersion = useCallback(() => {
|
||||
setVersionLoading(true);
|
||||
return request<SystemVersion | null>('/admin/dashboard/version')
|
||||
@@ -48,6 +88,17 @@ export default function DashboardPage() {
|
||||
.finally(() => setVersionLoading(false));
|
||||
}, []);
|
||||
|
||||
const loadAnalytics = useCallback((f: AnalyticsFilters) => {
|
||||
setAnalyticsLoading(true);
|
||||
return request<DashboardAnalytics>(`/admin/dashboard/analytics?${buildAnalyticsQs(f)}`)
|
||||
.then(setAnalytics)
|
||||
.catch((e) => {
|
||||
message.error(e instanceof Error ? e.message : '加载统计失败');
|
||||
setAnalytics(null);
|
||||
})
|
||||
.finally(() => setAnalyticsLoading(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
request<DashboardStats>('/admin/dashboard/stats')
|
||||
.then(setStats)
|
||||
@@ -64,8 +115,64 @@ export default function DashboardPage() {
|
||||
.catch(() => {
|
||||
setVersionLoading(false);
|
||||
});
|
||||
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setCities(res.items ?? []))
|
||||
.catch(() => setCities([]));
|
||||
void request<Paginated<PromoOption>>(`/admin/promo-codes?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setPromos(res.items ?? []))
|
||||
.catch(() => setPromos([]));
|
||||
void request<Paginated<{ id: string; companyName?: string | null; name: string }>>(
|
||||
`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`,
|
||||
)
|
||||
.then((res) => setPartners(res.items ?? []))
|
||||
.catch(() => setPartners([]));
|
||||
}, [loadVersion]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadAnalytics(filters);
|
||||
}, [filters, loadAnalytics]);
|
||||
|
||||
function applyFilters(values: {
|
||||
range?: [Dayjs, Dayjs];
|
||||
cityId?: string;
|
||||
promoCodeId?: string;
|
||||
partnerAccountId?: string;
|
||||
}) {
|
||||
const next: AnalyticsFilters = {
|
||||
range: values.range ?? filters.range,
|
||||
cityId: values.cityId || undefined,
|
||||
promoCodeId: values.promoCodeId || undefined,
|
||||
partnerAccountId: values.partnerAccountId || undefined,
|
||||
};
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setCityFilter(cityId: string) {
|
||||
const next = { ...filters, cityId: cityId === filters.cityId ? undefined : cityId };
|
||||
filterForm.setFieldsValue({ cityId: next.cityId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setPromoFilter(promoCodeId: string) {
|
||||
const key = promoCodeId === 'null' || promoCodeId === '' ? 'none' : promoCodeId;
|
||||
const next = {
|
||||
...filters,
|
||||
promoCodeId: key === filters.promoCodeId ? undefined : key,
|
||||
};
|
||||
filterForm.setFieldsValue({ promoCodeId: next.promoCodeId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function setPartnerFilter(partnerAccountId: string) {
|
||||
const next = {
|
||||
...filters,
|
||||
partnerAccountId:
|
||||
partnerAccountId === filters.partnerAccountId ? undefined : partnerAccountId,
|
||||
};
|
||||
filterForm.setFieldsValue({ partnerAccountId: next.partnerAccountId });
|
||||
setFilters(next);
|
||||
}
|
||||
|
||||
function handleDeploy() {
|
||||
Modal.confirm({
|
||||
title: '确认发布更新?',
|
||||
@@ -89,6 +196,176 @@ export default function DashboardPage() {
|
||||
|
||||
const shortSha = version?.commitId ? version.commitId.slice(0, 7) : '—';
|
||||
|
||||
const ordersDrillQs = useMemo(() => {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('createdFrom', filters.range[0].format('YYYY-MM-DD'));
|
||||
qs.set('createdTo', filters.range[1].format('YYYY-MM-DD'));
|
||||
if (filters.cityId && filters.cityId !== 'none') qs.set('cityId', filters.cityId);
|
||||
return qs.toString();
|
||||
}, [filters]);
|
||||
|
||||
const byDateOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byDate ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增用户', '订单数'] },
|
||||
grid: { left: 40, right: 20, top: 40, bottom: 40 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '新增用户', type: 'line', smooth: true, data: rows.map((r) => r.users) },
|
||||
{ name: '订单数', type: 'line', smooth: true, data: rows.map((r) => r.orders) },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const byPromoOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPromo ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['用户', '订单'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 64 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.name || r.code),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '用户', type: 'bar', data: rows.map((r) => r.users), barMaxWidth: 36 },
|
||||
{ name: '订单', type: 'bar', data: rows.map((r) => r.orders), barMaxWidth: 36 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByDateOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byDate ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['新增合伙人', '新签门店', '核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 48, bottom: 40 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.date.slice(5)),
|
||||
axisLabel: { rotate: rows.length > 14 ? 45 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '数量', minInterval: 1 },
|
||||
{ type: 'value', name: '金额', minInterval: 1 },
|
||||
],
|
||||
series: [
|
||||
{ name: '新增合伙人', type: 'line', smooth: true, data: rows.map((r) => r.partners) },
|
||||
{ name: '新签门店', type: 'line', smooth: true, data: rows.map((r) => r.stores) },
|
||||
{ name: '核销笔数', type: 'line', smooth: true, data: rows.map((r) => r.redeems) },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['合伙人', '门店', '核销笔数'] },
|
||||
grid: { left: 48, right: 20, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: { type: 'value', minInterval: 1 },
|
||||
series: [
|
||||
{ name: '合伙人', type: 'bar', data: rows.map((r) => r.partners), barMaxWidth: 28 },
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const opsByPartnerOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byPartner ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['门店', '核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 64 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.companyName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 3 ? 30 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '数量', minInterval: 1 },
|
||||
{ type: 'value', name: '金额' },
|
||||
],
|
||||
series: [
|
||||
{ name: '门店', type: 'bar', data: rows.map((r) => r.stores), barMaxWidth: 28 },
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 28 },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
const redeemByCityOption = useMemo<EChartsOption>(() => {
|
||||
const rows = analytics?.byCity ?? [];
|
||||
return {
|
||||
tooltip: { trigger: 'axis' },
|
||||
legend: { data: ['核销笔数', '核销金额'] },
|
||||
grid: { left: 48, right: 48, top: 40, bottom: 48 },
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: rows.map((r) => r.cityName),
|
||||
axisLabel: { interval: 0, rotate: rows.length > 4 ? 30 : 0 },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '笔数', minInterval: 1 },
|
||||
{ type: 'value', name: '金额' },
|
||||
],
|
||||
series: [
|
||||
{ name: '核销笔数', type: 'bar', data: rows.map((r) => r.redeems), barMaxWidth: 36 },
|
||||
{
|
||||
name: '核销金额',
|
||||
type: 'line',
|
||||
yAxisIndex: 1,
|
||||
data: rows.map((r) => r.redeemAmount),
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [analytics]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4}>数据概览</Typography.Title>
|
||||
@@ -176,6 +453,237 @@ export default function DashboardPage() {
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
title="数据统计筛选"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
size="small"
|
||||
onClick={() => void loadAnalytics(filters)}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Form
|
||||
form={filterForm}
|
||||
layout="inline"
|
||||
initialValues={{ range: filters.range }}
|
||||
onFinish={applyFilters}
|
||||
>
|
||||
<Form.Item name="range" label="日期" rules={[{ required: true, message: '请选择日期' }]}>
|
||||
<DatePicker.RangePicker allowClear={false} />
|
||||
</Form.Item>
|
||||
<Form.Item name="cityId" label="城市">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部开城"
|
||||
style={{ width: 160 }}
|
||||
options={[
|
||||
{ value: 'none', label: '未选城' },
|
||||
...cities.map((c) => ({ value: c.id, label: c.name })),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="promoCodeId" label="推广码">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部来源"
|
||||
style={{ width: 200 }}
|
||||
options={[
|
||||
{ value: 'none', label: '自然量 / 无推广码' },
|
||||
...promos.map((p) => ({ value: p.id, label: `${p.name}(${p.code})` })),
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="partnerAccountId" label="合伙人">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部合伙人"
|
||||
style={{ width: 200 }}
|
||||
options={partners.map((p) => ({
|
||||
value: p.id,
|
||||
label: p.companyName || p.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">查询</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="用户 / 订单统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to={`/orders?${ordersDrillQs}`}>查看订单</Link>
|
||||
<Link to="/users">查看用户</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间新增用户" value={analytics?.summary.users ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间订单数" value={analytics?.summary.orders ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Statistic title="区间付费用户" value={analytics?.summary.payingUsers ?? 0} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24}>
|
||||
<Card type="inner" title="按日趋势" loading={analyticsLoading} size="small">
|
||||
<ReactECharts option={byDateOption} style={{ height: 320 }} notMerge />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={byCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按推广码(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={byPromoOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byPromo ?? []).find(
|
||||
(r) => (r.name || r.code) === params.name,
|
||||
);
|
||||
if (row) setPromoFilter(row.promoCodeId ?? 'none');
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="合伙人 / 门店 / 核销统计"
|
||||
style={{ marginBottom: 24 }}
|
||||
extra={
|
||||
<Space>
|
||||
<Link to="/city-partners">查看合伙人</Link>
|
||||
<Link to="/stores">查看门店</Link>
|
||||
<Link to="/redeem-records">查看核销</Link>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新增合伙人" value={analytics?.summary.partners ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间新签门店" value={analytics?.summary.stores ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销笔数" value={analytics?.summary.redeems ?? 0} />
|
||||
</Col>
|
||||
<Col xs={24} sm={6}>
|
||||
<Statistic title="区间核销金额" value={analytics?.summary.redeemAmount ?? 0} precision={2} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24}>
|
||||
<Card type="inner" title="按日趋势(合伙人 / 门店 / 核销)" loading={analyticsLoading} size="small">
|
||||
<ReactECharts option={opsByDateOption} style={{ height: 320 }} notMerge />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市(点击柱联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={opsByCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按城市核销金额"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={redeemByCityOption}
|
||||
style={{ height: 300 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byCity ?? []).find((r) => r.cityName === params.name);
|
||||
if (row) setCityFilter(row.cityId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24}>
|
||||
<Card
|
||||
type="inner"
|
||||
title="按合伙人(门店 / 核销,点击联动筛选)"
|
||||
loading={analyticsLoading}
|
||||
size="small"
|
||||
>
|
||||
<ReactECharts
|
||||
option={opsByPartnerOption}
|
||||
style={{ height: 320 }}
|
||||
notMerge
|
||||
onEvents={{
|
||||
click: (params: { name?: string }) => {
|
||||
const row = (analytics?.byPartner ?? []).find(
|
||||
(r) => r.companyName === params.name,
|
||||
);
|
||||
if (row) setPartnerFilter(row.partnerAccountId);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card
|
||||
@@ -209,6 +717,26 @@ export default function DashboardPage() {
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card
|
||||
loading={loading}
|
||||
title="待审门店提现"
|
||||
extra={<Link to="/finance/store-bills?kind=WITHDRAW">去处理</Link>}
|
||||
>
|
||||
<Statistic
|
||||
value={stats?.pendingStoreWithdrawals ?? 0}
|
||||
suffix="笔"
|
||||
valueStyle={{
|
||||
color: (stats?.overdueStoreWithdrawals ?? 0) > 0 ? '#cf1322' : (stats?.pendingStoreWithdrawals ?? 0) > 0 ? '#fa8c16' : undefined,
|
||||
}}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{(stats?.overdueStoreWithdrawals ?? 0) > 0
|
||||
? `超时未审 ${stats?.overdueStoreWithdrawals} 笔(FIN-003)`
|
||||
: '工作日 T+0 审完'}
|
||||
</Typography.Text>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={8}>
|
||||
<Card loading={loading} title="待处理工单">
|
||||
<Statistic value={stats?.openTickets ?? 0} suffix="个" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
@@ -24,9 +25,11 @@ import {
|
||||
DELIVERY_PROVIDER_LABELS,
|
||||
ORDER_STATUS_COLORS,
|
||||
ORDER_STATUS_LABELS,
|
||||
ORDER_STATUS_OPERATOR_LABELS,
|
||||
fmtTime,
|
||||
} from '../lib/constants';
|
||||
import { FULFILLMENT_HOLD_REASON_LABELS } from '@dukang/shared-types';
|
||||
import ProxyOrderModal from '../components/ProxyOrderModal';
|
||||
|
||||
type ShipDefaults = {
|
||||
provider: string;
|
||||
@@ -102,7 +105,13 @@ type OrderDetail = AdminOrderRow & {
|
||||
listUnitPrice?: number;
|
||||
items?: AdminOrderItem[];
|
||||
payment?: Record<string, unknown> | null;
|
||||
statusLogs?: Array<{ fromStatus: string | null; toStatus: string; createdAt: string }>;
|
||||
statusLogs?: Array<{
|
||||
fromStatus: string | null;
|
||||
toStatus: string;
|
||||
operator?: string | null;
|
||||
remark?: string | null;
|
||||
createdAt: string;
|
||||
}>;
|
||||
benefitCoupons?: Array<Record<string, unknown>>;
|
||||
redeemSummary?: OrderRedeemSummary | null;
|
||||
redeemRecords?: OrderRedeemRecord[];
|
||||
@@ -167,6 +176,7 @@ export default function OrdersPage() {
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
|
||||
const [batchDeleteOpen, setBatchDeleteOpen] = useState(false);
|
||||
const [batchDeleting, setBatchDeleting] = useState(false);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [shipDefaults, setShipDefaults] = useState<ShipDefaults | null>(null);
|
||||
const [shipping, setShipping] = useState(false);
|
||||
const [logisticsShipping, setLogisticsShipping] = useState(false);
|
||||
@@ -175,7 +185,9 @@ export default function OrdersPage() {
|
||||
const [shipTarget, setShipTarget] = useState<OrderDetail | null>(null);
|
||||
const [shipMode, setShipMode] = useState<ShipMode>('EXPRESS');
|
||||
const [warehouses, setWarehouses] = useState<WarehouseOption[]>([]);
|
||||
const [proxyOpen, setProxyOpen] = useState(false);
|
||||
const canDeleteOrders = (profile?.permissionKeys ?? []).includes('orders_delete');
|
||||
const canProxyOrder = (profile?.permissionKeys ?? []).includes('orders');
|
||||
|
||||
const selectedOrders = useMemo(
|
||||
() => (data?.items ?? []).filter((row) => selectedRowKeys.includes(row.id)),
|
||||
@@ -207,6 +219,7 @@ export default function OrdersPage() {
|
||||
const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
|
||||
if (values.orderNo) qs.set('orderNo', values.orderNo);
|
||||
if (values.status) qs.set('status', values.status);
|
||||
if (values.orderType) qs.set('orderType', values.orderType);
|
||||
if (values.cityId) qs.set('cityId', values.cityId);
|
||||
if (values.receiverPhone) qs.set('receiverPhone', values.receiverPhone);
|
||||
if (values.fulfillmentHold) qs.set('fulfillmentHold', 'true');
|
||||
@@ -379,6 +392,43 @@ export default function OrdersPage() {
|
||||
}
|
||||
}
|
||||
|
||||
function askDeleteOrder(id: string, orderNo?: string) {
|
||||
Modal.confirm({
|
||||
title: '确认删除订单?',
|
||||
content: (
|
||||
<div>
|
||||
<p>将永久删除订单{orderNo ? ` ${orderNo}` : ''} 及其配送、权益券、核销、发票等关联数据。</p>
|
||||
<p style={{ color: 'var(--ant-color-error)', marginBottom: 0 }}>此操作不可恢复,请确认不是真实线上订单。</p>
|
||||
</div>
|
||||
),
|
||||
okText: '确认删除',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
onOk: () => deleteOrder(id),
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteOrder(id: string) {
|
||||
setDeletingId(id);
|
||||
try {
|
||||
const res = await request<{ deleted: number; message: string }>(`/admin/orders/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
message.success(res.message || '订单已删除');
|
||||
if (detail?.id === id) {
|
||||
setDrawerOpen(false);
|
||||
setDetail(null);
|
||||
}
|
||||
setSelectedRowKeys((prev) => prev.filter((k) => k !== id));
|
||||
void load();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '删除失败');
|
||||
throw e;
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<AdminOrderRow> = [
|
||||
{ title: '订单号', dataIndex: 'orderNo', width: 180 },
|
||||
{
|
||||
@@ -408,6 +458,11 @@ export default function OrdersPage() {
|
||||
<Space size={4} wrap>
|
||||
<Tag color={ORDER_STATUS_COLORS[s] || 'default'}>{ORDER_STATUS_LABELS[s] || s}</Tag>
|
||||
{row.fulfillmentHold ? <Tag color="orange">大单待确认</Tag> : null}
|
||||
{row.orderType === 'PROXY' || row.isProxyOrder ? (
|
||||
<Tag color="purple" title={row.proxyPartnerName || undefined}>
|
||||
代下单
|
||||
</Tag>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -415,7 +470,8 @@ export default function OrdersPage() {
|
||||
title: '配送',
|
||||
dataIndex: 'deliveryType',
|
||||
width: 90,
|
||||
render: (v) => (v === 'LOCAL' ? '同城' : '跨城'),
|
||||
render: (v) =>
|
||||
v === 'ON_SITE_PICKUP' ? '现场提货' : v === 'LOCAL' ? '同城' : '跨城',
|
||||
},
|
||||
{ title: '实付', dataIndex: 'payAmount', width: 90, render: (v) => `¥${v}` },
|
||||
{ title: '收货人', dataIndex: 'receiverName', width: 90 },
|
||||
@@ -439,7 +495,7 @@ export default function OrdersPage() {
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 140,
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space size={0}>
|
||||
@@ -451,6 +507,17 @@ export default function OrdersPage() {
|
||||
配送
|
||||
</Button>
|
||||
)}
|
||||
{canDeleteOrders && (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
danger
|
||||
loading={deletingId === row.id}
|
||||
onClick={() => askDeleteOrder(row.id, row.orderNo)}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -460,6 +527,12 @@ export default function OrdersPage() {
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>订单监控</Typography.Title>
|
||||
<Space>
|
||||
{canProxyOrder ? (
|
||||
<Button type="primary" onClick={() => setProxyOpen(true)}>
|
||||
代下单
|
||||
</Button>
|
||||
) : null}
|
||||
{canDeleteOrders ? (
|
||||
<Button
|
||||
danger
|
||||
@@ -470,6 +543,22 @@ export default function OrdersPage() {
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{!canDeleteOrders && profile ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="当前账号无「删除订单」权限"
|
||||
description={
|
||||
<span>
|
||||
非超管账号需在 <Link to="/hq-permissions">权限分配</Link> 中勾选危险操作「删除订单」。
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={() => { setPage(1); void load(); }}>
|
||||
<Form.Item name="orderNo" label="订单号">
|
||||
<Input placeholder="DK..." allowClear />
|
||||
@@ -477,6 +566,17 @@ export default function OrdersPage() {
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select allowClear style={{ width: 120 }} options={Object.entries(ORDER_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="orderType" label="类型">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
placeholder="全部"
|
||||
options={[
|
||||
{ value: 'NORMAL', label: '普通订单' },
|
||||
{ value: 'PROXY', label: '代下单' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="cityId" label="城市">
|
||||
<Select
|
||||
allowClear
|
||||
@@ -540,6 +640,15 @@ export default function OrdersPage() {
|
||||
配送发货
|
||||
</Button>
|
||||
)}
|
||||
{canDeleteOrders && (
|
||||
<Button
|
||||
danger
|
||||
loading={deletingId === detail.id}
|
||||
onClick={() => askDeleteOrder(detail.id, detail.orderNo)}
|
||||
>
|
||||
删除订单
|
||||
</Button>
|
||||
)}
|
||||
<Typography.Text type="secondary">调试改状态</Typography.Text>
|
||||
<Select
|
||||
value={detail.status}
|
||||
@@ -581,8 +690,16 @@ export default function OrdersPage() {
|
||||
'大单待确认'}
|
||||
</Tag>
|
||||
) : null}
|
||||
{detail.orderType === 'PROXY' || detail.isProxyOrder ? (
|
||||
<Tag color="purple">代下单</Tag>
|
||||
) : null}
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
{detail.orderType === 'PROXY' || detail.isProxyOrder || detail.proxyPartnerName ? (
|
||||
<Descriptions.Item label="代下单人">
|
||||
{[detail.proxyPartnerName, detail.proxyPartnerPhone].filter(Boolean).join(' / ') || '—'}
|
||||
</Descriptions.Item>
|
||||
) : null}
|
||||
<Descriptions.Item label="用户">{detail.user?.userNo} / {detail.user?.nickname}</Descriptions.Item>
|
||||
<Descriptions.Item label="商品额">¥{detail.productAmount}</Descriptions.Item>
|
||||
<Descriptions.Item label="实付">¥{detail.payAmount}</Descriptions.Item>
|
||||
@@ -765,13 +882,40 @@ export default function OrdersPage() {
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>状态流转</Typography.Title>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey="createdAt"
|
||||
rowKey={(_, i) => String(i)}
|
||||
pagination={false}
|
||||
dataSource={detail.statusLogs}
|
||||
columns={[
|
||||
{ title: '从', dataIndex: 'fromStatus', render: (v) => v || '—' },
|
||||
{ title: '到', dataIndex: 'toStatus', render: (v) => ORDER_STATUS_LABELS[v] || v },
|
||||
{ title: '时间', dataIndex: 'createdAt', render: (v) => new Date(v).toLocaleString('zh-CN') },
|
||||
{
|
||||
title: '从',
|
||||
dataIndex: 'fromStatus',
|
||||
width: 100,
|
||||
render: (v) => (v ? ORDER_STATUS_LABELS[v] || v : '—'),
|
||||
},
|
||||
{
|
||||
title: '到',
|
||||
dataIndex: 'toStatus',
|
||||
width: 100,
|
||||
render: (v) => ORDER_STATUS_LABELS[v] || v,
|
||||
},
|
||||
{
|
||||
title: '操作人',
|
||||
dataIndex: 'operator',
|
||||
width: 120,
|
||||
render: (v) => ORDER_STATUS_OPERATOR_LABELS[v] || v || '—',
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
ellipsis: true,
|
||||
render: (v) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'createdAt',
|
||||
width: 170,
|
||||
render: (v) => new Date(v).toLocaleString('zh-CN'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
@@ -1078,6 +1222,16 @@ export default function OrdersPage() {
|
||||
]}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
<ProxyOrderModal
|
||||
open={proxyOpen}
|
||||
onClose={() => setProxyOpen(false)}
|
||||
onSuccess={(order) => {
|
||||
setProxyOpen(false);
|
||||
void load();
|
||||
void openDetail(order.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Button, Descriptions, Divider, Drawer, Form, Input, InputNumber, Modal, Popconfirm, Select, Space,
|
||||
Switch, Table, Tabs, Tag, Typography, message,
|
||||
@@ -32,6 +32,10 @@ type Row = {
|
||||
status: string;
|
||||
sortOrder: number;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
mainImageUrl?: string | null;
|
||||
carouselUrls?: string[];
|
||||
detailImageUrls?: string[];
|
||||
@@ -51,6 +55,10 @@ type ProductFormValues = {
|
||||
status?: string;
|
||||
sortOrder?: number;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
coverUrl?: string;
|
||||
carouselUrls?: string[];
|
||||
detailImageUrls?: string[];
|
||||
@@ -59,13 +67,26 @@ type ProductFormValues = {
|
||||
features?: Array<{ icon?: string; title?: string; desc?: string }>;
|
||||
};
|
||||
|
||||
type UserPickRow = {
|
||||
id: string;
|
||||
phone?: string | null;
|
||||
nickname?: string | null;
|
||||
userNo?: string;
|
||||
};
|
||||
|
||||
function mapDetailToForm(d: Record<string, unknown>) {
|
||||
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
||||
const row = d as Row;
|
||||
return {
|
||||
...d,
|
||||
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
||||
carouselUrls: ((d as Row).carouselUrls?.length ? (d as Row).carouselUrls : ['']) as string[],
|
||||
detailImageUrls: ((d as Row).detailImageUrls?.length ? (d as Row).detailImageUrls : ['']) as string[],
|
||||
carouselUrls: (row.carouselUrls?.length ? row.carouselUrls : ['']) as string[],
|
||||
detailImageUrls: (row.detailImageUrls?.length ? row.detailImageUrls : ['']) as string[],
|
||||
allowOnlinePurchase: row.allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery: row.allowOnlinePurchase === false ? false : row.allowCrossCityDelivery !== false,
|
||||
allowOnSitePickup: !!row.allowOnSitePickup,
|
||||
visibilityWhitelistEnabled: !!row.visibilityWhitelistEnabled,
|
||||
visibilityPhones: (row.visibilityPhones ?? []) as string[],
|
||||
storyTitle: detail.storyTitle ?? '',
|
||||
storyText: detail.storyText ?? '',
|
||||
features: detail.features?.length
|
||||
@@ -91,8 +112,11 @@ function buildProductPayload(v: ProductFormValues) {
|
||||
features: features.length ? features : undefined,
|
||||
};
|
||||
|
||||
const visibilityPhones = (v.visibilityPhones ?? [])
|
||||
.map((p) => String(p || '').replace(/\D/g, '').trim())
|
||||
.filter(Boolean);
|
||||
|
||||
return {
|
||||
skuCode: v.skuCode,
|
||||
barcode69: v.barcode69,
|
||||
name: v.name,
|
||||
subtitle: v.subtitle,
|
||||
@@ -103,6 +127,11 @@ function buildProductPayload(v: ProductFormValues) {
|
||||
status: v.status,
|
||||
sortOrder: v.sortOrder,
|
||||
allowOnSitePickup: !!v.allowOnSitePickup,
|
||||
allowOnlinePurchase: v.allowOnlinePurchase !== false,
|
||||
allowCrossCityDelivery:
|
||||
v.allowOnlinePurchase === false ? false : v.allowCrossCityDelivery !== false,
|
||||
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||
visibilityPhones,
|
||||
coverUrl: v.coverUrl,
|
||||
carouselUrls,
|
||||
detailImageUrls,
|
||||
@@ -183,13 +212,94 @@ function ProductDetailFields({ form, aromaType }: { form: FormInstance; aromaTyp
|
||||
);
|
||||
}
|
||||
|
||||
function BaseInfoFields({ mode }: { mode: 'create' | 'edit' }) {
|
||||
function VisibilityWhitelistFields({ 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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormInstance }) {
|
||||
return (
|
||||
<>
|
||||
{mode === 'create' && (
|
||||
<>
|
||||
<Form.Item name="skuCode" label="SKU" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
<Form.Item label="SKU">
|
||||
<Input disabled placeholder="保存后自动生成" />
|
||||
</Form.Item>
|
||||
<Form.Item name="barcode69" label="69码" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
@@ -220,9 +330,40 @@ function BaseInfoFields({ mode }: { mode: 'create' | 'edit' }) {
|
||||
<Form.Item name="sortOrder" label="排序">
|
||||
<InputNumber min={0} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="allowOnlinePurchase"
|
||||
label="允许线上购买"
|
||||
valuePropName="checked"
|
||||
extra="配送到址(同城)"
|
||||
>
|
||||
<Switch
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
onChange={(checked) => {
|
||||
if (!checked) form.setFieldsValue({ allowCrossCityDelivery: false });
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item noStyle shouldUpdate={(prev, cur) => prev.allowOnlinePurchase !== cur.allowOnlinePurchase}>
|
||||
{() => (
|
||||
<Form.Item
|
||||
name="allowCrossCityDelivery"
|
||||
label="允许跨城配送"
|
||||
valuePropName="checked"
|
||||
extra="须先开启线上购买"
|
||||
>
|
||||
<Switch
|
||||
checkedChildren="开"
|
||||
unCheckedChildren="关"
|
||||
disabled={!form.getFieldValue('allowOnlinePurchase')}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
</Form.Item>
|
||||
<Form.Item name="allowOnSitePickup" label="允许现场取货" valuePropName="checked">
|
||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||
</Form.Item>
|
||||
<VisibilityWhitelistFields form={form} />
|
||||
<Form.Item name="coverUrl" label="封面">
|
||||
<OssUpload bizType="COVER" mediaType="IMAGE" />
|
||||
</Form.Item>
|
||||
@@ -264,7 +405,7 @@ export default function ProductsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
const columns: ColumnsType<Row> = useMemo(() => [
|
||||
{ title: 'SKU', dataIndex: 'skuCode', width: 90 },
|
||||
{ title: '商品名', dataIndex: 'name', width: 180, ellipsis: true },
|
||||
{ title: '香型', dataIndex: 'aromaType', width: 80, render: (v) => AROMA_TYPE_LABELS[v] || v },
|
||||
@@ -275,10 +416,26 @@ export default function ProductsPage() {
|
||||
<Tag color={s === 'ON_SALE' ? 'green' : undefined}>{PRODUCT_STATUS_LABELS[s] || s}</Tag>
|
||||
) },
|
||||
{
|
||||
title: '现场取货',
|
||||
dataIndex: 'allowOnSitePickup',
|
||||
title: '白名单',
|
||||
dataIndex: 'visibilityWhitelistEnabled',
|
||||
width: 90,
|
||||
render: (v: boolean) => (v ? <Tag color="green">允许</Tag> : <Tag>否</Tag>),
|
||||
render: (v: boolean, row) =>
|
||||
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||
},
|
||||
{
|
||||
title: '履约',
|
||||
key: 'fulfillment',
|
||||
width: 160,
|
||||
render: (_, row) => (
|
||||
<Space size={[0, 4]} wrap>
|
||||
{row.allowOnlinePurchase !== false ? <Tag color="blue">线上</Tag> : null}
|
||||
{row.allowOnlinePurchase !== false && row.allowCrossCityDelivery !== false ? (
|
||||
<Tag color="cyan">跨城</Tag>
|
||||
) : null}
|
||||
{row.allowOnSitePickup ? <Tag color="green">现场</Tag> : null}
|
||||
{row.allowOnlinePurchase === false && !row.allowOnSitePickup ? <Tag>无</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: '排序', dataIndex: 'sortOrder', width: 60 },
|
||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
@@ -305,7 +462,7 @@ export default function ProductsPage() {
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
], [detail, editForm]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -323,12 +480,16 @@ export default function ProductsPage() {
|
||||
</Form.Item>
|
||||
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
||||
</Form>
|
||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1140 }}
|
||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1320 }}
|
||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||
<Drawer title="编辑商品" width={720} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||
extra={detail && (
|
||||
<Button type="primary" onClick={async () => {
|
||||
const v = await editForm.validateFields();
|
||||
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||
return;
|
||||
}
|
||||
const payload = buildProductPayload(v);
|
||||
await request(`/admin/products/${detail.id}`, { method: 'PUT', body: JSON.stringify(payload) });
|
||||
message.success('已保存');
|
||||
@@ -345,7 +506,7 @@ export default function ProductsPage() {
|
||||
</Descriptions>
|
||||
<Form form={editForm} layout="vertical">
|
||||
<Tabs items={[
|
||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="edit" /> },
|
||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="edit" form={editForm} /> },
|
||||
{
|
||||
key: 'detail',
|
||||
label: '详情页',
|
||||
@@ -363,6 +524,10 @@ export default function ProductsPage() {
|
||||
</Drawer>
|
||||
<Modal title="新建商品" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => {
|
||||
const v = await createForm.validateFields();
|
||||
if (!v.allowOnlinePurchase && !v.allowOnSitePickup) {
|
||||
message.error('请至少勾选「允许线上购买」或「允许现场取货」之一');
|
||||
return;
|
||||
}
|
||||
const payload = buildProductPayload(v);
|
||||
await request('/admin/products', { method: 'POST', body: JSON.stringify(payload) });
|
||||
message.success('已创建');
|
||||
@@ -371,12 +536,14 @@ export default function ProductsPage() {
|
||||
void reload();
|
||||
}} width={720}>
|
||||
<Form form={createForm} layout="vertical" initialValues={{
|
||||
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0, allowOnSitePickup: false,
|
||||
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0,
|
||||
allowOnlinePurchase: true, allowCrossCityDelivery: true, allowOnSitePickup: false,
|
||||
visibilityWhitelistEnabled: false, visibilityPhones: [],
|
||||
carouselUrls: [''], detailImageUrls: [''],
|
||||
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
||||
}}>
|
||||
<Tabs items={[
|
||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="create" /> },
|
||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="create" form={createForm} /> },
|
||||
{
|
||||
key: 'detail',
|
||||
label: '详情页',
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Descriptions, Drawer, Form, Input, Table, Typography } from 'antd';
|
||||
import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string; redeemNo: string; amount: number; settleAmount: number; createdAt: string;
|
||||
id: string;
|
||||
redeemNo: string;
|
||||
amount: number;
|
||||
settleAmount: number;
|
||||
channel?: RedeemChannel;
|
||||
createdAt: string;
|
||||
user?: { userNo: string; phone: string | null };
|
||||
store?: { name: string; cityName: string };
|
||||
coupon?: { couponNo: string };
|
||||
@@ -21,6 +27,7 @@ export default function RedeemRecordsPage() {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.channel) qs.set('channel', filters.channel);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
@@ -30,6 +37,19 @@ export default function RedeemRecordsPage() {
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||
{
|
||||
title: '方式',
|
||||
dataIndex: 'channel',
|
||||
width: 110,
|
||||
render: (v: RedeemChannel | undefined) => {
|
||||
const channel = v === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||
return (
|
||||
<Tag color={channel === 'PHONE' ? 'purple' : 'blue'}>
|
||||
{REDEEM_CHANNEL_LABELS[channel]}
|
||||
</Tag>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ title: '用户', dataIndex: ['user', 'userNo'], width: 110 },
|
||||
{ title: '门店', dataIndex: ['store', 'name'] },
|
||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||
@@ -37,12 +57,19 @@ export default function RedeemRecordsPage() {
|
||||
{ title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 },
|
||||
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
{
|
||||
title: '操作', width: 80,
|
||||
title: '操作',
|
||||
width: 80,
|
||||
render: (_, row) => (
|
||||
<Button type="link" size="small" onClick={async () => {
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={async () => {
|
||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
||||
setDrawerOpen(true);
|
||||
}}>详情</Button>
|
||||
}}
|
||||
>
|
||||
详情
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -50,16 +77,65 @@ export default function RedeemRecordsPage() {
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4}>核销记录</Typography.Title>
|
||||
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
|
||||
<Form.Item name="redeemNo" label="核销号"><Input allowClear /></Form.Item>
|
||||
<Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
onFinish={(v) => {
|
||||
setFilters(v);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="redeemNo" label="核销号">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店ID">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item name="channel" label="方式">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={[
|
||||
{ value: 'SCAN', label: '扫码核销' },
|
||||
{ value: 'PHONE', label: '手机号核销' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1000 }}
|
||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1100 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
|
||||
{detail && (
|
||||
<Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="方式">
|
||||
{
|
||||
REDEEM_CHANNEL_LABELS[
|
||||
(detail.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel
|
||||
]
|
||||
}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -6,6 +7,7 @@ import {
|
||||
Descriptions,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
@@ -17,44 +19,61 @@ import {
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import {
|
||||
STORE_SETTLEMENT_KIND_LABELS,
|
||||
STORE_SETTLEMENT_STATUS_LABELS,
|
||||
storeSettlementStatusLabel,
|
||||
type StoreSettlementKind,
|
||||
type StoreSettlementStatus,
|
||||
} from '@dukang/shared-types';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { downloadExcelCsv } from '../lib/exportExcel';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
kind: StoreSettlementKind;
|
||||
id: string;
|
||||
billNo: string;
|
||||
billDate: string;
|
||||
redeemCount: number;
|
||||
redeemAmount: number;
|
||||
settlementRate: number;
|
||||
payoutAmount: number;
|
||||
status: string;
|
||||
paidAt?: string | null;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string };
|
||||
amount: number;
|
||||
status: StoreSettlementStatus;
|
||||
date: string;
|
||||
overdue?: boolean;
|
||||
redeemCount?: number | null;
|
||||
redeemAmount?: number | null;
|
||||
settlementRate?: number | null;
|
||||
payoutCount?: number | null;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string | null };
|
||||
};
|
||||
|
||||
type StoreOption = { id: string; name: string; phone: string };
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
UNPAID: '未打款',
|
||||
PAID: '已打款',
|
||||
};
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
UNPAID: 'red',
|
||||
PAID: 'green',
|
||||
PENDING_REVIEW: 'orange',
|
||||
REJECTED: 'red',
|
||||
};
|
||||
|
||||
const KIND_COLORS: Record<StoreSettlementKind, string> = {
|
||||
T1_BILL: 'blue',
|
||||
WITHDRAW: 'purple',
|
||||
};
|
||||
|
||||
export default function StoreBillsPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : '';
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||
const [filters, setFilters] = useState<Record<string, string>>({
|
||||
kind: initialKind,
|
||||
status: initialKind === 'WITHDRAW' ? 'PENDING_REVIEW' : '',
|
||||
});
|
||||
const [stores, setStores] = useState<StoreOption[]>([]);
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||
'/admin/store-bills',
|
||||
'/admin/store-settlements',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.kind) qs.set('kind', filters.kind);
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
@@ -64,21 +83,38 @@ export default function StoreBillsPage() {
|
||||
[filters],
|
||||
);
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [detailKind, setDetailKind] = useState<StoreSettlementKind | null>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
const [overdueSummary, setOverdueSummary] = useState<{
|
||||
pendingCount: number;
|
||||
overdueCount: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
form.setFieldsValue({
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
});
|
||||
}, [filters.kind, filters.status, form]);
|
||||
|
||||
useEffect(() => {
|
||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setStores(res.items))
|
||||
.catch(() => {});
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
function confirmPay(ids: string[], amountHint?: number) {
|
||||
Modal.confirm({
|
||||
title: '确认打款?',
|
||||
content: `将确认 ${ids.length} 笔门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
||||
content: `将确认 ${ids.length} 笔 T+1 门店对账单${amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}。此操作不可撤销。`,
|
||||
okText: '确认打款',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
@@ -102,9 +138,75 @@ export default function StoreBillsPage() {
|
||||
});
|
||||
}
|
||||
|
||||
async function openDetail(id: string) {
|
||||
const d = await request<Record<string, unknown>>(`/admin/store-bills/${id}`);
|
||||
function approveWithdraw(id: string) {
|
||||
let paymentRef = '';
|
||||
Modal.confirm({
|
||||
title: '审核通过并标记已结算?',
|
||||
content: (
|
||||
<Input
|
||||
placeholder="打款凭证号(可选)"
|
||||
onChange={(e) => {
|
||||
paymentRef = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '通过并结算',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await request(`/admin/store-withdrawals/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
|
||||
});
|
||||
message.success('已通过并标记已结算');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function rejectWithdraw(id: string) {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '驳回提现申请?',
|
||||
content: (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
placeholder="请填写驳回理由"
|
||||
onChange={(e) => {
|
||||
reason = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '确认驳回',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) {
|
||||
message.error('请填写驳回理由');
|
||||
throw new Error('reason required');
|
||||
}
|
||||
await request(`/admin/store-withdrawals/${id}/reject`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: reason.trim() }),
|
||||
});
|
||||
message.success('已驳回');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function openDetail(row: Row) {
|
||||
const path =
|
||||
row.kind === 'WITHDRAW' ? `/admin/store-withdrawals/${row.id}` : `/admin/store-bills/${row.id}`;
|
||||
const d = await request<Record<string, unknown>>(path);
|
||||
setDetail(d);
|
||||
setDetailKind(row.kind);
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
|
||||
@@ -118,88 +220,134 @@ export default function StoreBillsPage() {
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
const result = await request<{ csv: string; count: number }>(`/admin/store-bills/export?${qs}`);
|
||||
downloadExcelCsv(result.csv, `门店对账单_${filters.dateFrom || 'all'}_${filters.dateTo || 'all'}.csv`);
|
||||
message.success(`已导出 ${result.count} 条`);
|
||||
message.success(`已导出 ${result.count} 条 T+1 账单`);
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const summary = data?.summary;
|
||||
const selectedRows = (data?.items ?? []).filter((r) => selectedKeys.includes(r.id));
|
||||
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.payoutAmount), 0);
|
||||
const selectedRows = (data?.items ?? []).filter(
|
||||
(r) =>
|
||||
selectedKeys.includes(`${r.kind}-${r.id}`) &&
|
||||
r.kind === 'T1_BILL' &&
|
||||
r.status === 'UNPAID',
|
||||
);
|
||||
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.amount), 0);
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '账单号', dataIndex: 'billNo', width: 170, ellipsis: true },
|
||||
{
|
||||
title: '账单日',
|
||||
dataIndex: 'billDate',
|
||||
width: 110,
|
||||
render: (v) => String(v || '').slice(0, 10),
|
||||
title: '类型',
|
||||
dataIndex: 'kind',
|
||||
width: 100,
|
||||
render: (k: StoreSettlementKind) => (
|
||||
<Tag color={KIND_COLORS[k]}>{STORE_SETTLEMENT_KIND_LABELS[k] ?? k}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '单号',
|
||||
dataIndex: 'billNo',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
render: (v, row) => (
|
||||
<Space>
|
||||
<span>{v}</span>
|
||||
{row.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '日期',
|
||||
dataIndex: 'date',
|
||||
width: 160,
|
||||
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
|
||||
},
|
||||
{ title: '门店', dataIndex: ['store', 'name'], width: 140, ellipsis: true },
|
||||
{ title: '登录手机', dataIndex: ['store', 'phone'], width: 120, render: (v) => v || '—' },
|
||||
{ title: '城市', dataIndex: ['store', 'cityName'], width: 90 },
|
||||
{ title: '核销笔数', dataIndex: 'redeemCount', width: 90 },
|
||||
{
|
||||
title: '核销金额',
|
||||
dataIndex: 'redeemAmount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '结算比例',
|
||||
dataIndex: 'settlementRate',
|
||||
width: 90,
|
||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
||||
title: '笔数',
|
||||
width: 80,
|
||||
render: (_, row) =>
|
||||
row.kind === 'T1_BILL' ? (row.redeemCount ?? '—') : (row.payoutCount ?? '—'),
|
||||
},
|
||||
{
|
||||
title: '应付金额',
|
||||
dataIndex: 'payoutAmount',
|
||||
dataIndex: 'amount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
||||
width: 100,
|
||||
render: (s: string, row) => (
|
||||
<Tag color={STATUS_COLORS[s] || 'default'}>{storeSettlementStatusLabel(row.kind, s)}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 160,
|
||||
width: 200,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space size={0}>
|
||||
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
||||
<Button type="link" size="small" onClick={() => void openDetail(row)}>
|
||||
明细
|
||||
</Button>
|
||||
{row.status === 'UNPAID' && (
|
||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.payoutAmount))}>
|
||||
{row.kind === 'T1_BILL' && row.status === 'UNPAID' && (
|
||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.amount))}>
|
||||
确认打款
|
||||
</Button>
|
||||
)}
|
||||
{row.kind === 'WITHDRAW' && row.status === 'PENDING_REVIEW' && (
|
||||
<>
|
||||
<Button type="link" size="small" onClick={() => approveWithdraw(row.id)}>
|
||||
通过
|
||||
</Button>
|
||||
<Button type="link" size="small" danger onClick={() => rejectWithdraw(row.id)}>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const withdrawDetailItems =
|
||||
(detail?.items as Array<Record<string, unknown>> | undefined) ?? [];
|
||||
const storeAccount = detail?.storeAccount as
|
||||
| {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
bankAccountName?: string;
|
||||
bankAccountNo?: string;
|
||||
bankBranch?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||
门店对账单
|
||||
门店账单
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
按核销日汇总(每日 8:00 自动出账);未打款红色、已打款绿色
|
||||
含 T+1 自动出账与门店手动提现;按类型筛选,详情与审核动作沿用原接口
|
||||
</Typography.Text>
|
||||
{overdueSummary && overdueSummary.overdueCount > 0 ? (
|
||||
<Typography.Text type="danger">
|
||||
手动提现超时未审 {overdueSummary.overdueCount} 笔(待审共 {overdueSummary.pendingCount})
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
</Space>
|
||||
|
||||
{summary && (
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space size="large" wrap>
|
||||
<Statistic title="账单数" value={summary.count} />
|
||||
<Statistic title="记录数" value={summary.count} />
|
||||
<Statistic title="核销金额合计" value={summary.redeemAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.payoutAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.payoutAmount ?? summary.totalAmount ?? 0} prefix="¥" precision={2} />
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
@@ -208,16 +356,37 @@ export default function StoreBillsPage() {
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
onFinish={(v: { storeId?: string; status?: string; range?: [Dayjs, Dayjs] }) => {
|
||||
initialValues={{
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
}}
|
||||
onFinish={(v: {
|
||||
kind?: string;
|
||||
storeId?: string;
|
||||
status?: string;
|
||||
range?: [Dayjs, Dayjs];
|
||||
}) => {
|
||||
setFilters({
|
||||
kind: v.kind || '',
|
||||
storeId: v.storeId || '',
|
||||
status: v.status || '',
|
||||
dateFrom: v.range?.[0] ? v.range[0].format('YYYY-MM-DD') : '',
|
||||
dateTo: v.range?.[1] ? v.range[1].format('YYYY-MM-DD') : '',
|
||||
});
|
||||
setPage(1);
|
||||
setSelectedKeys([]);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="kind" label="类型">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={Object.entries(STORE_SETTLEMENT_KIND_LABELS).map(([value, label]) => ({
|
||||
value,
|
||||
label,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店">
|
||||
<Select
|
||||
allowClear
|
||||
@@ -232,10 +401,16 @@ export default function StoreBillsPage() {
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({ value, label }))}
|
||||
options={Object.entries(STORE_SETTLEMENT_STATUS_LABELS).map(([value, label]) => ({
|
||||
value,
|
||||
label:
|
||||
value === 'PAID'
|
||||
? '已打款/已结算'
|
||||
: label,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="range" label="账单日">
|
||||
<Form.Item name="range" label="日期">
|
||||
<DatePicker.RangePicker />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
@@ -249,6 +424,7 @@ export default function StoreBillsPage() {
|
||||
form.resetFields();
|
||||
setFilters({});
|
||||
setPage(1);
|
||||
setSelectedKeys([]);
|
||||
}}
|
||||
>
|
||||
重置
|
||||
@@ -256,33 +432,36 @@ export default function StoreBillsPage() {
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button loading={exporting} onClick={() => void exportExcel()}>
|
||||
导出 Excel
|
||||
导出 T+1 Excel
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button
|
||||
type="primary"
|
||||
disabled={!selectedKeys.length}
|
||||
disabled={!selectedRows.length}
|
||||
loading={batchLoading}
|
||||
onClick={() => confirmPay(selectedKeys.map(String), selectedAmount)}
|
||||
onClick={() => confirmPay(selectedRows.map((r) => r.id), selectedAmount)}
|
||||
>
|
||||
批量确认打款 ({selectedKeys.length})
|
||||
批量确认打款 ({selectedRows.length})
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<Table
|
||||
rowKey="id"
|
||||
rowKey={(r) => `${r.kind}-${r.id}`}
|
||||
className="admin-table-nowrap"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
rowClassName={(row) => (row.overdue ? 'ant-table-row-selected' : '')}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedKeys,
|
||||
onChange: setSelectedKeys,
|
||||
getCheckboxProps: (r) => ({ disabled: r.status !== 'UNPAID' }),
|
||||
getCheckboxProps: (r) => ({
|
||||
disabled: !(r.kind === 'T1_BILL' && r.status === 'UNPAID'),
|
||||
}),
|
||||
}}
|
||||
scroll={{ x: 1200 }}
|
||||
scroll={{ x: 1300 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
@@ -295,14 +474,25 @@ export default function StoreBillsPage() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer title="门店对账单明细" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}>
|
||||
{detail && (
|
||||
<Drawer
|
||||
title={detailKind === 'WITHDRAW' ? '手动提现明细' : 'T+1 对账单明细'}
|
||||
open={drawerOpen}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
width={detailKind === 'WITHDRAW' ? 640 : 520}
|
||||
>
|
||||
{detail && detailKind === 'T1_BILL' && (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">{String(detail.billDate || '').slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">¥{Number(detail.payoutAmount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">{STATUS_LABELS[String(detail.status)] || String(detail.status)}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">
|
||||
{String(detail.billDate || '').slice(0, 10)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">
|
||||
¥{Number(detail.payoutAmount ?? 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{storeSettlementStatusLabel('T1_BILL', String(detail.status))}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="打款时间">
|
||||
{detail.paidAt ? fmtTime(String(detail.paidAt)) : '—'}
|
||||
</Descriptions.Item>
|
||||
@@ -318,7 +508,8 @@ export default function StoreBillsPage() {
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
||||
render: (_, r) =>
|
||||
String((r.redeemRecord as { redeemNo?: string })?.redeemNo || '—'),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
@@ -334,6 +525,83 @@ export default function StoreBillsPage() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{detail && detailKind === 'WITHDRAW' && (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="提现单号">{String(detail.withdrawNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="金额">
|
||||
¥{Number(detail.amount ?? 0).toFixed(2)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{storeSettlementStatusLabel('WITHDRAW', String(detail.status))}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="申请时间">
|
||||
{detail.appliedAt ? fmtTime(String(detail.appliedAt)) : '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="驳回理由">
|
||||
{detail.rejectReason ? String(detail.rejectReason) : '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="打款凭证">
|
||||
{detail.paymentRef ? String(detail.paymentRef) : '—'}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{storeAccount ? (
|
||||
<>
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
收款账户
|
||||
</Typography.Title>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="户名">
|
||||
{storeAccount.bankAccountName || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="账号">
|
||||
{storeAccount.bankAccountNo || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="开户行">
|
||||
{storeAccount.bankBranch || '—'}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</>
|
||||
) : null}
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
提现明细
|
||||
</Typography.Title>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey="id"
|
||||
pagination={false}
|
||||
dataSource={withdrawDetailItems}
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => {
|
||||
const payout = r.storePayout as
|
||||
| { redeemRecord?: { redeemNo?: string }; payoutAmount?: number }
|
||||
| undefined;
|
||||
return String(payout?.redeemRecord?.redeemNo || '—');
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '应付',
|
||||
render: (_, r) => {
|
||||
const payout = r.storePayout as { payoutAmount?: number } | undefined;
|
||||
return `¥${Number(payout?.payoutAmount ?? 0).toFixed(2)}`;
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{String(detail.status) === 'PENDING_REVIEW' ? (
|
||||
<Space style={{ marginTop: 16 }}>
|
||||
<Button type="primary" onClick={() => approveWithdraw(String(detail.id))}>
|
||||
通过
|
||||
</Button>
|
||||
<Button danger onClick={() => rejectWithdraw(String(detail.id))}>
|
||||
驳回
|
||||
</Button>
|
||||
</Space>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button, Form, Input, Table, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
serviceScore: number;
|
||||
envScore: number;
|
||||
createdAt: string;
|
||||
redeemNo: string;
|
||||
redeemAmount: number;
|
||||
store?: { id: string; name: string; cityName?: string };
|
||||
user?: { userNo: string; phone: string | null; nickname: string | null };
|
||||
};
|
||||
|
||||
export default function StoreRatingsPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialStoreId = searchParams.get('storeId') || '';
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({
|
||||
...(initialStoreId ? { storeId: initialStoreId } : {}),
|
||||
});
|
||||
|
||||
const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<Row>(
|
||||
'/admin/store-ratings',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.redeemNo) qs.set('redeemNo', filters.redeemNo);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
);
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||
{
|
||||
title: '门店',
|
||||
dataIndex: ['store', 'name'],
|
||||
render: (v, row) => (row.store?.cityName ? `${v}(${row.store.cityName})` : v),
|
||||
},
|
||||
{
|
||||
title: '用户',
|
||||
width: 140,
|
||||
render: (_, row) => row.user?.phone || row.user?.userNo || '-',
|
||||
},
|
||||
{ title: '核销额', dataIndex: 'redeemAmount', width: 90, render: (v) => `¥${v}` },
|
||||
{ title: '服务分', dataIndex: 'serviceScore', width: 80 },
|
||||
{ title: '环境分', dataIndex: 'envScore', width: 80 },
|
||||
{ title: '评价时间', dataIndex: 'createdAt', width: 170, render: fmtTime },
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4} style={{ marginTop: 0 }}>
|
||||
门店评价
|
||||
</Typography.Title>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16 }}
|
||||
initialValues={filters}
|
||||
onFinish={(v) => {
|
||||
setFilters({
|
||||
storeId: v.storeId || '',
|
||||
redeemNo: v.redeemNo || '',
|
||||
});
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<Form.Item name="storeId" label="门店ID">
|
||||
<Input allowClear placeholder="storeId" />
|
||||
</Form.Item>
|
||||
<Form.Item name="redeemNo" label="核销号">
|
||||
<Input allowClear />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
DatePicker,
|
||||
Descriptions,
|
||||
Drawer,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import { STORE_WITHDRAW_STATUS_LABELS, type StoreWithdrawStatus } from '@dukang/shared-types';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
withdrawNo: string;
|
||||
amount: number;
|
||||
payoutCount: number;
|
||||
status: StoreWithdrawStatus;
|
||||
appliedAt: string;
|
||||
reviewedAt?: string | null;
|
||||
paidAt?: string | null;
|
||||
paymentRef?: string | null;
|
||||
rejectReason?: string | null;
|
||||
overdue?: boolean;
|
||||
store?: { id: string; name: string; cityName: string; phone?: string };
|
||||
};
|
||||
|
||||
type StoreOption = { id: string; name: string; phone: string };
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
PENDING_REVIEW: 'orange',
|
||||
REJECTED: 'red',
|
||||
PAID: 'green',
|
||||
};
|
||||
|
||||
export default function StoreWithdrawalsPage() {
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({ status: 'PENDING_REVIEW' });
|
||||
const [stores, setStores] = useState<StoreOption[]>([]);
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||
'/admin/store-withdrawals',
|
||||
() => {
|
||||
const qs = new URLSearchParams();
|
||||
if (filters.status) qs.set('status', filters.status);
|
||||
if (filters.storeId) qs.set('storeId', filters.storeId);
|
||||
if (filters.dateFrom) qs.set('dateFrom', filters.dateFrom);
|
||||
if (filters.dateTo) qs.set('dateTo', filters.dateTo);
|
||||
return qs;
|
||||
},
|
||||
[filters],
|
||||
);
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [overdueSummary, setOverdueSummary] = useState<{
|
||||
pendingCount: number;
|
||||
overdueCount: number;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
.then((res) => setStores(res.items))
|
||||
.catch(() => {});
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function openDetail(id: string) {
|
||||
const d = await request<Record<string, unknown>>(`/admin/store-withdrawals/${id}`);
|
||||
setDetail(d);
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
|
||||
function approve(id: string) {
|
||||
let paymentRef = '';
|
||||
Modal.confirm({
|
||||
title: '审核通过并标记已结算?',
|
||||
content: (
|
||||
<Input
|
||||
placeholder="打款凭证号(可选)"
|
||||
onChange={(e) => {
|
||||
paymentRef = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '通过并结算',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
await request(`/admin/store-withdrawals/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
|
||||
});
|
||||
message.success('已通过并标记已结算');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
void request<{ pendingCount: number; overdueCount: number }>(
|
||||
'/admin/store-withdrawals/overdue-summary',
|
||||
)
|
||||
.then(setOverdueSummary)
|
||||
.catch(() => {});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function reject(id: string) {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '驳回提现申请?',
|
||||
content: (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
placeholder="请填写驳回理由"
|
||||
onChange={(e) => {
|
||||
reason = e.target.value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
okText: '确认驳回',
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) {
|
||||
message.error('请填写驳回理由');
|
||||
throw new Error('reason required');
|
||||
}
|
||||
await request(`/admin/store-withdrawals/${id}/reject`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: reason.trim() }),
|
||||
});
|
||||
message.success('已驳回');
|
||||
setDrawerOpen(false);
|
||||
reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Row> = [
|
||||
{
|
||||
title: '提现单号',
|
||||
dataIndex: 'withdrawNo',
|
||||
width: 180,
|
||||
render: (v, row) => (
|
||||
<Space>
|
||||
<Typography.Link onClick={() => void openDetail(row.id)}>{v}</Typography.Link>
|
||||
{row.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '门店',
|
||||
dataIndex: ['store', 'name'],
|
||||
width: 160,
|
||||
render: (_, row) => (
|
||||
<div>
|
||||
<div>{row.store?.name || '—'}</div>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{row.store?.cityName} {row.store?.phone}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '金额',
|
||||
dataIndex: 'amount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{ title: '明细笔数', dataIndex: 'payoutCount', width: 90 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 100,
|
||||
render: (v: StoreWithdrawStatus) => (
|
||||
<Tag color={STATUS_COLORS[v]}>{STORE_WITHDRAW_STATUS_LABELS[v] ?? v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '申请时间',
|
||||
dataIndex: 'appliedAt',
|
||||
width: 170,
|
||||
render: (v) => fmtTime(v),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'actions',
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => void openDetail(row.id)}>
|
||||
详情
|
||||
</Button>
|
||||
{row.status === 'PENDING_REVIEW' ? (
|
||||
<>
|
||||
<Button size="small" type="primary" onClick={() => approve(row.id)}>
|
||||
通过
|
||||
</Button>
|
||||
<Button size="small" danger onClick={() => reject(row.id)}>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const detailItems = (detail?.items as Array<Record<string, unknown>> | undefined) ?? [];
|
||||
const storeAccount = detail?.storeAccount as
|
||||
| {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
bankAccountName?: string;
|
||||
bankAccountNo?: string;
|
||||
bankBranch?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4} style={{ marginTop: 0 }}>
|
||||
门店提现审
|
||||
</Typography.Title>
|
||||
{overdueSummary ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
待审 {overdueSummary.pendingCount} 笔
|
||||
{overdueSummary.overdueCount > 0 ? (
|
||||
<Typography.Text type="danger">
|
||||
{' '}
|
||||
· 超时未审 {overdueSummary.overdueCount} 笔(FIN-003)
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
style={{ marginBottom: 16, gap: 8 }}
|
||||
initialValues={{ status: 'PENDING_REVIEW' }}
|
||||
onFinish={(v) => {
|
||||
const range = v.range as [Dayjs, Dayjs] | undefined;
|
||||
setFilters({
|
||||
status: v.status || '',
|
||||
storeId: v.storeId || '',
|
||||
dateFrom: range?.[0]?.format('YYYY-MM-DD') || '',
|
||||
dateTo: range?.[1]?.format('YYYY-MM-DD') || '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
options={[
|
||||
{ value: 'PENDING_REVIEW', label: '待审核' },
|
||||
{ value: 'PAID', label: '已结算' },
|
||||
{ value: 'REJECTED', label: '已驳回' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="storeId" label="门店">
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: 220 }}
|
||||
options={stores.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name} (${s.phone})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="range" label="申请日">
|
||||
<DatePicker.RangePicker />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
<Button type="primary" htmlType="submit">
|
||||
查询
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1100 }}
|
||||
rowClassName={(row) => (row.overdue ? 'ant-table-row-selected' : '')}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer
|
||||
title="提现详情"
|
||||
width={640}
|
||||
open={drawerOpen}
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
extra={
|
||||
detail?.status === 'PENDING_REVIEW' ? (
|
||||
<Space>
|
||||
<Button type="primary" onClick={() => approve(String(detail.id))}>
|
||||
通过
|
||||
</Button>
|
||||
<Button danger onClick={() => reject(String(detail.id))}>
|
||||
驳回
|
||||
</Button>
|
||||
</Space>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detail ? (
|
||||
<>
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="提现单号">{String(detail.withdrawNo)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={STATUS_COLORS[String(detail.status)]}>
|
||||
{STORE_WITHDRAW_STATUS_LABELS[detail.status as StoreWithdrawStatus] ??
|
||||
String(detail.status)}
|
||||
</Tag>
|
||||
{detail.overdue ? <Tag color="magenta">超时</Tag> : null}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="金额">¥{Number(detail.amount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="明细笔数">{String(detail.payoutCount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="申请时间">{fmtTime(String(detail.appliedAt))}</Descriptions.Item>
|
||||
{detail.rejectReason ? (
|
||||
<Descriptions.Item label="驳回理由">{String(detail.rejectReason)}</Descriptions.Item>
|
||||
) : null}
|
||||
{detail.paymentRef ? (
|
||||
<Descriptions.Item label="打款凭证">{String(detail.paymentRef)}</Descriptions.Item>
|
||||
) : null}
|
||||
<Descriptions.Item label="收款户名">
|
||||
{storeAccount?.bankAccountName || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="收款账号">
|
||||
{storeAccount?.bankAccountNo || '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="开户行">{storeAccount?.bankBranch || '—'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Typography.Title level={5} style={{ marginTop: 24 }}>
|
||||
关联结算明细
|
||||
</Typography.Title>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey={(r) => String((r as { id?: string }).id)}
|
||||
pagination={false}
|
||||
dataSource={detailItems}
|
||||
columns={[
|
||||
{
|
||||
title: '核销单号',
|
||||
render: (_, r) => {
|
||||
const payout = (r as { storePayout?: { redeemRecord?: { redeemNo?: string } } })
|
||||
.storePayout;
|
||||
return payout?.redeemRecord?.redeemNo || '—';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '结算额',
|
||||
render: (_, r) => {
|
||||
const payout = (r as { storePayout?: { payoutAmount?: number } }).storePayout;
|
||||
return `¥${Number(payout?.payoutAmount ?? 0).toFixed(2)}`;
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Alert,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Select,
|
||||
Space,
|
||||
Steps,
|
||||
Switch,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { FormInstance } from 'antd/es/form';
|
||||
import { FilePdfOutlined, LinkOutlined, EnvironmentOutlined } from '@ant-design/icons';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import {
|
||||
@@ -274,6 +276,89 @@ function StoreAuditMediaSection({ detail }: { detail: Record<string, unknown> })
|
||||
);
|
||||
}
|
||||
|
||||
type UserPickRow = { id: string; phone?: string | null; nickname?: string | null; userNo?: string | null };
|
||||
|
||||
function StoreVisibilityWhitelistFields({ form }: { form: FormInstance }) {
|
||||
const [userOptions, setUserOptions] = useState<UserPickRow[]>([]);
|
||||
const [userSearching, setUserSearching] = useState(false);
|
||||
const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
async function searchUsers(keyword: string) {
|
||||
const q = keyword.trim();
|
||||
if (searchTimer.current) clearTimeout(searchTimer.current);
|
||||
if (!q) {
|
||||
setUserOptions([]);
|
||||
return;
|
||||
}
|
||||
searchTimer.current = setTimeout(() => {
|
||||
void (async () => {
|
||||
setUserSearching(true);
|
||||
try {
|
||||
const qs = new URLSearchParams({ page: '1', pageSize: '20', phone: q });
|
||||
const res = await request<{ items: UserPickRow[] }>(`/admin/users?${qs}`);
|
||||
setUserOptions((res.items ?? []).filter((u) => !!u.phone));
|
||||
} catch {
|
||||
setUserOptions([]);
|
||||
} finally {
|
||||
setUserSearching(false);
|
||||
}
|
||||
})();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
const enabled = Form.useWatch('visibilityWhitelistEnabled', form);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form.Item
|
||||
name="visibilityWhitelistEnabled"
|
||||
label="可见白名单"
|
||||
valuePropName="checked"
|
||||
extra="开启后仅名单内手机号在 C 端可见,用于在线测试"
|
||||
>
|
||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||
</Form.Item>
|
||||
{enabled ? (
|
||||
<>
|
||||
<Form.Item
|
||||
name="visibilityPhones"
|
||||
label="白名单手机号"
|
||||
rules={[{ required: true, message: '请至少添加一个手机号' }]}
|
||||
extra="可直接输入多个手机号回车添加,或从下方用户库选择"
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
tokenSeparators={[',', ' ', ',', ';', ';']}
|
||||
placeholder="输入手机号后回车"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="从用户库添加">
|
||||
<Select
|
||||
showSearch
|
||||
filterOption={false}
|
||||
placeholder="按手机号搜索用户"
|
||||
loading={userSearching}
|
||||
options={userOptions.map((u) => ({
|
||||
value: u.phone!,
|
||||
label: `${u.phone}${u.nickname ? ` · ${u.nickname}` : ''}${u.userNo ? `(${u.userNo})` : ''}`,
|
||||
}))}
|
||||
onSearch={searchUsers}
|
||||
onSelect={(phone: string) => {
|
||||
const cur = (form.getFieldValue('visibilityPhones') as string[] | undefined) ?? [];
|
||||
if (!cur.includes(phone)) {
|
||||
form.setFieldsValue({ visibilityPhones: [...cur, phone] });
|
||||
}
|
||||
}}
|
||||
notFoundContent={userSearching ? '搜索中…' : '输入手机号搜索'}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type StoreRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -287,6 +372,8 @@ type StoreRow = {
|
||||
intro: string | null;
|
||||
coverUrl: string | null;
|
||||
createdAt: string;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
cityRef?: { name: string; code: string };
|
||||
partner?: { companyName: string };
|
||||
account?: {
|
||||
@@ -306,7 +393,14 @@ type StoreRow = {
|
||||
category?: { id: string; name: string; parentId?: string | null } | null;
|
||||
};
|
||||
|
||||
type PartnerOption = { id: string; companyName: string };
|
||||
type PartnerOption = { id: string; companyName: string; name?: string };
|
||||
|
||||
function partnerOptionLabel(p: PartnerOption): string {
|
||||
const company = (p.companyName || '').trim();
|
||||
const person = (p.name || '').trim();
|
||||
if (company && person) return `${company}-${person}`;
|
||||
return company || person || p.id;
|
||||
}
|
||||
type CityOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -497,6 +591,10 @@ export default function StoresPage() {
|
||||
bankAccountName: account?.bankAccountName || undefined,
|
||||
bankAccountNo: account?.bankAccountNo || undefined,
|
||||
bankBranch: account?.bankBranch || undefined,
|
||||
visibilityWhitelistEnabled: !!d.visibilityWhitelistEnabled,
|
||||
visibilityPhones: Array.isArray(d.visibilityPhones)
|
||||
? (d.visibilityPhones as string[])
|
||||
: [],
|
||||
});
|
||||
setDrawerOpen(true);
|
||||
}
|
||||
@@ -536,6 +634,10 @@ export default function StoresPage() {
|
||||
bankAccountName: v.bankAccountName ?? null,
|
||||
bankAccountNo: v.bankAccountNo ?? null,
|
||||
bankBranch: v.bankBranch ?? null,
|
||||
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||
visibilityPhones: ((v.visibilityPhones as string[] | undefined) ?? [])
|
||||
.map((p) => String(p || '').replace(/\D/g, '').trim())
|
||||
.filter(Boolean),
|
||||
...(hasCoords
|
||||
? { latitude: Number(v.latitude), longitude: Number(v.longitude) }
|
||||
: {}),
|
||||
@@ -625,6 +727,8 @@ export default function StoresPage() {
|
||||
openTime2: undefined,
|
||||
closeTime2: undefined,
|
||||
avgPrice: undefined,
|
||||
visibilityWhitelistEnabled: false,
|
||||
visibilityPhones: [],
|
||||
});
|
||||
setCreateStep(0);
|
||||
setCreateError('');
|
||||
@@ -706,6 +810,10 @@ export default function StoresPage() {
|
||||
bankAccountNo: values.bankAccountNo.replace(/\s/g, ''),
|
||||
bankBranch: values.bankBranch.trim(),
|
||||
settlementRate: Number(values.settlementRate ?? 60) / 100,
|
||||
visibilityWhitelistEnabled: !!values.visibilityWhitelistEnabled,
|
||||
visibilityPhones: (values.visibilityPhones ?? [])
|
||||
.map((p: string) => String(p || '').replace(/\D/g, '').trim())
|
||||
.filter(Boolean),
|
||||
}),
|
||||
});
|
||||
message.success('门店已创建');
|
||||
@@ -759,13 +867,23 @@ export default function StoresPage() {
|
||||
},
|
||||
},
|
||||
{ title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 120 },
|
||||
{
|
||||
title: '可见',
|
||||
dataIndex: 'visibilityWhitelistEnabled',
|
||||
width: 90,
|
||||
render: (v, row) =>
|
||||
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||
},
|
||||
{ title: '介绍', dataIndex: 'intro', width: 160, ellipsis: true, render: (v) => v || '—' },
|
||||
{ title: '店长', dataIndex: ['account', 'name'], width: 90, render: (v) => v || '—' },
|
||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
{
|
||||
title: '操作', width: 80,
|
||||
title: '操作', width: 140,
|
||||
render: (_, row) => (
|
||||
<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>
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -799,7 +917,7 @@ export default function StoresPage() {
|
||||
optionFilterProp="label"
|
||||
style={{ width: 180 }}
|
||||
placeholder="全部"
|
||||
options={filterPartners.map((p) => ({ value: p.id, label: p.companyName || p.id }))}
|
||||
options={filterPartners.map((p) => ({ value: p.id, label: partnerOptionLabel(p) }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="status" label="营业状态">
|
||||
@@ -1049,6 +1167,7 @@ export default function StoresPage() {
|
||||
<Input type="time" style={{ width: 140 }} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<StoreVisibilityWhitelistFields form={editForm} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
@@ -1129,7 +1248,7 @@ export default function StoresPage() {
|
||||
loading={optionsLoading}
|
||||
optionFilterProp="label"
|
||||
placeholder={optionsLoading ? '加载中…' : '请选择开城合伙人'}
|
||||
options={partners.map((p) => ({ value: p.id, label: p.companyName }))}
|
||||
options={partners.map((p) => ({ value: p.id, label: partnerOptionLabel(p) }))}
|
||||
onChange={(partnerAccountId) => {
|
||||
const codes = createForm.getFieldValue('regionCodes') as string[] | undefined;
|
||||
if (codes?.length === 3) bindRegionSelection(codes, partnerAccountId);
|
||||
@@ -1269,6 +1388,7 @@ export default function StoresPage() {
|
||||
>
|
||||
<Input.TextArea rows={3} placeholder="选填,最多1000字" showCount maxLength={1000} />
|
||||
</Form.Item>
|
||||
<StoreVisibilityWhitelistFields form={createForm} />
|
||||
</div>
|
||||
<div style={{ display: createStep === 1 ? 'block' : 'none' }}>
|
||||
<Typography.Paragraph type="secondary">
|
||||
|
||||
@@ -61,6 +61,34 @@ function MockSmsCodePanel({ codes, loading }: { codes: MockSmsCodeItem[]; loadin
|
||||
);
|
||||
}
|
||||
|
||||
function WecomAlertTestButton() {
|
||||
const [testing, setTesting] = useState(false);
|
||||
async function onTest() {
|
||||
setTesting(true);
|
||||
try {
|
||||
const res = await request<{ ok: boolean; message: string }>(
|
||||
'/admin/system-config/wecom-alert/test',
|
||||
{ method: 'POST', body: '{}' },
|
||||
);
|
||||
message.success(res.message || '已发送测试告警');
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '发送失败');
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div style={{ marginTop: -8, marginBottom: 16 }}>
|
||||
<Button size="small" loading={testing} onClick={() => void onTest()}>
|
||||
发送测试告警
|
||||
</Button>
|
||||
<Typography.Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
|
||||
需已配置 WECOM_ALERT_WEBHOOK_URL 并开启上方开关
|
||||
</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderField(
|
||||
field: SystemConfigFieldMeta,
|
||||
configuredSecrets: string[],
|
||||
@@ -263,6 +291,8 @@ export default function SystemSettingsPage() {
|
||||
meta.configuredSecrets,
|
||||
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
||||
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
||||
) : f.key === 'WECOM_ALERT_ENABLED' ? (
|
||||
<WecomAlertTestButton />
|
||||
) : undefined,
|
||||
),
|
||||
)}
|
||||
|
||||
@@ -9,15 +9,17 @@
|
||||
"lint": "echo ok"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/weixin-sdk": "workspace:*",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -16,6 +16,8 @@ import SettlementPage from './pages/SettlementPage';
|
||||
import WeeklyReportPage from './pages/WeeklyReportPage';
|
||||
import ProxyOrderPage from './pages/ProxyOrderPage';
|
||||
import ProxyOrderProductsPage from './pages/ProxyOrderProductsPage';
|
||||
import ProxyOrderListPage from './pages/ProxyOrderListPage';
|
||||
import ProxyOrderDetailPage from './pages/ProxyOrderDetailPage';
|
||||
import StaffListPage from './pages/StaffListPage';
|
||||
import StaffCreatePage from './pages/StaffCreatePage';
|
||||
import LeaderboardPage from './pages/LeaderboardPage';
|
||||
@@ -33,6 +35,8 @@ function PrimaryRoutes() {
|
||||
<Route path="/center/settlement" element={<SettlementPage />} />
|
||||
<Route path="/center/staff" element={<StaffListPage />} />
|
||||
<Route path="/center/staff/new" element={<StaffCreatePage />} />
|
||||
<Route path="/center/proxy-orders" element={<ProxyOrderListPage />} />
|
||||
<Route path="/center/proxy-orders/:id" element={<ProxyOrderDetailPage />} />
|
||||
<Route path="/proxy-order" element={<ProxyOrderPage />} />
|
||||
<Route path="/proxy-order/products" element={<ProxyOrderProductsPage />} />
|
||||
<Route path="/reports/weekly" element={<WeeklyReportPage />} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getPartnerProfile } from '../lib/api';
|
||||
import { getPartnerProfile, hasPartnerWxSession } from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getPartnerProfile();
|
||||
if (profile && hasPartnerWxSession() && profile.hasWechat) {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { uploadFileToOss, type OssMediaType } from '../lib/upload';
|
||||
import { enqueueUpload } from '../lib/upload-lock';
|
||||
import { formatChooseImageFailMessage } from '@dukang/weixin-sdk';
|
||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||
import { toastError } from '../lib/toast';
|
||||
|
||||
type OssUploadFieldProps = {
|
||||
@@ -12,10 +14,31 @@ type OssUploadFieldProps = {
|
||||
wide?: boolean;
|
||||
compact?: boolean;
|
||||
label?: string;
|
||||
/** 兼容现有调用:选图不再依赖 openId 绑定 */
|
||||
wechatReady?: boolean;
|
||||
onWechatReadyChange?: (ready: boolean) => void;
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_MB = 10;
|
||||
|
||||
function isCancelError(msg: string): boolean {
|
||||
return /cancel|取消/i.test(msg);
|
||||
}
|
||||
|
||||
function formatWechatUploadError(e: unknown): string {
|
||||
const msg = e instanceof Error ? e.message : '无法打开相册';
|
||||
const formatted = formatChooseImageFailMessage(msg);
|
||||
if (formatted) return formatted;
|
||||
if (/invalid signature/i.test(msg)) {
|
||||
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
function acceptsImages(accept: string) {
|
||||
return accept.includes('image');
|
||||
}
|
||||
|
||||
export default function OssUploadField({
|
||||
value,
|
||||
onChange,
|
||||
@@ -27,8 +50,10 @@ export default function OssUploadField({
|
||||
label,
|
||||
}: OssUploadFieldProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const pickingRef = useRef(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [showAlbumFallback, setShowAlbumFallback] = useState(false);
|
||||
|
||||
function showUploadError(text: string) {
|
||||
setError(text);
|
||||
@@ -37,6 +62,17 @@ export default function OssUploadField({
|
||||
|
||||
const resolvedAccept =
|
||||
accept ?? (mediaType === 'VIDEO' ? 'video/*' : mediaType === 'FILE' ? 'image/*,.pdf' : 'image/*');
|
||||
const inWechat = isWechatEnv();
|
||||
const useWechatPicker =
|
||||
inWechat && (mediaType === 'IMAGE' || (mediaType === 'FILE' && acceptsImages(resolvedAccept)));
|
||||
|
||||
useEffect(() => {
|
||||
if (!useWechatPicker) return;
|
||||
// 仅预热,勿在每次点击时 reset,否则取消后再点常无法调起
|
||||
void weixinSdk.init().catch(() => {
|
||||
/* 点击上传时会再次初始化 */
|
||||
});
|
||||
}, [useWechatPicker]);
|
||||
|
||||
async function persistUpload(file: File) {
|
||||
if (!file.size) {
|
||||
@@ -64,21 +100,66 @@ export default function OssUploadField({
|
||||
}
|
||||
}
|
||||
|
||||
function pickFile() {
|
||||
if (uploading) return;
|
||||
async function pickWechatImage() {
|
||||
if (pickingRef.current || uploading) return;
|
||||
pickingRef.current = true;
|
||||
setError('');
|
||||
try {
|
||||
// 不要每次 reset:会打断 JSSDK,取消后再点经常无法调起相机/相册
|
||||
await weixinSdk.init();
|
||||
const files = await weixinSdk.chooseImages({
|
||||
count: 1,
|
||||
sourceType: ['album', 'camera'],
|
||||
});
|
||||
// 取消或未选图:直接结束,允许再次点击
|
||||
if (!files?.length) return;
|
||||
|
||||
setUploading(true);
|
||||
try {
|
||||
// 仅串行化实际上传,选图本身不占上传锁,避免取消后锁态异常
|
||||
await enqueueUpload(() => persistUpload(files[0]!));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '无法打开相册';
|
||||
if (isCancelError(msg)) return;
|
||||
throw e;
|
||||
} finally {
|
||||
pickingRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pickFile() {
|
||||
if (uploading || pickingRef.current) return;
|
||||
setError('');
|
||||
|
||||
if (useWechatPicker) {
|
||||
try {
|
||||
await pickWechatImage();
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '无法打开相册';
|
||||
if (isCancelError(msg)) return;
|
||||
const formatted = formatWechatUploadError(e);
|
||||
setError(`${formatted},可改从系统相册选择`);
|
||||
setShowAlbumFallback(true);
|
||||
inputRef.current?.click();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
inputRef.current?.click();
|
||||
}
|
||||
|
||||
const isImage = mediaType === 'IMAGE' && value;
|
||||
const isFile = mediaType === 'FILE' && value;
|
||||
const busy = uploading;
|
||||
const pickerLabel = label ?? (mediaType === 'IMAGE' ? '从系统相册选择' : '点击上传');
|
||||
const pickerLabel = label ?? (useWechatPicker ? '拍照 / 从相册选择' : '点击上传');
|
||||
|
||||
const triggerProps = {
|
||||
type: 'button' as const,
|
||||
disabled: busy,
|
||||
onClick: pickFile,
|
||||
onClick: () => void pickFile(),
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -92,6 +173,7 @@ export default function OssUploadField({
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setShowAlbumFallback(false);
|
||||
void uploadSelectedFile(file);
|
||||
}
|
||||
}}
|
||||
@@ -120,13 +202,24 @@ export default function OssUploadField({
|
||||
className={`partner-upload-dashed${wide ? ' partner-upload-dashed--wide' : ''}${compact ? ' partner-upload-dashed--compact' : ''}`}
|
||||
>
|
||||
<span className="material-symbols-outlined text-primary" style={{ fontSize: compact ? 28 : 36 }}>
|
||||
{busy ? 'hourglass_top' : 'photo_library'}
|
||||
{busy ? 'hourglass_top' : 'add_a_photo'}
|
||||
</span>
|
||||
<span className="text-primary" style={{ fontWeight: 500 }}>
|
||||
{uploading ? '上传中…' : pickerLabel}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{showAlbumFallback && useWechatPicker && (
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ marginTop: 8, width: '100%' }}
|
||||
disabled={busy}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
从系统相册选择
|
||||
</button>
|
||||
)}
|
||||
{error && <p className="partner-form-error" role="alert">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { ClientRuntimeConfig } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import {
|
||||
placeToPicked,
|
||||
type LbsPlaceItem,
|
||||
buildTencentLocPickerUrl,
|
||||
parseTencentLocPickerMessage,
|
||||
type TencentPickedLocation,
|
||||
} from '../lib/tencentLocPicker';
|
||||
|
||||
@@ -12,117 +13,84 @@ type Props = {
|
||||
onPick: (loc: TencentPickedLocation) => void;
|
||||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
/** 保留兼容,iframe 选点不使用 */
|
||||
region?: string | null;
|
||||
};
|
||||
|
||||
let cachedKey: string | null | undefined;
|
||||
|
||||
async function loadTencentLbsKey(): Promise<string> {
|
||||
if (cachedKey) return cachedKey;
|
||||
const cfg = await request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config', {
|
||||
silent: true,
|
||||
});
|
||||
const key = (cfg.tencentLbsKey || '').trim();
|
||||
if (!key) {
|
||||
throw new Error('未配置腾讯位置服务 Key,请联系管理员在系统设置中配置');
|
||||
}
|
||||
cachedKey = key;
|
||||
return key;
|
||||
}
|
||||
|
||||
export default function TencentLocPickerOverlay({
|
||||
open,
|
||||
onClose,
|
||||
onPick,
|
||||
latitude,
|
||||
longitude,
|
||||
region,
|
||||
}: Props) {
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [items, setItems] = useState<LbsPlaceItem[]>([]);
|
||||
const [key, setKey] = useState<string | null>(cachedKey ?? null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
/** 选点结果仅存内存,界面不展示经纬度 */
|
||||
const [pending, setPending] = useState<TencentPickedLocation | null>(null);
|
||||
const [hint, setHint] = useState('输入地点名称搜索');
|
||||
const seqRef = useRef(0);
|
||||
const [iframeReady, setIframeReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setKeyword('');
|
||||
setItems([]);
|
||||
setPending(null);
|
||||
setHint('输入地点名称搜索');
|
||||
setIframeReady(false);
|
||||
setError('');
|
||||
return;
|
||||
}
|
||||
const lat = latitude != null ? Number(latitude) : NaN;
|
||||
const lng = longitude != null ? Number(longitude) : NaN;
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng) && !(lat === 0 && lng === 0)) {
|
||||
void loadNearby(lat, lng);
|
||||
let cancelled = false;
|
||||
if (key) return;
|
||||
setLoading(true);
|
||||
void loadTencentLbsKey()
|
||||
.then((k) => {
|
||||
if (!cancelled) setKey(k);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e instanceof Error ? e.message : '加载地图配置失败');
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onMessage(event: MessageEvent) {
|
||||
const picked = parseTencentLocPickerMessage(event.data);
|
||||
if (!picked) return;
|
||||
setPending(picked);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
window.addEventListener('message', onMessage);
|
||||
return () => window.removeEventListener('message', onMessage);
|
||||
}, [open]);
|
||||
|
||||
async function loadNearby(lat: number, lng: number) {
|
||||
const seq = ++seqRef.current;
|
||||
setLoading(true);
|
||||
setHint('正在加载附近地点…');
|
||||
try {
|
||||
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||
'PARTNER_H5',
|
||||
`/common/lbs/nearby?lat=${encodeURIComponent(String(lat))}&lng=${encodeURIComponent(String(lng))}`,
|
||||
{ silent: true },
|
||||
);
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems(res.items ?? []);
|
||||
setHint(res.items?.length ? `附近 ${res.items.length} 个地点` : '附近暂无地点,请搜索');
|
||||
} catch (e) {
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems([]);
|
||||
setHint(e instanceof Error ? e.message : '加载附近地点失败');
|
||||
} finally {
|
||||
if (seq === seqRef.current) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSearch() {
|
||||
const trimmed = keyword.trim();
|
||||
if (!trimmed) {
|
||||
setHint('请输入搜索关键词');
|
||||
return;
|
||||
}
|
||||
const seq = ++seqRef.current;
|
||||
setLoading(true);
|
||||
setHint('搜索中…');
|
||||
try {
|
||||
const params = new URLSearchParams({ keyword: trimmed });
|
||||
if (region?.trim()) params.set('region', region.trim());
|
||||
const lat = latitude != null ? Number(latitude) : NaN;
|
||||
const lng = longitude != null ? Number(longitude) : NaN;
|
||||
if (Number.isFinite(lat) && Number.isFinite(lng)) {
|
||||
params.set('lat', String(lat));
|
||||
params.set('lng', String(lng));
|
||||
}
|
||||
const res = await request<{ items: LbsPlaceItem[] }>(
|
||||
'PARTNER_H5',
|
||||
`/common/lbs/suggest?${params.toString()}`,
|
||||
{ silent: true },
|
||||
);
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems(res.items ?? []);
|
||||
setHint(res.items?.length ? `找到 ${res.items.length} 个结果` : '无匹配结果');
|
||||
} catch (e) {
|
||||
if (seq !== seqRef.current) return;
|
||||
setItems([]);
|
||||
setHint(e instanceof Error ? e.message : '搜索失败');
|
||||
} finally {
|
||||
if (seq === seqRef.current) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function useBrowserLocation() {
|
||||
if (!navigator.geolocation) {
|
||||
setHint('当前浏览器不支持定位');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
const lat = pos.coords.latitude;
|
||||
const lng = pos.coords.longitude;
|
||||
setPending({ latitude: lat, longitude: lng, name: '当前位置' });
|
||||
void loadNearby(lat, lng);
|
||||
},
|
||||
() => {
|
||||
setLoading(false);
|
||||
setHint('定位失败,请检查定位权限');
|
||||
},
|
||||
{ enableHighAccuracy: true, timeout: 12000 },
|
||||
);
|
||||
}
|
||||
const src = useMemo(() => {
|
||||
if (!key) return '';
|
||||
const lat = latitude != null ? Number(latitude) : undefined;
|
||||
const lng = longitude != null ? Number(longitude) : undefined;
|
||||
return buildTencentLocPickerUrl(key, {
|
||||
latitude: lat != null && Number.isFinite(lat) ? lat : undefined,
|
||||
longitude: lng != null && Number.isFinite(lng) ? lng : undefined,
|
||||
});
|
||||
}, [key, latitude, longitude]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
@@ -134,6 +102,7 @@ export default function TencentLocPickerOverlay({
|
||||
|
||||
return (
|
||||
<div
|
||||
className="partner-locpicker-overlay"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
@@ -141,123 +110,124 @@ export default function TencentLocPickerOverlay({
|
||||
background: '#fff',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
height: '100dvh',
|
||||
maxHeight: '-webkit-fill-available',
|
||||
paddingTop: 'env(safe-area-inset-top)',
|
||||
paddingBottom: 'env(safe-area-inset-bottom)',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
padding: '12px 16px',
|
||||
flexDirection: 'column',
|
||||
padding: '12px 12px 10px',
|
||||
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||
flexShrink: 0,
|
||||
gap: 8,
|
||||
gap: 10,
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
<button type="button" className="partner-btn-outline" style={{ padding: '6px 12px' }} onClick={onClose}>
|
||||
关闭
|
||||
</button>
|
||||
<span style={{ fontWeight: 600 }}>地图选点</span>
|
||||
<h2
|
||||
style={{
|
||||
margin: 0,
|
||||
textAlign: 'center',
|
||||
fontWeight: 700,
|
||||
fontSize: 17,
|
||||
lineHeight: 1.3,
|
||||
}}
|
||||
>
|
||||
地图选点
|
||||
</h2>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ padding: '6px 12px', opacity: pending ? 1 : 0.45, width: 'auto' }}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '12px 16px',
|
||||
fontSize: 15,
|
||||
fontWeight: 600,
|
||||
opacity: pending ? 1 : 0.45,
|
||||
width: 'auto',
|
||||
}}
|
||||
disabled={!pending}
|
||||
onClick={confirmPick}
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '12px 16px', borderBottom: '1px solid rgba(0,0,0,0.04)', flexShrink: 0 }}>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void runSearch();
|
||||
}}
|
||||
placeholder="输入小区 / 写字楼 / 门店名称"
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '10px 12px',
|
||||
border: '1px solid rgba(0,0,0,0.12)',
|
||||
borderRadius: 8,
|
||||
fontSize: 14,
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ width: 'auto', padding: '8px 14px' }}
|
||||
disabled={loading}
|
||||
onClick={() => void runSearch()}
|
||||
>
|
||||
搜索
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8, alignItems: 'center' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '6px 12px' }}
|
||||
disabled={loading}
|
||||
onClick={useBrowserLocation}
|
||||
style={{ padding: '12px 16px', minWidth: 72, flexShrink: 0 }}
|
||||
onClick={onClose}
|
||||
>
|
||||
定位当前位置
|
||||
关闭
|
||||
</button>
|
||||
<span className="label-md text-muted">{hint}</span>
|
||||
</div>
|
||||
{pending ? (
|
||||
<p className="label-md text-muted" style={{ margin: '8px 0 0' }}>
|
||||
已选 {pending.latitude.toFixed(6)}, {pending.longitude.toFixed(6)}
|
||||
{pending.name ? ` · ${pending.name}` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', WebkitOverflowScrolling: 'touch' }}>
|
||||
{loading && !items.length ? (
|
||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||
加载中…
|
||||
</p>
|
||||
) : items.length ? (
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
|
||||
{items.map((item) => {
|
||||
const active =
|
||||
pending?.latitude === item.latitude && pending?.longitude === item.longitude;
|
||||
return (
|
||||
<li key={`${item.id}-${item.latitude}-${item.longitude}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPending(placeToPicked(item))}
|
||||
<p
|
||||
className="label-md text-muted"
|
||||
style={{
|
||||
width: '100%',
|
||||
textAlign: 'left',
|
||||
padding: '12px 16px',
|
||||
border: 0,
|
||||
borderBottom: '1px solid rgba(0,0,0,0.06)',
|
||||
background: active ? 'rgba(166, 29, 36, 0.06)' : '#fff',
|
||||
cursor: 'pointer',
|
||||
margin: 0,
|
||||
padding: '8px 14px',
|
||||
borderBottom: '1px solid rgba(0,0,0,0.04)',
|
||||
flexShrink: 0,
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<div style={{ fontWeight: 600, fontSize: 15 }}>{item.title}</div>
|
||||
<div className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
{item.address}
|
||||
</div>
|
||||
<div className="label-md text-muted" style={{ marginTop: 2, fontSize: 12 }}>
|
||||
{item.latitude.toFixed(6)}, {item.longitude.toFixed(6)}
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||
{hint}
|
||||
{pending ? '已选定位置,请点右上角「确认」' : '在地图上点选或搜索地点,选中后点右上角「确认」'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, position: 'relative', background: '#f5f5f5' }}>
|
||||
{loading ? (
|
||||
<p className="label-md text-muted" style={{ padding: 24, textAlign: 'center' }}>
|
||||
正在加载地图…
|
||||
</p>
|
||||
) : error ? (
|
||||
<div style={{ padding: 24 }}>
|
||||
<p className="label-md" style={{ color: 'var(--color-heritage-red, #a61d24)' }}>
|
||||
{error}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 12 }}>
|
||||
请确认系统设置中已配置腾讯位置服务 Key,并白名单 apis.map.qq.com。
|
||||
</p>
|
||||
</div>
|
||||
) : src ? (
|
||||
<>
|
||||
{!iframeReady ? (
|
||||
<p
|
||||
className="label-md text-muted"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
margin: 0,
|
||||
zIndex: 1,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
地图加载中…
|
||||
</p>
|
||||
) : null}
|
||||
<iframe
|
||||
title="地图选点"
|
||||
src={src}
|
||||
allow="geolocation *"
|
||||
onLoad={() => setIframeReady(true)}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: 0,
|
||||
display: 'block',
|
||||
background: '#fff',
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -113,6 +113,10 @@ export function clearAuth(options?: { keepProfile?: boolean }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
export function isLoggedIn() {
|
||||
return !!localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { apiBase, getToken } from './api';
|
||||
|
||||
const CLIENT_APP = 'PARTNER_H5';
|
||||
|
||||
export type ClientErrorLevel = 'fatal' | 'error' | 'warn';
|
||||
export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
| 'other';
|
||||
|
||||
export type ClientErrorPayload = {
|
||||
level: ClientErrorLevel;
|
||||
category: ClientErrorCategory;
|
||||
message: string;
|
||||
stack?: string;
|
||||
pagePath?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function currentPagePath(): string | undefined {
|
||||
try {
|
||||
return typeof window !== 'undefined' ? window.location.pathname : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 上报客户端错误(失败静默,避免递归) */
|
||||
export function reportClientError(payload: ClientErrorPayload): void {
|
||||
const body = {
|
||||
level: payload.level,
|
||||
category: payload.category,
|
||||
message: String(payload.message || 'unknown').slice(0, 1000),
|
||||
stack: payload.stack ? String(payload.stack).slice(0, 4000) : undefined,
|
||||
pagePath: (payload.pagePath || currentPagePath() || '').slice(0, 128) || undefined,
|
||||
clientApp: CLIENT_APP,
|
||||
extra: payload.extra,
|
||||
};
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': CLIENT_APP,
|
||||
};
|
||||
const token = getToken();
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
void fetch(`${apiBase}/common/client-errors`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
/** 安装 H5 全局未捕获错误钩子(幂等) */
|
||||
export function installClientErrorReporting(): void {
|
||||
if (installed || typeof window === 'undefined') return;
|
||||
installed = true;
|
||||
|
||||
window.addEventListener('error', (ev) => {
|
||||
reportClientError({
|
||||
level: 'fatal',
|
||||
category: 'js_error',
|
||||
message: ev.message || 'window.error',
|
||||
stack: ev.error instanceof Error ? ev.error.stack : undefined,
|
||||
extra: { filename: ev.filename, lineno: ev.lineno, colno: ev.colno },
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (ev) => {
|
||||
const reason = ev.reason;
|
||||
reportClientError({
|
||||
level: 'error',
|
||||
category: 'unhandled_rejection',
|
||||
message:
|
||||
reason instanceof Error
|
||||
? reason.message
|
||||
: typeof reason === 'string'
|
||||
? reason
|
||||
: 'unhandledrejection',
|
||||
stack: reason instanceof Error ? reason.stack : undefined,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PartnerProxyDeliveryMode } from '@dukang/shared-types';
|
||||
|
||||
const PROXY_ORDER_DRAFT_KEY = 'partner_proxy_order_draft_v2';
|
||||
|
||||
export type ProxyOrderDraft = {
|
||||
phone: string;
|
||||
receiverName: string;
|
||||
regionCodes: string[];
|
||||
addressDetail: string;
|
||||
productId: string;
|
||||
quantity: number;
|
||||
promoCodeId: string;
|
||||
deliveryMode: PartnerProxyDeliveryMode;
|
||||
autoReceive: boolean;
|
||||
};
|
||||
|
||||
export function saveProxyOrderDraft(draft: ProxyOrderDraft) {
|
||||
try {
|
||||
sessionStorage.setItem(PROXY_ORDER_DRAFT_KEY, JSON.stringify(draft));
|
||||
} catch {
|
||||
/* ignore quota / private mode */
|
||||
}
|
||||
}
|
||||
|
||||
export function loadProxyOrderDraft(): ProxyOrderDraft | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(PROXY_ORDER_DRAFT_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as Partial<ProxyOrderDraft>;
|
||||
if (!parsed || typeof parsed !== 'object') return null;
|
||||
return {
|
||||
phone: typeof parsed.phone === 'string' ? parsed.phone : '',
|
||||
receiverName: typeof parsed.receiverName === 'string' ? parsed.receiverName : '',
|
||||
regionCodes: Array.isArray(parsed.regionCodes)
|
||||
? parsed.regionCodes.filter((c): c is string => typeof c === 'string')
|
||||
: [],
|
||||
addressDetail: typeof parsed.addressDetail === 'string' ? parsed.addressDetail : '',
|
||||
productId: typeof parsed.productId === 'string' ? parsed.productId : '',
|
||||
quantity: typeof parsed.quantity === 'number' && parsed.quantity >= 1 ? parsed.quantity : 2,
|
||||
promoCodeId: typeof parsed.promoCodeId === 'string' ? parsed.promoCodeId : '',
|
||||
deliveryMode: parsed.deliveryMode === 'ON_SITE_PICKUP' ? 'ON_SITE_PICKUP' : 'ADDRESS',
|
||||
autoReceive: parsed.autoReceive === true,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearProxyOrderDraft() {
|
||||
try {
|
||||
sessionStorage.removeItem(PROXY_ORDER_DRAFT_KEY);
|
||||
sessionStorage.removeItem('partner_proxy_order_draft_v1');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
PENDING_PAY: '待付款',
|
||||
PENDING_SHIP: '待发货',
|
||||
OUT_WAREHOUSE: '已出库',
|
||||
SHIPPING: '配送中',
|
||||
PENDING_RECEIVE: '待收货',
|
||||
COMPLETED: '已完成',
|
||||
CANCELLED: '已取消',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
const PAY_LABELS: Record<string, string> = {
|
||||
UNPAID: '未支付',
|
||||
PAYING: '支付中',
|
||||
PAID: '已付款',
|
||||
REFUNDING: '退款中',
|
||||
REFUNDED: '已退款',
|
||||
};
|
||||
|
||||
export function proxyOrderStatusLabel(status?: string | null) {
|
||||
if (!status) return '—';
|
||||
return STATUS_LABELS[status] || status;
|
||||
}
|
||||
|
||||
export function proxyOrderPayLabel(payStatus?: string | null) {
|
||||
if (!payStatus) return '—';
|
||||
return PAY_LABELS[payStatus] || payStatus;
|
||||
}
|
||||
|
||||
export function proxyOrderStatusColor(status?: string | null) {
|
||||
if (status === 'PENDING_PAY') return 'var(--color-warning, #d48806)';
|
||||
if (status === 'COMPLETED') return 'var(--color-success-green)';
|
||||
if (status === 'CANCELLED' || status === 'REFUNDED') return 'var(--color-text-muted, #999)';
|
||||
return 'var(--color-primary, #8b1e1e)';
|
||||
}
|
||||
@@ -24,3 +24,78 @@ export function placeToPicked(item: LbsPlaceItem): TencentPickedLocation {
|
||||
cityname: item.city || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
type LocPickerMessage = {
|
||||
module?: string;
|
||||
latlng?: { lat?: number; lng?: number };
|
||||
poiaddress?: string;
|
||||
poiname?: string;
|
||||
cityname?: string;
|
||||
};
|
||||
|
||||
const REFERER = 'dukang';
|
||||
|
||||
function coerceMessageData(data: unknown): LocPickerMessage | null {
|
||||
if (data == null) return null;
|
||||
if (typeof data === 'string') {
|
||||
const trimmed = data.trim();
|
||||
if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) return null;
|
||||
try {
|
||||
return JSON.parse(trimmed) as LocPickerMessage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (typeof data === 'object') return data as LocPickerMessage;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 腾讯地图选点组件(iframe) */
|
||||
export function buildTencentLocPickerUrl(
|
||||
key: string,
|
||||
options?: { latitude?: number; longitude?: number },
|
||||
): string {
|
||||
const params = new URLSearchParams({
|
||||
search: '1',
|
||||
type: '1',
|
||||
key,
|
||||
referer: REFERER,
|
||||
policy: '1',
|
||||
total: '20',
|
||||
radius: '2000',
|
||||
mapdraggable: '1',
|
||||
});
|
||||
const lat = options?.latitude;
|
||||
const lng = options?.longitude;
|
||||
if (
|
||||
lat != null &&
|
||||
lng != null &&
|
||||
Number.isFinite(lat) &&
|
||||
Number.isFinite(lng) &&
|
||||
!(lat === 0 && lng === 0)
|
||||
) {
|
||||
params.set('coord', `${lat},${lng}`);
|
||||
params.set('coordtype', '5');
|
||||
}
|
||||
return `https://apis.map.qq.com/tools/locpicker?${params.toString()}`;
|
||||
}
|
||||
|
||||
export function parseTencentLocPickerMessage(data: unknown): TencentPickedLocation | null {
|
||||
const loc = coerceMessageData(data);
|
||||
if (!loc || loc.module !== 'locationPicker') return null;
|
||||
const lat = Number(loc.latlng?.lat);
|
||||
const lng = Number(loc.latlng?.lng);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
||||
|
||||
let name = loc.poiname?.trim() || undefined;
|
||||
const address = loc.poiaddress?.trim() || undefined;
|
||||
if (name === '我的位置' && address) name = address;
|
||||
|
||||
return {
|
||||
latitude: lat,
|
||||
longitude: lng,
|
||||
address,
|
||||
name,
|
||||
cityname: loc.cityname?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,9 +5,12 @@ import { getRouterBasename } from '@dukang/weixin-sdk';
|
||||
import App from './App';
|
||||
import { PartnerSessionProvider } from './contexts/PartnerSessionContext';
|
||||
import { PartnerToastProvider } from './contexts/PartnerToastContext';
|
||||
import { installClientErrorReporting } from './lib/client-error';
|
||||
import './styles.css';
|
||||
import './styles/legal.css';
|
||||
|
||||
installClientErrorReporting();
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter basename={getRouterBasename()}>
|
||||
|
||||
@@ -219,6 +219,15 @@ export default function CenterPage({ variant = 'primary', roleLabel }: CenterPag
|
||||
<span className="material-symbols-outlined text-muted">chevron_right</span>
|
||||
</div>
|
||||
</Link>
|
||||
<Link to="/center/proxy-orders" className="partner-menu-item">
|
||||
<div className="partner-menu-item-left">
|
||||
<div className="partner-menu-icon">
|
||||
<span className="material-symbols-outlined">receipt_long</span>
|
||||
</div>
|
||||
<span className="body-md" style={{ fontSize: 16 }}>代下单列表</span>
|
||||
</div>
|
||||
<span className="material-symbols-outlined text-muted">chevron_right</span>
|
||||
</Link>
|
||||
<Link to="/stores?audit=pending" className="partner-menu-item">
|
||||
<div className="partner-menu-item-left">
|
||||
<div className="partner-menu-icon">
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { WECHAT_INAPP_REQUIRED_MSG } from '@dukang/weixin-sdk';
|
||||
import {
|
||||
getLastPhone,
|
||||
getPartnerProfile,
|
||||
hasPartnerWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type PartnerSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { partnerHomePath } from '../lib/partnerAccess';
|
||||
import {
|
||||
bindPartnerWechatAfterSmsLogin,
|
||||
fetchClientConfig,
|
||||
loginPartnerWithWechat,
|
||||
} from '../lib/wechat-auth';
|
||||
import { toastError } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
const REMEMBER_PHONE_KEY = 'partner_remember_phone';
|
||||
const REMEMBER_FLAG_KEY = 'partner_remember_account';
|
||||
@@ -39,6 +49,11 @@ function AgreementCheckbox({
|
||||
);
|
||||
}
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function loadRememberedPhone(): { phone: string; remember: boolean } {
|
||||
try {
|
||||
const remember = localStorage.getItem(REMEMBER_FLAG_KEY) === '1';
|
||||
@@ -60,9 +75,19 @@ function formatPartnerError(e: unknown): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession, refresh, account } = usePartnerSession();
|
||||
const [params] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getPartnerProfile();
|
||||
const remembered = loadRememberedPhone();
|
||||
const [phone, setPhone] = useState(remembered.phone || getLastPhone());
|
||||
@@ -70,13 +95,27 @@ export default function LoginPage() {
|
||||
const [rememberAccount, setRememberAccount] = useState(remembered.remember);
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
const quickName = savedProfile?.name ?? '城市合伙人';
|
||||
const quickCompany = savedProfile?.companyName ?? '';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先勾选并同意用户协议');
|
||||
const tip = '请先勾选并同意用户协议';
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
agreementRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
return false;
|
||||
}
|
||||
@@ -140,6 +179,11 @@ export default function LoginPage() {
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
persistRememberAccount(phone);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindPartnerWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
await finishLoginNavigate();
|
||||
} catch (e) {
|
||||
setMsg(formatPartnerError(e));
|
||||
@@ -148,6 +192,119 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg(WECHAT_INAPP_REQUIRED_MSG);
|
||||
toastError(WECHAT_INAPP_REQUIRED_MSG);
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
// 直接发起 OAuth;未绑定账号由后端返回「请先短信登录」提示
|
||||
const session = await loginPartnerWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
await finishLoginNavigate();
|
||||
return;
|
||||
}
|
||||
if (session === null) {
|
||||
const tip = '微信授权暂未开启,请使用验证码登录';
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
}
|
||||
// session === undefined:已跳转微信授权页
|
||||
} catch (e) {
|
||||
const tip = formatWechatError(e);
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick =
|
||||
wxAuthorize &&
|
||||
isWechatEnv() &&
|
||||
hasPartnerWxSession() &&
|
||||
!!savedProfile &&
|
||||
savedProfile.hasWechat === true;
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page partner-auth-page--quick">
|
||||
<header className="partner-auth-brand">
|
||||
<div className="partner-quick-avatar" style={{ width: 120, height: 120, margin: '0 auto 16px' }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 48 }}>wine_bar</span>
|
||||
</div>
|
||||
<h1 className="partner-auth-title" style={{ fontSize: 20 }}>杜康好客</h1>
|
||||
<p className="partner-auth-subtitle" style={{ fontSize: 12, letterSpacing: '0.2em', textTransform: 'uppercase' }}>城市合伙人端</p>
|
||||
</header>
|
||||
|
||||
<section className="partner-glass-card">
|
||||
<div className="partner-quick-badge">已识别账号</div>
|
||||
<div className="partner-quick-avatar">
|
||||
<span className="material-symbols-outlined">person</span>
|
||||
</div>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<h2 className="headline-md">
|
||||
{quickName}
|
||||
{quickCompany ? (
|
||||
<span className="text-muted body-md" style={{ fontWeight: 400 }}> ({quickCompany})</span>
|
||||
) : null}
|
||||
</h2>
|
||||
<p className="text-muted body-md" style={{ letterSpacing: '0.1em', marginTop: 4 }}>
|
||||
{quickPhone ? maskPhone(quickPhone) : '暂无已保存账号'}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<nav style={{ width: '100%', maxWidth: 384, marginTop: 16 }}>
|
||||
{msg && <p className="partner-auth-msg" style={{ color: 'var(--color-error, #d33)', fontSize: 13, textAlign: 'center', marginBottom: 12 }}>{msg}</p>}
|
||||
<AgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
inputRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center', marginTop: 12, marginBottom: 12 }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="partner-btn-primary" style={{ display: 'block', textAlign: 'center', textDecoration: 'none', marginTop: 12 }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<Link to="/login" className="partner-btn-ghost" style={{ display: 'block', marginTop: 12 }}>切换账号</Link>
|
||||
</nav>
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
<span className="label-md" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
|
||||
{canWechatQuick ? '微信验证 · 7 天内免登录' : 'Secured by Dukang Heritage'}
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="partner-auth-page">
|
||||
<div className="partner-auth-brand">
|
||||
@@ -214,12 +371,34 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="partner-auth-divider"><span>其他登录方式</span></div>
|
||||
<button type="button" className="partner-btn-wechat" onClick={() => void wechatLogin()} disabled={wxLoading}>
|
||||
<svg viewBox="0 0 24 24" fill="#07C160" aria-hidden>
|
||||
<path d="M8.25 4.5C4.52 4.5 1.5 7.04 1.5 10.17c0 1.78.98 3.37 2.5 4.48l-.63 1.88 2.19-1.09c.84.24 1.74.38 2.69.38.25 0 .5 0 .75-.03-.16-.53-.25-1.09-.25-1.66 0-3.13 3.02-5.67 6.75-5.67.57 0 1.13.06 1.66.17C15.17 6.13 12 4.5 8.25 4.5zm10.5 6.33c-3.11 0-5.62 2.12-5.62 4.73 0 2.61 2.51 4.73 5.62 4.73.79 0 1.54-.14 2.24-.38l1.83.91-.53-1.57c1.27-.92 2.08-2.25 2.08-3.73 0-2.61-2.51-4.73-5.62-4.73z" />
|
||||
</svg>
|
||||
<span>{wxLoading ? '跳转授权中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
{msg && (
|
||||
<p className="partner-auth-msg" style={{ color: 'var(--color-error, #d33)', fontSize: 13, textAlign: 'center' }}>
|
||||
{msg}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="partner-auth-msg" style={{ textAlign: 'center' }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
请在微信内打开;首次请先用验证码登录,成功后将自动关联微信,之后可一键登录
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{hasPartnerWxSession() && savedProfile?.hasWechat && (
|
||||
<Link to="/login?quick=1" className="partner-link">微信快捷登录</Link>
|
||||
)}
|
||||
|
||||
<footer className="partner-auth-footer">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className="material-symbols-outlined">verified_user</span>
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import QRCode from 'qrcode';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
||||
import type { PartnerProxyOrderListItem, ProxyOrderPayResponse, ProxyPayMethod } from '@dukang/shared-types';
|
||||
import { getToken, request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderPayLabel,
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { fetchPartnerProfile, partnerHasWechatBinding } from '../lib/wechat-auth';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function fmtTime(value: string | undefined) {
|
||||
if (!value) return '—';
|
||||
const d = new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function deliveryLabel(order: PartnerProxyOrderListItem) {
|
||||
const t = String(order.deliveryType || '').toUpperCase();
|
||||
if (t === 'ON_SITE_PICKUP') return '现场提货';
|
||||
if (t === 'CROSS_CITY') return '跨城配送';
|
||||
if (t === 'LOCAL') return '同城配送';
|
||||
return '代下单';
|
||||
}
|
||||
|
||||
type TrackNode = {
|
||||
time?: string;
|
||||
status?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
type TrackResult = {
|
||||
nodes?: TrackNode[];
|
||||
trackingNo?: string | null;
|
||||
provider?: string | null;
|
||||
manualQueryUrl?: string | null;
|
||||
};
|
||||
|
||||
export default function ProxyOrderDetailPage() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [order, setOrder] = useState<PartnerProxyOrderListItem | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [track, setTrack] = useState<TrackResult | null>(null);
|
||||
const [trackError, setTrackError] = useState('');
|
||||
const [paying, setPaying] = useState(false);
|
||||
const [payMsg, setPayMsg] = useState('');
|
||||
const [payMethod, setPayMethod] = useState<ProxyPayMethod>('NATIVE');
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = '代下单详情';
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
void request<PartnerProxyOrderListItem>('PARTNER_H5', `/partner/proxy-orders/${id}`)
|
||||
.then(setOrder)
|
||||
.catch((e) => setError(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !order) return;
|
||||
const dt = String(order.deliveryType || '').toUpperCase();
|
||||
if (dt === 'ON_SITE_PICKUP' || order.payStatus !== 'PAID') {
|
||||
setTrack(null);
|
||||
return;
|
||||
}
|
||||
void request<TrackResult>('PARTNER_H5', `/partner/proxy-orders/${id}/track`, { silent: true })
|
||||
.then(setTrack)
|
||||
.catch((e) => setTrackError(e instanceof Error ? e.message : '物流暂不可用'));
|
||||
}, [id, order]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!codeUrl) {
|
||||
setQrDataUrl(null);
|
||||
return;
|
||||
}
|
||||
void QRCode.toDataURL(codeUrl, { width: 220, margin: 1 })
|
||||
.then(setQrDataUrl)
|
||||
.catch(() => setQrDataUrl(null));
|
||||
}, [codeUrl]);
|
||||
|
||||
const unpaid = order?.payStatus === 'UNPAID' || order?.status === 'PENDING_PAY';
|
||||
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<{ payStatus: string; orderNo: string }>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay-status`,
|
||||
{ silent: true },
|
||||
)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
toastSuccess(`支付成功:${st.orderNo}`);
|
||||
void request<PartnerProxyOrderListItem>('PARTNER_H5', `/partner/proxy-orders/${orderId}`)
|
||||
.then(setOrder)
|
||||
.catch(() => undefined);
|
||||
setCodeUrl(null);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function startPay(method: ProxyPayMethod) {
|
||||
if (!id) return;
|
||||
setPaying(true);
|
||||
setPayMsg('');
|
||||
setPayMethod(method);
|
||||
try {
|
||||
if (method === 'JSAPI') {
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开合伙人端以使用微信代付');
|
||||
}
|
||||
const profile = await fetchPartnerProfile();
|
||||
if (!partnerHasWechatBinding(profile)) {
|
||||
throw new Error('请先绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const pay = await request<ProxyOrderPayResponse>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${id}/pay`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: method }),
|
||||
silent: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (pay.mode === 'mock') {
|
||||
toastSuccess('支付成功');
|
||||
const refreshed = await request<PartnerProxyOrderListItem>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${id}`,
|
||||
);
|
||||
setOrder(refreshed);
|
||||
setCodeUrl(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'native' && pay.codeUrl) {
|
||||
setCodeUrl(pay.codeUrl);
|
||||
startPoll(id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'jsapi' && pay.prepay) {
|
||||
setCodeUrl(null);
|
||||
await invokeWechatPay(pay.prepay, {
|
||||
apiBase: '/api/v1',
|
||||
clientApp: 'PARTNER_H5',
|
||||
getAccessToken: getToken,
|
||||
platform: 'wechat-h5',
|
||||
});
|
||||
startPoll(id);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('支付发起失败');
|
||||
} catch (e) {
|
||||
setPayMsg(e instanceof Error ? e.message : '支付失败');
|
||||
toastError(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const autoPayStartedRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!id || !unpaid || autoPayStartedRef.current) return;
|
||||
autoPayStartedRef.current = true;
|
||||
void startPay('NATIVE');
|
||||
// 仅首次进入未支付详情时自动拉收款码
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id, unpaid]);
|
||||
|
||||
const img = order?.imageResource?.url || '';
|
||||
const isOnSite = String(order?.deliveryType || '').toUpperCase() === 'ON_SITE_PICKUP';
|
||||
|
||||
return (
|
||||
<div className="page-no-tab partner-orders-page">
|
||||
<PageHeader title="代下单详情" onBack={() => navigate('/center/proxy-orders')} />
|
||||
|
||||
{error && (
|
||||
<p className="partner-form-error" role="alert" style={{ margin: '16px 20px' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!order && !error && <p className="label-md text-muted" style={{ margin: 20 }}>加载中…</p>}
|
||||
|
||||
{order && (
|
||||
<div style={{ padding: '0 16px 32px' }}>
|
||||
<div className="partner-order-card" style={{ pointerEvents: 'none' }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {order.orderNo}</span>
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(order.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(order.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
<div
|
||||
className="partner-order-product-img"
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
overflow: 'hidden',
|
||||
background: img ? `center/cover no-repeat url(${img})` : undefined,
|
||||
}}
|
||||
>
|
||||
{!img && <span className="material-symbols-outlined text-muted">liquor</span>}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<h3 className="headline-md">{order.productName || '杜康好酒'}</h3>
|
||||
{order.productSpec && (
|
||||
<p className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
{order.productSpec}
|
||||
</p>
|
||||
)}
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
×{order.quantity} · ¥{fmtMoney(Number(order.payAmount || 0))}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
权益 ¥{fmtMoney(Number(order.benefitAmount || 0))}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>客户信息</h3>
|
||||
<p className="body-md">姓名:{order.receiverName || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>手机:{order.receiverPhone || '—'}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
地址:{order.receiverAddress || (isOnSite ? '现场提货' : '—')}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>订单信息</h3>
|
||||
<p className="body-md">配送方式:{deliveryLabel(order)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>下单时间:{fmtTime(order.createdAt)}</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
支付状态:{proxyOrderPayLabel(order.payStatus)}
|
||||
</p>
|
||||
<p className="body-md" style={{ marginTop: 8 }}>
|
||||
订单状态:{proxyOrderStatusLabel(order.status)}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{unpaid ? (
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>继续支付</h3>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => void startPay('NATIVE')}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => void startPay('JSAPI')}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{payMethod === 'NATIVE' ? (
|
||||
<div style={{ textAlign: 'center', marginTop: 16 }}>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt="收款码" width={220} height={220} style={{ margin: '0 auto' }} />
|
||||
) : (
|
||||
<p className="label-md text-muted">{paying ? '生成收款码中…' : '暂无收款码'}</p>
|
||||
)}
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
请使用微信扫码支付,支付成功后自动更新
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block"
|
||||
style={{ marginTop: 12 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay('NATIVE')}
|
||||
>
|
||||
{paying ? '生成中…' : '重新生成收款码'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<p className="label-md text-muted">将调起微信支付,由合伙人微信完成代付</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 12 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay('JSAPI')}
|
||||
>
|
||||
{paying ? '支付中…' : '调起微信代付'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payMsg ? (
|
||||
<p className="partner-form-error" role="alert" style={{ marginTop: 12 }}>
|
||||
{payMsg}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{!isOnSite && order.payStatus === 'PAID' ? (
|
||||
<section className="partner-form-card" style={{ marginTop: 12 }}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 12 }}>物流信息</h3>
|
||||
{trackError ? (
|
||||
<p className="label-md text-muted">{trackError}</p>
|
||||
) : !track ? (
|
||||
<p className="label-md text-muted">加载物流…</p>
|
||||
) : (
|
||||
<>
|
||||
{track.trackingNo ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
运单号:{track.trackingNo}
|
||||
{track.provider ? `(${track.provider})` : ''}
|
||||
</p>
|
||||
) : null}
|
||||
{track.manualQueryUrl ? (
|
||||
<p className="body-md" style={{ marginBottom: 8 }}>
|
||||
<a href={track.manualQueryUrl} target="_blank" rel="noreferrer">
|
||||
查看物流官网
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
{(track.nodes ?? []).length === 0 ? (
|
||||
<p className="label-md text-muted">暂无物流轨迹(待总部发货后更新)</p>
|
||||
) : (
|
||||
<ul style={{ paddingLeft: 18, margin: 0 }}>
|
||||
{(track.nodes ?? []).map((n, i) => (
|
||||
<li key={`${n.time}-${i}`} className="body-md" style={{ marginBottom: 8 }}>
|
||||
<div className="label-md text-muted">{fmtTime(n.time)}</div>
|
||||
<div>{n.description || n.status || '—'}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import type { PartnerProxyOrderListItem, PartnerProxyOrderListResponse } from '@dukang/shared-types';
|
||||
import { isLoggedIn, request } from '../lib/api';
|
||||
import {
|
||||
proxyOrderStatusColor,
|
||||
proxyOrderStatusLabel,
|
||||
} from '../lib/proxyOrderStatus';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function fmtTime(value: string | undefined) {
|
||||
if (!value) return '—';
|
||||
const d = new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function deliveryLabel(item: PartnerProxyOrderListItem) {
|
||||
const t = String(item.deliveryType || '').toUpperCase();
|
||||
if (t === 'ON_SITE_PICKUP') return '现场提货';
|
||||
if (t === 'CROSS_CITY') return '跨城配送';
|
||||
if (t === 'LOCAL') return '同城配送';
|
||||
return '线下代下单';
|
||||
}
|
||||
|
||||
function coverUrl(item: PartnerProxyOrderListItem) {
|
||||
return item.imageResource?.url || '';
|
||||
}
|
||||
|
||||
export default function ProxyOrderListPage() {
|
||||
const navigate = useNavigate();
|
||||
const [list, setList] = useState<PartnerProxyOrderListItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [q, setQ] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const loadList = useCallback(() => {
|
||||
if (!isLoggedIn()) {
|
||||
navigate('/login');
|
||||
return Promise.resolve();
|
||||
}
|
||||
setLoading(true);
|
||||
const params = new URLSearchParams({ page: '1', pageSize: '50' });
|
||||
if (q.trim()) params.set('keyword', q.trim());
|
||||
return request<PartnerProxyOrderListResponse>('PARTNER_H5', `/partner/proxy-orders?${params}`)
|
||||
.then((res) => {
|
||||
setList(Array.isArray(res.list) ? res.list : []);
|
||||
setTotal(Number(res.total) || 0);
|
||||
})
|
||||
.catch(() => {
|
||||
setList([]);
|
||||
setTotal(0);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [navigate, q]);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = '代下单列表';
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadList();
|
||||
}, [loadList]);
|
||||
|
||||
function submitSearch(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setQ(keyword.trim());
|
||||
}
|
||||
|
||||
return (
|
||||
<PullToRefresh onRefresh={loadList} className="page-no-tab partner-orders-page">
|
||||
<PageHeader title="代下单列表" onBack={() => navigate('/center')} />
|
||||
|
||||
<div style={{ padding: '0 20px 12px' }}>
|
||||
<form className="partner-search" onSubmit={submitSearch}>
|
||||
<span className="material-symbols-outlined">search</span>
|
||||
<input
|
||||
placeholder="订单号 / 手机号 / 姓名 / 商品"
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
/>
|
||||
</form>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
{loading ? '加载中…' : `共 ${total} 笔代下单`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '0 16px 24px' }}>
|
||||
{!loading && list.length === 0 && <div className="empty">暂无代下单记录</div>}
|
||||
|
||||
{list.map((o) => {
|
||||
const orderId = String(o.id);
|
||||
const img = coverUrl(o);
|
||||
return (
|
||||
<Link key={orderId} to={`/center/proxy-orders/${orderId}`} className="partner-order-card" style={{ marginBottom: 12 }}>
|
||||
<div className="partner-order-card-top">
|
||||
<span className="label-md text-muted">NO. {o.orderNo}</span>
|
||||
<span
|
||||
className="label-md"
|
||||
style={{ color: proxyOrderStatusColor(o.status), fontWeight: 600 }}
|
||||
>
|
||||
{proxyOrderStatusLabel(o.status)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="partner-order-product">
|
||||
<div
|
||||
className="partner-order-product-img"
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
overflow: 'hidden',
|
||||
background: img ? `center/cover no-repeat url(${img})` : undefined,
|
||||
}}
|
||||
>
|
||||
{!img && <span className="material-symbols-outlined text-muted">liquor</span>}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<h3 className="headline-md line-2-clamp">{o.productName || '杜康好酒'}</h3>
|
||||
<p className="text-variant body-md" style={{ marginTop: 4 }}>
|
||||
×{o.quantity} · ¥{fmtMoney(Number(o.payAmount || 0))}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
{deliveryLabel(o)} · {fmtTime(o.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="partner-order-address">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>person</span>
|
||||
<p className="line-2-clamp">
|
||||
{o.receiverName || '客户'}
|
||||
{o.receiverPhone ? ` · ${o.receiverPhone}` : ''}
|
||||
{o.receiverAddress ? ` · ${o.receiverAddress}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
@@ -1,48 +1,112 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import QRCode from 'qrcode';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { invokeWechatPay } from '@dukang/weixin-sdk';
|
||||
import ChinaRegionPicker from '../components/ChinaRegionPicker';
|
||||
import { request } from '../lib/api';
|
||||
import { getToken, request } from '../lib/api';
|
||||
import { formatRegionLabel, parseRegionCodes } from '../lib/china-region';
|
||||
import {
|
||||
clearProxyOrderDraft,
|
||||
loadProxyOrderDraft,
|
||||
saveProxyOrderDraft,
|
||||
type ProxyOrderDraft,
|
||||
} from '../lib/proxyOrderDraft';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { fetchPartnerProfile, partnerHasWechatBinding } from '../lib/wechat-auth';
|
||||
import type {
|
||||
PartnerProxyDeliveryMode,
|
||||
PartnerProxyOrderCreateRequest,
|
||||
PartnerProxyOrderOptions,
|
||||
PartnerProxyOrderPreviewResult,
|
||||
ProxyOrderCreateResponse,
|
||||
ProxyOrderPayResponse,
|
||||
ProxyPayMethod,
|
||||
} from '@dukang/shared-types';
|
||||
|
||||
function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function initialDraft(): ProxyOrderDraft {
|
||||
return (
|
||||
loadProxyOrderDraft() ?? {
|
||||
phone: '',
|
||||
receiverName: '',
|
||||
regionCodes: [],
|
||||
addressDetail: '',
|
||||
productId: '',
|
||||
quantity: 2,
|
||||
promoCodeId: '',
|
||||
deliveryMode: 'ADDRESS',
|
||||
autoReceive: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export default function ProxyOrderPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const draft0 = useMemo(() => initialDraft(), []);
|
||||
const [options, setOptions] = useState<PartnerProxyOrderOptions | null>(null);
|
||||
const [loadingOptions, setLoadingOptions] = useState(true);
|
||||
const [phone, setPhone] = useState('');
|
||||
const [customerSmsCode, setCustomerSmsCode] = useState('');
|
||||
const [partnerSmsCode, setPartnerSmsCode] = useState('');
|
||||
const [receiverName, setReceiverName] = useState('');
|
||||
const [regionCodes, setRegionCodes] = useState<string[]>([]);
|
||||
const [addressDetail, setAddressDetail] = useState('');
|
||||
const [productId, setProductId] = useState('');
|
||||
const [quantity, setQuantity] = useState(2);
|
||||
const [promoCodeId, setPromoCodeId] = useState('');
|
||||
const [deliveryMode, setDeliveryMode] = useState<PartnerProxyDeliveryMode>('ADDRESS');
|
||||
const [autoReceive, setAutoReceive] = useState(false);
|
||||
const [confirmStep, setConfirmStep] = useState(false);
|
||||
const [phone, setPhone] = useState(draft0.phone);
|
||||
const [receiverName, setReceiverName] = useState(draft0.receiverName);
|
||||
const [regionCodes, setRegionCodes] = useState<string[]>(draft0.regionCodes);
|
||||
const [addressDetail, setAddressDetail] = useState(draft0.addressDetail);
|
||||
const [productId, setProductId] = useState(draft0.productId);
|
||||
const [quantity, setQuantity] = useState(draft0.quantity);
|
||||
const [promoCodeId, setPromoCodeId] = useState(draft0.promoCodeId);
|
||||
const [deliveryMode, setDeliveryMode] = useState<PartnerProxyDeliveryMode>(draft0.deliveryMode);
|
||||
const [autoReceive, setAutoReceive] = useState(draft0.autoReceive);
|
||||
const [preview, setPreview] = useState<PartnerProxyOrderPreviewResult | null>(null);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [customerCooldown, setCustomerCooldown] = useState(0);
|
||||
const [partnerCooldown, setPartnerCooldown] = useState(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [step, setStep] = useState<'form' | 'pay'>('form');
|
||||
const [created, setCreated] = useState<ProxyOrderCreateResponse | null>(null);
|
||||
const [payMethod, setPayMethod] = useState<ProxyPayMethod>('NATIVE');
|
||||
const [codeUrl, setCodeUrl] = useState<string | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
const [paying, setPaying] = useState(false);
|
||||
const pollRef = useRef<number | null>(null);
|
||||
|
||||
const region = useMemo(() => parseRegionCodes(regionCodes), [regionCodes]);
|
||||
const regionLabel = region ? formatRegionLabel(region) : '';
|
||||
|
||||
function stopPoll() {
|
||||
if (pollRef.current != null) {
|
||||
window.clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => () => stopPoll(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!codeUrl) {
|
||||
setQrDataUrl(null);
|
||||
return;
|
||||
}
|
||||
void QRCode.toDataURL(codeUrl, { width: 220, margin: 1 }).then(setQrDataUrl).catch(() => setQrDataUrl(null));
|
||||
}, [codeUrl]);
|
||||
|
||||
function persistDraft(overrides?: Partial<ProxyOrderDraft>) {
|
||||
saveProxyOrderDraft({
|
||||
phone,
|
||||
receiverName,
|
||||
regionCodes,
|
||||
addressDetail,
|
||||
productId,
|
||||
quantity,
|
||||
promoCodeId,
|
||||
deliveryMode,
|
||||
autoReceive,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
request<PartnerProxyOrderOptions>('PARTNER_H5', '/partner/proxy-orders/options')
|
||||
.then((data) => {
|
||||
@@ -53,6 +117,7 @@ export default function ProxyOrderPage() {
|
||||
const fromQuery = searchParams.get('productId');
|
||||
if (fromQuery && data.products.some((p) => p.id === fromQuery)) {
|
||||
setProductId(fromQuery);
|
||||
persistDraft({ productId: fromQuery });
|
||||
} else if (data.products[0] && !productId) {
|
||||
setProductId(data.products[0].id);
|
||||
}
|
||||
@@ -64,9 +129,44 @@ export default function ProxyOrderPage() {
|
||||
|
||||
useEffect(() => {
|
||||
const fromQuery = searchParams.get('productId');
|
||||
if (fromQuery) setProductId(fromQuery);
|
||||
if (fromQuery) {
|
||||
setProductId(fromQuery);
|
||||
persistDraft({ productId: fromQuery });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- only sync productId from URL
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
persistDraft();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- keep draft in sync for product-picker roundtrip
|
||||
}, [
|
||||
phone,
|
||||
receiverName,
|
||||
regionCodes,
|
||||
addressDetail,
|
||||
productId,
|
||||
quantity,
|
||||
promoCodeId,
|
||||
deliveryMode,
|
||||
autoReceive,
|
||||
]);
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const allowOnline = selectedProduct ? selectedProduct.allowOnlinePurchase !== false : true;
|
||||
const allowOnSite = !!selectedProduct?.allowOnSitePickup;
|
||||
const allowCrossCity = selectedProduct ? selectedProduct.allowCrossCityDelivery !== false : true;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProduct) return;
|
||||
if (!allowOnline && allowOnSite && deliveryMode !== 'ON_SITE_PICKUP') {
|
||||
setDeliveryMode('ON_SITE_PICKUP');
|
||||
return;
|
||||
}
|
||||
if (allowOnline && !allowOnSite && deliveryMode !== 'ADDRESS') {
|
||||
setDeliveryMode('ADDRESS');
|
||||
}
|
||||
}, [selectedProduct, allowOnline, allowOnSite, deliveryMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!productId || quantity < 1) {
|
||||
setPreview(null);
|
||||
@@ -85,89 +185,108 @@ export default function ProxyOrderPage() {
|
||||
}),
|
||||
silent: true,
|
||||
})
|
||||
.then(setPreview)
|
||||
.catch(() => setPreview(null))
|
||||
.then((data) => {
|
||||
setPreview(data);
|
||||
setMsg('');
|
||||
})
|
||||
.catch((e) => {
|
||||
setPreview(null);
|
||||
setMsg(e instanceof Error ? e.message : '费用预览失败');
|
||||
})
|
||||
.finally(() => setPreviewLoading(false));
|
||||
}, 300);
|
||||
return () => clearTimeout(timer);
|
||||
}, [productId, quantity, deliveryMode, region?.city, region?.district]);
|
||||
|
||||
function startCooldown(setter: (n: number | ((s: number) => number)) => void) {
|
||||
setter(60);
|
||||
const timer = setInterval(() => {
|
||||
setter((s) => {
|
||||
if (s <= 1) {
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
}
|
||||
return s - 1;
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
async function sendCustomerSms() {
|
||||
setMsg('');
|
||||
if (!/^1\d{10}$/.test(phone.trim())) {
|
||||
setMsg('请输入有效手机号');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await request<{ maskedPhone: string }>(
|
||||
'PARTNER_H5',
|
||||
'/partner/proxy-orders/send-customer-sms',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone: phone.trim() }),
|
||||
silent: true,
|
||||
},
|
||||
);
|
||||
setMsg(`客户验证码已发送至 ${res.maskedPhone}`);
|
||||
startCooldown(setCustomerCooldown);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '发送失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function sendPartnerSms() {
|
||||
setMsg('');
|
||||
try {
|
||||
const res = await request<{ maskedPhone: string }>(
|
||||
'PARTNER_H5',
|
||||
'/partner/proxy-orders/send-partner-sms',
|
||||
{ method: 'POST', body: '{}', silent: true },
|
||||
);
|
||||
setMsg(`确认验证码已发送至合伙人手机 ${res.maskedPhone}`);
|
||||
startCooldown(setPartnerCooldown);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '发送失败');
|
||||
}
|
||||
}
|
||||
|
||||
function validateForm(): string | null {
|
||||
if (!/^1\d{10}$/.test(phone.trim())) return '请输入有效手机号';
|
||||
if (!customerSmsCode.trim()) return '请输入客户验证码';
|
||||
if (!productId) return '请选择商品';
|
||||
if (deliveryMode !== 'ADDRESS') {
|
||||
// 现场提货不需要地址与门店
|
||||
} else {
|
||||
if (deliveryMode === 'ADDRESS') {
|
||||
if (!allowOnline) return '该商品不支持线上购买';
|
||||
if (!region?.province || !region?.city || !region?.district) return '请选择省市区';
|
||||
if (!addressDetail.trim()) return '请填写详细地址';
|
||||
if (!autoReceive) return '配送到址须勾选同意自动收货';
|
||||
} else if (!allowOnSite) {
|
||||
return '该商品不支持现场提货';
|
||||
}
|
||||
if (!preview) return '请等待费用计算完成';
|
||||
if (!preview) return msg || '请等待费用计算完成';
|
||||
return null;
|
||||
}
|
||||
|
||||
async function openConfirmStep() {
|
||||
function startPoll(orderId: string) {
|
||||
stopPoll();
|
||||
pollRef.current = window.setInterval(() => {
|
||||
void request<{ payStatus: string; orderNo: string }>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay-status`,
|
||||
{ silent: true },
|
||||
)
|
||||
.then((st) => {
|
||||
if (st.payStatus === 'PAID') {
|
||||
stopPoll();
|
||||
toastSuccess(`支付成功:${st.orderNo}`);
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function startPay(orderId: string, method: ProxyPayMethod) {
|
||||
setPaying(true);
|
||||
setMsg('');
|
||||
const err = validateForm();
|
||||
if (err) {
|
||||
setMsg(err);
|
||||
try {
|
||||
if (method === 'JSAPI') {
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开合伙人端以使用微信代付');
|
||||
}
|
||||
const profile = await fetchPartnerProfile();
|
||||
if (!partnerHasWechatBinding(profile)) {
|
||||
throw new Error('请先绑定微信后再代付');
|
||||
}
|
||||
}
|
||||
|
||||
const pay = await request<ProxyOrderPayResponse>(
|
||||
'PARTNER_H5',
|
||||
`/partner/proxy-orders/${orderId}/pay`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: method }),
|
||||
silent: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (pay.mode === 'mock') {
|
||||
toastSuccess('支付成功');
|
||||
clearProxyOrderDraft();
|
||||
navigate(`/center/proxy-orders/${orderId}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
setConfirmStep(true);
|
||||
setPartnerSmsCode('');
|
||||
await sendPartnerSms();
|
||||
|
||||
if (pay.mode === 'native' && pay.codeUrl) {
|
||||
setCodeUrl(pay.codeUrl);
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pay.mode === 'jsapi' && pay.prepay) {
|
||||
await invokeWechatPay(pay.prepay, {
|
||||
apiBase: '/api/v1',
|
||||
clientApp: 'PARTNER_H5',
|
||||
getAccessToken: getToken,
|
||||
platform: 'wechat-h5',
|
||||
});
|
||||
startPoll(orderId);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error('支付发起失败');
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '支付失败');
|
||||
} finally {
|
||||
setPaying(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
@@ -177,15 +296,9 @@ export default function ProxyOrderPage() {
|
||||
setMsg(err);
|
||||
return;
|
||||
}
|
||||
if (!partnerSmsCode.trim()) {
|
||||
setMsg('请输入合伙人确认验证码');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: PartnerProxyOrderCreateRequest = {
|
||||
phone: phone.trim(),
|
||||
customerSmsCode: customerSmsCode.trim(),
|
||||
partnerSmsCode: partnerSmsCode.trim(),
|
||||
deliveryMode,
|
||||
autoReceive: deliveryMode === 'ADDRESS' ? true : undefined,
|
||||
receiverName: receiverName.trim() || undefined,
|
||||
@@ -200,13 +313,16 @@ export default function ProxyOrderPage() {
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const order = await request<{ id: string; orderNo: string }>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
const order = await request<ProxyOrderCreateResponse>('PARTNER_H5', '/partner/proxy-orders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
silent: true,
|
||||
});
|
||||
toastSuccess(`代下单成功:${order.orderNo}`);
|
||||
navigate(`/orders/${order.id}`);
|
||||
clearProxyOrderDraft();
|
||||
setCreated(order);
|
||||
setStep('pay');
|
||||
setCodeUrl(null);
|
||||
await startPay(order.id, payMethod);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '下单失败');
|
||||
} finally {
|
||||
@@ -214,7 +330,6 @@ export default function ProxyOrderPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const selectedProduct = options?.products.find((p) => p.id === productId);
|
||||
const deliveryLabel =
|
||||
preview?.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '现场提货'
|
||||
@@ -224,17 +339,94 @@ export default function ProxyOrderPage() {
|
||||
|
||||
return (
|
||||
<div className="page partner-proxy-order-page">
|
||||
<PageHeader title="代下单" onBack={() => navigate(-1)} />
|
||||
<PageHeader title={step === 'pay' ? '代下单支付' : '代下单'} onBack={() => navigate(-1)} />
|
||||
|
||||
<main className="partner-form-card" style={{ margin: '0 16px 24px' }}>
|
||||
{loadingOptions ? (
|
||||
{step === 'pay' && created ? (
|
||||
<>
|
||||
<p className="body-md">
|
||||
订单 {created.orderNo} · 应付 ¥{fmtMoney(created.payAmount)}
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
{created.deliveryType === 'ON_SITE_PICKUP'
|
||||
? '支付成功后订单即为已完成,并发放好客权益'
|
||||
: '支付成功后进入待发货,由总部履约'}
|
||||
</p>
|
||||
|
||||
<section className="partner-form-section" style={{ marginTop: 16 }}>
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('NATIVE');
|
||||
void startPay(created.id, 'NATIVE');
|
||||
}}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => {
|
||||
setPayMethod('JSAPI');
|
||||
void startPay(created.id, 'JSAPI');
|
||||
}}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{payMethod === 'NATIVE' ? (
|
||||
<div style={{ textAlign: 'center', marginTop: 16 }}>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt="收款码" width={220} height={220} style={{ margin: '0 auto' }} />
|
||||
) : (
|
||||
<p className="label-md text-muted">{paying ? '生成收款码中…' : '暂无收款码'}</p>
|
||||
)}
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
请使用微信扫码支付,支付成功后自动跳转
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-block"
|
||||
style={{ marginTop: 16 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay(created.id, 'NATIVE')}
|
||||
>
|
||||
{paying ? '生成中…' : '重新生成收款码'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<p className="label-md text-muted">将调起微信支付,由合伙人微信完成代付</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
style={{ marginTop: 12 }}
|
||||
disabled={paying}
|
||||
onClick={() => void startPay(created.id, 'JSAPI')}
|
||||
>
|
||||
{paying ? '支付中…' : '重新调起微信代付'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{msg ? (
|
||||
<p className="partner-form-error" role="alert" style={{ marginTop: 12 }}>
|
||||
{msg}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : loadingOptions ? (
|
||||
<p className="label-md text-muted">加载商品…</p>
|
||||
) : (
|
||||
<>
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">用户手机号</label>
|
||||
<div className="partner-input-row">
|
||||
<div className="partner-input-wrap" style={{ flex: 1 }}>
|
||||
<div className="partner-input-wrap">
|
||||
<input
|
||||
className="partner-input"
|
||||
placeholder="11 位手机号"
|
||||
@@ -242,27 +434,6 @@ export default function ProxyOrderPage() {
|
||||
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={customerCooldown > 0}
|
||||
onClick={() => void sendCustomerSms()}
|
||||
>
|
||||
{customerCooldown > 0 ? `${customerCooldown}s` : '获取验证码'}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">客户验证码</label>
|
||||
<div className="partner-input-wrap">
|
||||
<input
|
||||
className="partner-input"
|
||||
placeholder="发至客户手机"
|
||||
value={customerSmsCode}
|
||||
onChange={(e) => setCustomerSmsCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="partner-form-section">
|
||||
@@ -270,11 +441,12 @@ export default function ProxyOrderPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="partner-proxy-product-picker"
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
persistDraft();
|
||||
navigate(
|
||||
`/proxy-order/products${productId ? `?selected=${encodeURIComponent(productId)}` : ''}`,
|
||||
)
|
||||
}
|
||||
);
|
||||
}}
|
||||
>
|
||||
{selectedProduct ? (
|
||||
<>
|
||||
@@ -329,6 +501,7 @@ export default function ProxyOrderPage() {
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">履约方式</label>
|
||||
{allowOnline && allowOnSite ? (
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
@@ -345,9 +518,20 @@ export default function ProxyOrderPage() {
|
||||
现场提货
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="label-md text-muted">
|
||||
{!allowOnline && allowOnSite
|
||||
? '该商品仅支持现场提货'
|
||||
: allowOnline && !allowOnSite
|
||||
? allowCrossCity
|
||||
? '该商品仅支持配送到址(含跨城)'
|
||||
: '该商品仅支持配送到址(不可跨城)'
|
||||
: '该商品暂无可选履约方式'}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{deliveryMode === 'ADDRESS' ? (
|
||||
{deliveryMode === 'ADDRESS' && allowOnline ? (
|
||||
<>
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">收货人(选填)</label>
|
||||
@@ -389,11 +573,36 @@ export default function ProxyOrderPage() {
|
||||
checked={autoReceive}
|
||||
onChange={(e) => setAutoReceive(e.target.checked)}
|
||||
/>
|
||||
<span>同意自动收货(线下代下单提交后视为已送达并发放权益)</span>
|
||||
<span>同意自动收货(配送到址必选)</span>
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<section className="partner-form-section">
|
||||
<label className="partner-form-label">支付方式</label>
|
||||
<div className="partner-proxy-mode-tabs">
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'NATIVE' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('NATIVE')}
|
||||
>
|
||||
收款码
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`partner-proxy-mode-tab${payMethod === 'JSAPI' ? ' is-active' : ''}`}
|
||||
onClick={() => setPayMethod('JSAPI')}
|
||||
>
|
||||
微信代付
|
||||
</button>
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8, lineHeight: 1.5 }}>
|
||||
{payMethod === 'NATIVE'
|
||||
? '提交后展示商家收款码,客户或现场扫码支付'
|
||||
: '提交后在微信内由您代客户完成支付(需已绑定微信)'}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="partner-proxy-fee-card">
|
||||
<h3 className="headline-md">费用明细</h3>
|
||||
{previewLoading ? (
|
||||
@@ -428,73 +637,24 @@ export default function ProxyOrderPage() {
|
||||
)}
|
||||
</section>
|
||||
|
||||
{confirmStep ? (
|
||||
<section className="partner-form-section partner-proxy-confirm">
|
||||
<label className="partner-form-label">合伙人确认验证码</label>
|
||||
<p className="label-md text-muted" style={{ marginBottom: 8 }}>
|
||||
确认线下已收款后,将向您的登录手机号发送验证码
|
||||
</p>
|
||||
<div className="partner-input-row">
|
||||
<div className="partner-input-wrap" style={{ flex: 1 }}>
|
||||
<input
|
||||
className="partner-input"
|
||||
placeholder="发至合伙人手机"
|
||||
value={partnerSmsCode}
|
||||
onChange={(e) => setPartnerSmsCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
disabled={partnerCooldown > 0}
|
||||
onClick={() => void sendPartnerSms()}
|
||||
>
|
||||
{partnerCooldown > 0 ? `${partnerCooldown}s` : '重新发送'}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{msg ? (
|
||||
<p className="partner-form-error" role="alert">
|
||||
{msg}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!confirmStep ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-block"
|
||||
disabled={!preview}
|
||||
onClick={() => void openConfirmStep()}
|
||||
disabled={submitting || paying || !preview}
|
||||
onClick={() => void submit()}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
确认代下单
|
||||
{submitting || paying ? '处理中…' : '提交并支付'}
|
||||
</button>
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ flex: 1 }}
|
||||
onClick={() => setConfirmStep(false)}
|
||||
>
|
||||
返回修改
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
style={{ flex: 1 }}
|
||||
disabled={submitting || !preview}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting ? '提交中…' : '验证并提交'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="label-md text-muted" style={{ marginTop: 12, lineHeight: 1.5 }}>
|
||||
线下已收款确认后,将自动创建/关联用户,订单标记为代下单并直接完成,同时发放对应权益。客户订单列表会显示您的姓名。
|
||||
提交后进入在线支付;支付成功后发放权益。配送单将进入待发货由总部履约,现场提货走自提闭环。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import PageHeader from '@dukang/shared-ui/PageHeader';
|
||||
import { request } from '../lib/api';
|
||||
@@ -9,12 +9,30 @@ function fmtMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
type FulfillmentFilter = 'ALL' | 'ONLINE' | 'CROSS_CITY' | 'ON_SITE';
|
||||
|
||||
const FILTERS: Array<{ key: FulfillmentFilter; label: string }> = [
|
||||
{ key: 'ALL', label: '全部' },
|
||||
{ key: 'ONLINE', label: '线上' },
|
||||
{ key: 'CROSS_CITY', label: '跨城' },
|
||||
{ key: 'ON_SITE', label: '现场' },
|
||||
];
|
||||
|
||||
function matchFilter(p: PartnerProxyOrderProductOption, filter: FulfillmentFilter): boolean {
|
||||
if (filter === 'ALL') return true;
|
||||
if (filter === 'ONLINE') return p.allowOnlinePurchase !== false;
|
||||
if (filter === 'CROSS_CITY') return p.allowCrossCityDelivery !== false;
|
||||
return !!p.allowOnSitePickup;
|
||||
}
|
||||
|
||||
export default function ProxyOrderProductsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const selectedId = searchParams.get('selected') || '';
|
||||
const [products, setProducts] = useState<PartnerProxyOrderProductOption[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [filter, setFilter] = useState<FulfillmentFilter>('ALL');
|
||||
|
||||
useEffect(() => {
|
||||
request<PartnerProxyOrderOptions>('PARTNER_H5', '/partner/proxy-orders/options')
|
||||
@@ -23,6 +41,15 @@ export default function ProxyOrderProductsPage() {
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = keyword.trim().toLowerCase();
|
||||
return products.filter((p) => {
|
||||
if (!matchFilter(p, filter)) return false;
|
||||
if (!q) return true;
|
||||
return `${p.name} ${p.spec}`.toLowerCase().includes(q);
|
||||
});
|
||||
}, [products, keyword, filter]);
|
||||
|
||||
function pick(product: PartnerProxyOrderProductOption) {
|
||||
navigate(`/proxy-order?productId=${encodeURIComponent(product.id)}`, { replace: true });
|
||||
}
|
||||
@@ -30,12 +57,32 @@ export default function ProxyOrderProductsPage() {
|
||||
return (
|
||||
<div className="page partner-proxy-order-page">
|
||||
<PageHeader title="选择酒品" onBack={() => navigate(-1)} />
|
||||
<div className="partner-proxy-product-toolbar">
|
||||
<input
|
||||
className="partner-input"
|
||||
placeholder="搜索酒品名称 / 规格"
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
/>
|
||||
<div className="partner-proxy-product-filters">
|
||||
{FILTERS.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
type="button"
|
||||
className={`partner-proxy-product-filter${filter === f.key ? ' is-active' : ''}`}
|
||||
onClick={() => setFilter(f.key)}
|
||||
>
|
||||
{f.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<main className="partner-proxy-product-list">
|
||||
{loading ? <p className="label-md text-muted">加载中…</p> : null}
|
||||
{!loading && products.length === 0 ? (
|
||||
<p className="label-md text-muted">暂无可售商品</p>
|
||||
{!loading && filtered.length === 0 ? (
|
||||
<p className="label-md text-muted">暂无符合条件的商品</p>
|
||||
) : null}
|
||||
{products.map((p) => {
|
||||
{filtered.map((p) => {
|
||||
const benefit = p.benefitAmount != null ? Number(p.benefitAmount) : Number(p.price);
|
||||
const active = p.id === selectedId;
|
||||
return (
|
||||
@@ -59,6 +106,11 @@ export default function ProxyOrderProductsPage() {
|
||||
</div>
|
||||
<p className="partner-proxy-product-spec">{p.spec}</p>
|
||||
<p className="partner-proxy-product-benefit">好客权益 ¥{fmtMoney(benefit)}</p>
|
||||
<div className="partner-proxy-product-tags">
|
||||
{p.allowOnlinePurchase !== false ? <span className="partner-proxy-tag">线上</span> : null}
|
||||
{p.allowCrossCityDelivery !== false ? <span className="partner-proxy-tag">跨城</span> : null}
|
||||
{p.allowOnSitePickup ? <span className="partner-proxy-tag">现场</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -13,10 +13,10 @@ import { resolveRegionBinding } from '../lib/china-region';
|
||||
|
||||
import { checkStorePhoneAvailable } from '../lib/storePhone';
|
||||
|
||||
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
|
||||
|
||||
import { fetchPartnerCities, type OpenCityOption } from '../lib/upload';
|
||||
|
||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
|
||||
import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay';
|
||||
@@ -101,8 +101,6 @@ export default function StoreCreatePage() {
|
||||
|
||||
const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]);
|
||||
|
||||
const [locating, setLocating] = useState(false);
|
||||
|
||||
const [mapPickerOpen, setMapPickerOpen] = useState(false);
|
||||
|
||||
const draftSaveDisabledRef = useRef(false);
|
||||
@@ -134,7 +132,12 @@ export default function StoreCreatePage() {
|
||||
saveStoreDraft({ step, form }, accountId);
|
||||
}, [step, form, accountId]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 2 || !isWechatEnv()) return;
|
||||
void weixinSdk.init().catch(() => {
|
||||
/* OssUploadField 点击时会再次初始化 */
|
||||
});
|
||||
}, [step]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -662,31 +665,6 @@ export default function StoreCreatePage() {
|
||||
<textarea rows={2} placeholder="请输入详细门牌号" value={form.address} onChange={(e) => patchForm({ address: e.target.value })} />
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '8px 12px', fontSize: 13 }}
|
||||
disabled={locating}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setLocating(true);
|
||||
try {
|
||||
const pos = await locateStorePosition();
|
||||
patchForm({
|
||||
latitude: String(pos.latitude),
|
||||
longitude: String(pos.longitude),
|
||||
});
|
||||
toastSuccess('已获取当前坐标');
|
||||
} catch (e) {
|
||||
toastError(e instanceof Error ? e.message : '定位失败');
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{locating ? '定位中…' : '获取当前位置'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
@@ -696,11 +674,12 @@ export default function StoreCreatePage() {
|
||||
地图选点
|
||||
</button>
|
||||
<span className="label-md text-muted">
|
||||
{formatStoreCoords(form.latitude, form.longitude)
|
||||
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
|
||||
: '未定位(可定位或地图选点)'}
|
||||
{form.latitude.trim() && form.longitude.trim() ? '已选点' : '未选点'}
|
||||
</span>
|
||||
</div>
|
||||
{/* 经纬度仅内存/提交用,界面不展示 */}
|
||||
<input type="hidden" name="latitude" value={form.latitude} readOnly />
|
||||
<input type="hidden" name="longitude" value={form.longitude} readOnly />
|
||||
|
||||
</div>
|
||||
|
||||
@@ -928,7 +907,7 @@ export default function StoreCreatePage() {
|
||||
|
||||
onChange={(coverUrl) => patchForm({ coverUrl })}
|
||||
|
||||
label="从系统相册选择"
|
||||
label="拍照 / 从相册选择"
|
||||
|
||||
/>
|
||||
|
||||
@@ -974,7 +953,7 @@ export default function StoreCreatePage() {
|
||||
|
||||
<h3 className="headline-md">签约合同 <span className="text-primary">*</span></h3>
|
||||
|
||||
<p className="label-md text-muted" style={{ margin: '4px 0 12px' }}>上传签约协议首页与盖章页</p>
|
||||
<p className="label-md text-muted" style={{ margin: '4px 0 12px' }}>拍照上传签约协议首页与盖章页</p>
|
||||
|
||||
<OssUploadField
|
||||
|
||||
@@ -1164,9 +1143,7 @@ export default function StoreCreatePage() {
|
||||
longitude: String(loc.longitude),
|
||||
...(loc.address && !form.address.trim() ? { address: loc.address } : {}),
|
||||
});
|
||||
toastSuccess(
|
||||
`已选点 ${loc.latitude.toFixed(6)}, ${loc.longitude.toFixed(6)}${loc.name ? `(${loc.name})` : ''}`,
|
||||
);
|
||||
toastSuccess(loc.name ? `已选定:${loc.name}` : '位置已选定');
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { canManagePartnerStore } from '../lib/partnerAccess';
|
||||
import { normalizeStringArray, patchEnvPhotoAt } from '../lib/storeDraft';
|
||||
import { formatStoreCoords, locateStorePosition } from '../lib/storeLocate';
|
||||
import OssUploadField from '../components/OssUploadField';
|
||||
import TencentLocPickerOverlay from '../components/TencentLocPickerOverlay';
|
||||
import {
|
||||
@@ -55,7 +54,6 @@ export default function StoreDetailPage() {
|
||||
const [statusSaving, setStatusSaving] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [mediaSaving, setMediaSaving] = useState(false);
|
||||
const [locating, setLocating] = useState(false);
|
||||
const [mapPickerOpen, setMapPickerOpen] = useState(false);
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
|
||||
@@ -326,7 +324,7 @@ export default function StoreDetailPage() {
|
||||
mediaType="IMAGE"
|
||||
value={coverUrl}
|
||||
onChange={setCoverUrl}
|
||||
label="从系统相册选择"
|
||||
label="拍照 / 从相册选择"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -346,35 +344,6 @@ export default function StoreDetailPage() {
|
||||
<textarea disabled={readOnly} rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
|
||||
{!readOnly ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
style={{ padding: '8px 12px', fontSize: 13 }}
|
||||
disabled={locating}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
setLocating(true);
|
||||
setActionError('');
|
||||
try {
|
||||
const pos = await locateStorePosition();
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
latitude: String(pos.latitude),
|
||||
longitude: String(pos.longitude),
|
||||
}));
|
||||
toastSuccess('已获取当前坐标');
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : '定位失败';
|
||||
setActionError(msg);
|
||||
toastError(msg);
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{locating ? '定位中…' : '获取当前位置'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
@@ -384,16 +353,12 @@ export default function StoreDetailPage() {
|
||||
地图选点
|
||||
</button>
|
||||
<span className="label-md text-muted">
|
||||
{formatStoreCoords(form.latitude, form.longitude)
|
||||
? `坐标:${formatStoreCoords(form.latitude, form.longitude)}`
|
||||
: '未定位'}
|
||||
{form.latitude.trim() && form.longitude.trim() ? '已选点' : '未选点'}
|
||||
</span>
|
||||
</div>
|
||||
) : formatStoreCoords(form.latitude, form.longitude) ? (
|
||||
<p className="label-md text-muted" style={{ marginTop: 6 }}>
|
||||
坐标:{formatStoreCoords(form.latitude, form.longitude)}
|
||||
</p>
|
||||
) : null}
|
||||
<input type="hidden" name="latitude" value={form.latitude} readOnly />
|
||||
<input type="hidden" name="longitude" value={form.longitude} readOnly />
|
||||
</div>
|
||||
<div className="partner-field">
|
||||
<label>门店简介</label>
|
||||
@@ -523,9 +488,7 @@ export default function StoreDetailPage() {
|
||||
longitude: String(loc.longitude),
|
||||
...(loc.address && !prev.address.trim() ? { address: loc.address } : {}),
|
||||
}));
|
||||
toastSuccess(
|
||||
`已选点 ${loc.latitude.toFixed(6)}, ${loc.longitude.toFixed(6)}${loc.name ? `(${loc.name})` : ''}`,
|
||||
);
|
||||
toastSuccess(loc.name ? `已选定:${loc.name}` : '位置已选定');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3374,6 +3374,50 @@ body {
|
||||
color: var(--color-muted, #999);
|
||||
}
|
||||
|
||||
.partner-proxy-product-toolbar {
|
||||
padding: 0 16px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.partner-proxy-product-filters {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.partner-proxy-product-filter {
|
||||
border: 1px solid var(--color-border);
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--color-muted, #888);
|
||||
}
|
||||
|
||||
.partner-proxy-product-filter.is-active {
|
||||
border-color: var(--color-heritage-red);
|
||||
color: var(--color-heritage-red);
|
||||
background: rgba(166, 29, 36, 0.06);
|
||||
}
|
||||
|
||||
.partner-proxy-product-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.partner-proxy-tag {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
color: var(--color-muted, #666);
|
||||
}
|
||||
|
||||
.partner-proxy-product-list {
|
||||
padding: 0 16px 24px;
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
@@ -5,12 +5,14 @@ import LoginPage from './pages/LoginPage';
|
||||
import LegalPage from './pages/LegalPage';
|
||||
import SelectStorePage from './pages/SelectStorePage';
|
||||
import HomePage from './pages/HomePage';
|
||||
import RedeemConfirmPage from './pages/RedeemConfirmPage';
|
||||
import PhoneRedeemPage from './pages/PhoneRedeemPage';
|
||||
import RedeemSuccessPage from './pages/RedeemSuccessPage';
|
||||
import RecordsPage from './pages/RecordsPage';
|
||||
import StatusPage from './pages/StatusPage';
|
||||
import MinePage from './pages/MinePage';
|
||||
import StaffPage from './pages/StaffPage';
|
||||
import WithdrawPage from './pages/WithdrawPage';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -21,7 +23,8 @@ export default function App() {
|
||||
<Route path="/legal/privacy-policy" element={<LegalPage docId="privacy-policy" />} />
|
||||
<Route path="/select-store" element={<SelectStorePage />} />
|
||||
<Route path="/staff" element={<StaffPage />} />
|
||||
<Route path="/redeem" element={<Navigate to="/redeem/phone" replace />} />
|
||||
<Route path="/withdraw" element={<WithdrawPage />} />
|
||||
<Route path="/redeem" element={<RedeemConfirmPage />} />
|
||||
<Route path="/redeem/phone" element={<PhoneRedeemPage />} />
|
||||
<Route path="/redeem/success" element={<RedeemSuccessPage />} />
|
||||
<Route element={<TabLayout />}>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { getStoreProfile, hasShopWxSession } from '../lib/api';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
|
||||
const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
|
||||
@@ -25,6 +26,10 @@ export default function AuthGate({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
|
||||
const profile = getStoreProfile();
|
||||
if (profile && hasShopWxSession() && location.pathname !== '/login') {
|
||||
return <Navigate to="/login?quick=1" replace state={{ from: location }} />;
|
||||
}
|
||||
return <Navigate to="/login" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import {
|
||||
clearAuth,
|
||||
ensureSession,
|
||||
@@ -14,6 +16,15 @@ import {
|
||||
type ShopSessionPayload,
|
||||
type StoreSessionStore,
|
||||
} from '../lib/api';
|
||||
import {
|
||||
fetchClientConfig,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
isShopWechatUnboundError,
|
||||
SHOP_WX_NEED_PHONE_LOGIN_MSG,
|
||||
stashShopWechatLoginHint,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
type StoreSessionContextValue = {
|
||||
ready: boolean;
|
||||
@@ -26,6 +37,12 @@ type StoreSessionContextValue = {
|
||||
|
||||
const StoreSessionContext = createContext<StoreSessionContextValue | null>(null);
|
||||
|
||||
function deriveSelectStore(session: ShopSessionPayload, nextStore: StoreSessionStore | null) {
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
return stores.length > 1 && !storeId;
|
||||
}
|
||||
|
||||
export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [authenticated, setAuthenticated] = useState(false);
|
||||
@@ -43,9 +60,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
: null;
|
||||
setStore(nextStore);
|
||||
const storeId = nextStore?.storeId || session.selectedStoreId || '';
|
||||
const stores = session.stores ?? nextStore?.stores ?? [];
|
||||
setNeedsSelectStore(stores.length > 1 && !storeId);
|
||||
setNeedsSelectStore(deriveSelectStore(session, nextStore));
|
||||
}, []);
|
||||
|
||||
const resetSession = useCallback(() => {
|
||||
@@ -59,6 +74,27 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (isWechatEnv() && params.get('code')) {
|
||||
try {
|
||||
const config = await fetchClientConfig();
|
||||
if (isWxAuthorizeEnabled(config)) {
|
||||
const result = await handleShopWechatCallback();
|
||||
if (result && !cancelled) {
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) applySession(session);
|
||||
}
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
} catch (e) {
|
||||
const raw = e instanceof Error ? e.message : '';
|
||||
if (isShopWechatUnboundError(raw)) {
|
||||
stashShopWechatLoginHint(SHOP_WX_NEED_PHONE_LOGIN_MSG);
|
||||
}
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await ensureSession();
|
||||
if (cancelled) return;
|
||||
setAuthenticated(result.authenticated);
|
||||
@@ -73,7 +109,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [resetSession]);
|
||||
}, [applySession, resetSession]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ ready, authenticated, needsSelectStore, store, applySession, resetSession }),
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { apiBase } from './api';
|
||||
|
||||
const CLIENT_APP = 'SHOP_H5';
|
||||
const ACCESS_TOKEN = 'accessToken';
|
||||
|
||||
export type ClientErrorLevel = 'fatal' | 'error' | 'warn';
|
||||
export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
| 'other';
|
||||
|
||||
export type ClientErrorPayload = {
|
||||
level: ClientErrorLevel;
|
||||
category: ClientErrorCategory;
|
||||
message: string;
|
||||
stack?: string;
|
||||
pagePath?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function currentPagePath(): string | undefined {
|
||||
try {
|
||||
return typeof window !== 'undefined' ? window.location.pathname : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function getToken(): string {
|
||||
try {
|
||||
return localStorage.getItem(ACCESS_TOKEN) || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** 上报客户端错误(失败静默,避免递归) */
|
||||
export function reportClientError(payload: ClientErrorPayload): void {
|
||||
const body = {
|
||||
level: payload.level,
|
||||
category: payload.category,
|
||||
message: String(payload.message || 'unknown').slice(0, 1000),
|
||||
stack: payload.stack ? String(payload.stack).slice(0, 4000) : undefined,
|
||||
pagePath: (payload.pagePath || currentPagePath() || '').slice(0, 128) || undefined,
|
||||
clientApp: CLIENT_APP,
|
||||
extra: payload.extra,
|
||||
};
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': CLIENT_APP,
|
||||
};
|
||||
const token = getToken();
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
void fetch(`${apiBase}/common/client-errors`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
/** 安装 H5 全局未捕获错误钩子(幂等) */
|
||||
export function installClientErrorReporting(): void {
|
||||
if (installed || typeof window === 'undefined') return;
|
||||
installed = true;
|
||||
|
||||
window.addEventListener('error', (ev) => {
|
||||
reportClientError({
|
||||
level: 'fatal',
|
||||
category: 'js_error',
|
||||
message: ev.message || 'window.error',
|
||||
stack: ev.error instanceof Error ? ev.error.stack : undefined,
|
||||
extra: { filename: ev.filename, lineno: ev.lineno, colno: ev.colno },
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (ev) => {
|
||||
const reason = ev.reason;
|
||||
reportClientError({
|
||||
level: 'error',
|
||||
category: 'unhandled_rejection',
|
||||
message:
|
||||
reason instanceof Error
|
||||
? reason.message
|
||||
: typeof reason === 'string'
|
||||
? reason
|
||||
: 'unhandledrejection',
|
||||
stack: reason instanceof Error ? reason.stack : undefined,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -15,6 +15,40 @@ export type ShopAccountProfile = {
|
||||
store?: { name: string };
|
||||
};
|
||||
|
||||
/** 微信未绑定门店账号时的登录提示 */
|
||||
export const SHOP_WX_NEED_PHONE_LOGIN_MSG = '请先用手机号登录';
|
||||
|
||||
const SHOP_WX_LOGIN_HINT_KEY = 'shop_wx_login_hint';
|
||||
|
||||
export function isShopWechatUnboundError(message: string): boolean {
|
||||
return message.includes('首次登录') || message.includes('手机验证码') || message.includes('请先用手机号');
|
||||
}
|
||||
|
||||
export function formatShopWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (isShopWechatUnboundError(text)) return SHOP_WX_NEED_PHONE_LOGIN_MSG;
|
||||
return text;
|
||||
}
|
||||
|
||||
/** OAuth 在启动层失败时暂存提示,供登录页展示 */
|
||||
export function stashShopWechatLoginHint(message: string): void {
|
||||
try {
|
||||
sessionStorage.setItem(SHOP_WX_LOGIN_HINT_KEY, message);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeShopWechatLoginHint(): string | null {
|
||||
try {
|
||||
const hint = sessionStorage.getItem(SHOP_WX_LOGIN_HINT_KEY);
|
||||
if (hint) sessionStorage.removeItem(SHOP_WX_LOGIN_HINT_KEY);
|
||||
return hint;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
||||
return request<ClientRuntimeConfig>('SHOP_H5', '/common/client-config');
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { getRouterBasename } from '@dukang/weixin-sdk';
|
||||
import { StoreSessionProvider } from './contexts/StoreSessionContext';
|
||||
import { installClientErrorReporting } from './lib/client-error';
|
||||
import App from './App';
|
||||
import './styles.css';
|
||||
import './styles/legal.css';
|
||||
|
||||
installClientErrorReporting();
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter basename={getRouterBasename()}>
|
||||
|
||||
@@ -1,15 +1,47 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
import { request } from '../lib/api';
|
||||
import { parseRedeemTokenFromScan } from '../lib/redeem-scan';
|
||||
import {
|
||||
authorizeShopWechat,
|
||||
checkNeedsWechatAuth,
|
||||
fetchShopAccount,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import WechatScanAuthModal from '../components/WechatScanAuthModal';
|
||||
|
||||
const PENDING_SCAN_KEY = 'shop_pending_scan';
|
||||
|
||||
function formatMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function formatScanError(e: unknown): string {
|
||||
const msg = e instanceof Error ? e.message : '扫码失败,请重试';
|
||||
if (/invalid signature/i.test(msg)) {
|
||||
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
|
||||
}
|
||||
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
||||
return '微信权限校验尚未完成,请等待 1~2 秒后再次点击扫码(首次绑定微信时较常见)';
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession } = useStoreSession();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [dash, setDash] = useState<Record<string, unknown> | null>(null);
|
||||
const [scanMsg, setScanMsg] = useState('');
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [authModalOpen, setAuthModalOpen] = useState(false);
|
||||
const [authLoading, setAuthLoading] = useState(false);
|
||||
const [authError, setAuthError] = useState('');
|
||||
|
||||
const loadDashboard = useCallback(() => {
|
||||
return request<Record<string, unknown>>('SHOP_H5', '/shop/dashboard')
|
||||
@@ -25,6 +57,7 @@ export default function HomePage() {
|
||||
|
||||
useEffect(() => {
|
||||
function onResume() {
|
||||
setScanning(false);
|
||||
void loadDashboard();
|
||||
}
|
||||
function onVisibility() {
|
||||
@@ -40,6 +73,96 @@ export default function HomePage() {
|
||||
};
|
||||
}, [loadDashboard]);
|
||||
|
||||
async function runScan(opts?: { postAuthWarmup?: boolean }) {
|
||||
if (!isWechatEnv()) {
|
||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||
return;
|
||||
}
|
||||
setScanning(true);
|
||||
setScanMsg('');
|
||||
try {
|
||||
// 授权回跳后强制重签,避免沿用带 code 的旧签名态
|
||||
if (opts?.postAuthWarmup) {
|
||||
weixinSdk.reset();
|
||||
}
|
||||
await weixinSdk.init();
|
||||
const raw = await weixinSdk.scanQrCode(
|
||||
opts?.postAuthWarmup ? { postAuthWarmup: true } : undefined,
|
||||
);
|
||||
if (!raw) {
|
||||
void loadDashboard();
|
||||
return;
|
||||
}
|
||||
const token = parseRedeemTokenFromScan(raw);
|
||||
if (!token) {
|
||||
setScanMsg('无法识别核销码,请扫描用户出示的核销二维码');
|
||||
return;
|
||||
}
|
||||
navigate(`/redeem?token=${encodeURIComponent(token)}`);
|
||||
} catch (e) {
|
||||
setScanMsg(formatScanError(e));
|
||||
} finally {
|
||||
setScanning(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !searchParams.get('code')) return;
|
||||
void handleShopWechatCallback()
|
||||
.then((result) => {
|
||||
if (!result) return;
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) {
|
||||
applySession(session);
|
||||
}
|
||||
setAuthModalOpen(false);
|
||||
setAuthError('');
|
||||
// 先清 OAuth 参数再扫,保证 JSSDK 签名 URL 与当前页一致
|
||||
stripOAuthParamsFromLocation();
|
||||
setSearchParams({}, { replace: true });
|
||||
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
||||
if (shouldScan) {
|
||||
// OAuth 回跳后微信权限离线校验未完成;稍候再扫,失败可再点一次
|
||||
window.setTimeout(() => void runScan({ postAuthWarmup: true }), 400);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
||||
});
|
||||
}, [searchParams, applySession, setSearchParams]);
|
||||
|
||||
async function handleScan() {
|
||||
setScanMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const profile = await fetchShopAccount();
|
||||
if (await checkNeedsWechatAuth(profile)) {
|
||||
setAuthModalOpen(true);
|
||||
return;
|
||||
}
|
||||
await runScan();
|
||||
} catch (e) {
|
||||
setScanMsg(e instanceof Error ? e.message : '无法发起扫码');
|
||||
}
|
||||
}
|
||||
|
||||
async function startWechatAuth() {
|
||||
setAuthLoading(true);
|
||||
setAuthError('');
|
||||
try {
|
||||
sessionStorage.setItem(PENDING_SCAN_KEY, '1');
|
||||
await authorizeShopWechat();
|
||||
} catch (e) {
|
||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
||||
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
||||
setAuthLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const store = dash?.store as Record<string, unknown> | undefined;
|
||||
const recent = (dash?.recentRecords as Array<Record<string, unknown>>) || [];
|
||||
const status = String(store?.status || '');
|
||||
@@ -67,6 +190,9 @@ export default function HomePage() {
|
||||
<div className="shop-home-stat">
|
||||
<p className="shop-home-stat-label">今日核销笔数</p>
|
||||
<p className="shop-home-stat-value">{Number(dash?.todayCount || 0)}</p>
|
||||
<p className="shop-home-stat-sub">
|
||||
扫码 {Number(dash?.todayScanCount || 0)} · 手机号 {Number(dash?.todayPhoneCount || 0)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="shop-home-stat">
|
||||
<p className="shop-home-stat-label">今日到账金额</p>
|
||||
@@ -79,13 +205,20 @@ export default function HomePage() {
|
||||
</section>
|
||||
|
||||
<section className="shop-home-scan">
|
||||
<Link
|
||||
to="/redeem/phone"
|
||||
<button
|
||||
type="button"
|
||||
className="shop-home-scan-btn"
|
||||
disabled={scanning}
|
||||
onClick={() => void handleScan()}
|
||||
>
|
||||
<span className="material-symbols-outlined">qr_code_scanner</span>
|
||||
</button>
|
||||
<p className="shop-home-scan-label">{scanning ? '正在打开相机…' : '扫码核销'}</p>
|
||||
{scanMsg && <p className="shop-home-scan-msg" role="alert">{scanMsg}</p>}
|
||||
<Link to="/redeem/phone" className="shop-home-phone-link">
|
||||
<span className="material-symbols-outlined">smartphone</span>
|
||||
手机号核销
|
||||
</Link>
|
||||
<p className="shop-home-scan-label">手机号核销</p>
|
||||
</section>
|
||||
|
||||
<section className="shop-home-status">
|
||||
@@ -132,6 +265,17 @@ export default function HomePage() {
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<WechatScanAuthModal
|
||||
open={authModalOpen}
|
||||
loading={authLoading}
|
||||
error={authError}
|
||||
onAuthorize={() => void startWechatAuth()}
|
||||
onCancel={() => {
|
||||
setAuthModalOpen(false);
|
||||
setAuthError('');
|
||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
||||
}}
|
||||
/>
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
import { useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import AppImage from '@dukang/shared-ui/AppImage';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||
import {
|
||||
getLastPhone,
|
||||
getStoreProfile,
|
||||
hasShopWxSession,
|
||||
request,
|
||||
saveRememberedSession,
|
||||
type ShopSessionPayload,
|
||||
} from '../lib/api';
|
||||
import { routeAfterShopLogin } from './SelectStorePage';
|
||||
import {
|
||||
bindShopWechatAfterSmsLogin,
|
||||
consumeShopWechatLoginHint,
|
||||
fetchClientConfig,
|
||||
formatShopWechatError,
|
||||
handleShopWechatCallback,
|
||||
handleShopWechatLoginResult,
|
||||
loginShopWithWechat,
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
if (phone.length < 7) return phone;
|
||||
return `${phone.slice(0, 3)} **** ${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
function ShopAgreementCheckbox({
|
||||
agreed,
|
||||
@@ -43,14 +62,49 @@ function ShopAgreementCheckbox({
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession } = useStoreSession();
|
||||
const [params, setSearchParams] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getStoreProfile();
|
||||
const [phone, setPhone] = useState(getLastPhone());
|
||||
const [code, setCode] = useState('');
|
||||
const [agreed, setAgreed] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const [wxLoading, setWxLoading] = useState(false);
|
||||
const [msg, setMsg] = useState(() => consumeShopWechatLoginHint() ?? '');
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [wxAuthorize, setWxAuthorize] = useState(false);
|
||||
const agreementRef = useRef<HTMLLabelElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((config) => setWxAuthorize(isWxAuthorizeEnabled(config)))
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const hint = consumeShopWechatLoginHint();
|
||||
if (hint) setMsg(hint);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||
void handleShopWechatCallback()
|
||||
.then((result) => {
|
||||
if (!result) return;
|
||||
const session = handleShopWechatLoginResult(result);
|
||||
if (session) {
|
||||
applySession(session);
|
||||
stripOAuthParamsFromLocation();
|
||||
setSearchParams({}, { replace: true });
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
})
|
||||
.catch((e) => setMsg(formatShopWechatError(e)));
|
||||
}, [applySession, navigate, params, setSearchParams, wxAuthorize]);
|
||||
|
||||
const quickStoreName = savedProfile?.storeName ?? '门店管理中心';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
function ensureAgreed() {
|
||||
if (!agreed) {
|
||||
setMsg('请先阅读并同意用户协议');
|
||||
@@ -95,6 +149,11 @@ export default function LoginPage() {
|
||||
});
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
if (isWechatEnv() && wxAuthorize) {
|
||||
setMsg('登录成功,正在关联微信…');
|
||||
await bindShopWechatAfterSmsLogin();
|
||||
return;
|
||||
}
|
||||
routeAfterShopLogin(data, navigate);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '登录失败');
|
||||
@@ -103,6 +162,103 @@ export default function LoginPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function wechatLogin() {
|
||||
if (!ensureAgreed()) return;
|
||||
setMsg('');
|
||||
if (!isWechatEnv()) {
|
||||
setMsg('请在微信内打开以使用微信一键登录');
|
||||
return;
|
||||
}
|
||||
setWxLoading(true);
|
||||
try {
|
||||
const session = await loginShopWithWechat();
|
||||
if (session) {
|
||||
applySession(session);
|
||||
routeAfterShopLogin(session, navigate);
|
||||
}
|
||||
} catch (e) {
|
||||
setMsg(formatShopWechatError(e));
|
||||
} finally {
|
||||
setWxLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (quick) {
|
||||
const canWechatQuick = wxAuthorize && isWechatEnv() && hasShopWxSession() && !!savedProfile;
|
||||
|
||||
return (
|
||||
<div className="shop-quick-login-page">
|
||||
<header className="shop-quick-header">
|
||||
<AppImage src="/logo.png" alt="杜康好客" wrapperClassName="shop-quick-logo" fit="contain" />
|
||||
<h1 className="shop-quick-welcome">欢迎回来</h1>
|
||||
<div className="shop-quick-welcome-line" />
|
||||
</header>
|
||||
|
||||
<section className="shop-quick-store-card">
|
||||
<div className="shop-quick-store-inner">
|
||||
<div className="shop-quick-store-icon">
|
||||
<span className="material-symbols-outlined shop-fill-icon">storefront</span>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="shop-quick-store-name">{quickStoreName}</h2>
|
||||
<p className="shop-quick-store-phone">{maskPhone(quickPhone)}</p>
|
||||
</div>
|
||||
<span className="shop-quick-verified">
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 14 }}>verified_user</span>
|
||||
认证门店
|
||||
</span>
|
||||
<div className="shop-quick-switch">
|
||||
<Link to="/login">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>sync</span>
|
||||
切换账号
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="shop-quick-actions">
|
||||
{msg && <p className="shop-login-msg">{msg}</p>}
|
||||
<ShopAgreementCheckbox
|
||||
agreed={agreed}
|
||||
onChange={setAgreed}
|
||||
labelRef={agreementRef}
|
||||
/>
|
||||
{canWechatQuick ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shop-quick-login-btn shop-quick-login-btn--wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
) : (
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center' }}>
|
||||
{wxAuthorize && !isWechatEnv()
|
||||
? '请在微信内打开以使用一键登录'
|
||||
: '请使用验证码登录并绑定微信后,即可 7 天内免登录'}
|
||||
</p>
|
||||
)}
|
||||
{!canWechatQuick && (
|
||||
<Link to="/login" className="shop-quick-login-btn" style={{ textAlign: 'center', textDecoration: 'none' }}>
|
||||
验证码登录
|
||||
</Link>
|
||||
)}
|
||||
<div className="shop-quick-secure">
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 16 }}>lock</span>
|
||||
<span>{canWechatQuick ? '微信验证 · 7 天内免登录' : '加密环境安全登录中'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="shop-quick-footer">
|
||||
<p className="shop-login-footer-brand">SECURED BY DUKANG HERITAGE</p>
|
||||
<p style={{ fontSize: 10, fontFamily: 'var(--font-label)' }}>© 2024 杜康酒业门店管理系统</p>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="shop-login-page">
|
||||
<header className="shop-login-hero">
|
||||
@@ -172,8 +328,29 @@ export default function LoginPage() {
|
||||
<span>{loading ? '登录中...' : '登录'}</span>
|
||||
{!loading && <span className="material-symbols-outlined">arrow_forward</span>}
|
||||
</button>
|
||||
|
||||
{wxAuthorize && (
|
||||
<>
|
||||
<div className="shop-login-divider">
|
||||
<span className="shop-login-divider-line" />
|
||||
<span className="shop-login-divider-text">或者</span>
|
||||
<span className="shop-login-divider-line" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="shop-login-wechat"
|
||||
disabled={wxLoading}
|
||||
onClick={() => void wechatLogin()}
|
||||
>
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
<span>{wxLoading ? '登录中...' : '微信一键登录'}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="shop-login-msg" style={{ textAlign: 'center', marginTop: 12 }}>
|
||||
手机号验证成功后,7 天内无需再次输入验证码
|
||||
手机号验证成功后,7 天内无需再次输入验证码;微信内登录将自动关联微信
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
@@ -183,6 +360,11 @@ export default function LoginPage() {
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ opacity: 0.3, fontSize: 20, color: 'var(--color-outline)' }}>
|
||||
security
|
||||
</span>
|
||||
{hasShopWxSession() && savedProfile && (
|
||||
<p style={{ marginTop: 16, textAlign: 'center' }}>
|
||||
<Link to="/login?quick=1" className="text-primary body-md">微信快捷登录</Link>
|
||||
</p>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -141,6 +141,10 @@ export default function MinePage() {
|
||||
切换门店
|
||||
</button>
|
||||
) : null}
|
||||
<button type="button" className="shop-mine-action" onClick={() => navigate('/withdraw')}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>account_balance_wallet</span>
|
||||
结算提现
|
||||
</button>
|
||||
{profile?.isPrimary ? (
|
||||
<button type="button" className="shop-mine-action" onClick={() => navigate('/staff')}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>group</span>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel, type RedeemStatsDto } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
type RangeKey = 'today' | '7d' | '30d';
|
||||
@@ -23,32 +24,59 @@ function inRange(dateStr: string, range: RangeKey) {
|
||||
return d >= start;
|
||||
}
|
||||
|
||||
function channelLabel(channel: unknown): string {
|
||||
const key = channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||
return REDEEM_CHANNEL_LABELS[key];
|
||||
}
|
||||
|
||||
export default function RecordsPage() {
|
||||
const [records, setRecords] = useState<Array<Record<string, unknown>>>([]);
|
||||
const [range, setRange] = useState<RangeKey>('today');
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
const [storeName, setStoreName] = useState('');
|
||||
const [statsOpen, setStatsOpen] = useState(false);
|
||||
const [statsLoading, setStatsLoading] = useState(false);
|
||||
const [stats, setStats] = useState<RedeemStatsDto | null>(null);
|
||||
|
||||
const loadRecords = useCallback(() => {
|
||||
return Promise.all([
|
||||
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records').then((d) => {
|
||||
request<{ list: Array<Record<string, unknown>> }>('SHOP_H5', '/shop/redeem/records?pageSize=200').then(
|
||||
(d) => {
|
||||
setRecords(d.list || []);
|
||||
}),
|
||||
},
|
||||
),
|
||||
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
||||
.then((s) => setStoreName(String(s.name || '')))
|
||||
.catch(() => {}),
|
||||
]);
|
||||
}, []);
|
||||
|
||||
const loadStats = useCallback(async (r: RangeKey) => {
|
||||
setStatsLoading(true);
|
||||
try {
|
||||
const data = await request<RedeemStatsDto>('SHOP_H5', `/shop/redeem/stats?range=${r}`);
|
||||
setStats(data);
|
||||
} catch {
|
||||
setStats(null);
|
||||
} finally {
|
||||
setStatsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadRecords();
|
||||
}, [loadRecords]);
|
||||
|
||||
useEffect(() => {
|
||||
if (statsOpen) void loadStats(range);
|
||||
}, [statsOpen, range, loadStats]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return records.filter((r) => {
|
||||
if (!inRange(String(r.createdAt), range)) return false;
|
||||
if (statusFilter === 'all') return true;
|
||||
const isPaid = Boolean(r.paidAt);
|
||||
const payout = r.payout as { paidAt?: string | null; status?: string } | undefined;
|
||||
const isPaid = Boolean(payout?.paidAt) || payout?.status === 'PAID' || Boolean(r.paidAt);
|
||||
if (statusFilter === 'paid') return isPaid;
|
||||
return !isPaid;
|
||||
});
|
||||
@@ -70,11 +98,13 @@ export default function RecordsPage() {
|
||||
<div className="shop-records-main">
|
||||
<nav className="shop-records-filters">
|
||||
<div className="shop-records-range-tabs">
|
||||
{([
|
||||
{(
|
||||
[
|
||||
['today', '今日'],
|
||||
['7d', '近7日'],
|
||||
['30d', '近30日'],
|
||||
] as const).map(([key, label]) => (
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
@@ -85,12 +115,15 @@ export default function RecordsPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="shop-records-status-row">
|
||||
<div className="shop-records-status-chips">
|
||||
{([
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['pending', '待打款'],
|
||||
['paid', '已打款'],
|
||||
] as const).map(([key, label]) => (
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
@@ -101,6 +134,17 @@ export default function RecordsPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-records-stats-btn"
|
||||
onClick={() => setStatsOpen(true)}
|
||||
>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 18 }}>
|
||||
bar_chart
|
||||
</span>
|
||||
统计
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<section className="shop-records-summary">
|
||||
@@ -115,7 +159,10 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<p className="shop-records-summary-note">
|
||||
<span className="material-symbols-outlined shop-fill-icon" style={{ fontSize: 16, color: 'var(--color-success-green)' }}>
|
||||
<span
|
||||
className="material-symbols-outlined shop-fill-icon"
|
||||
style={{ fontSize: 16, color: 'var(--color-success-green)' }}
|
||||
>
|
||||
check_circle
|
||||
</span>
|
||||
结算比例: {summary.rate}% (按{summary.rate / 10}折结算)
|
||||
@@ -134,17 +181,32 @@ export default function RecordsPage() {
|
||||
{filtered.map((r) => {
|
||||
const amount = Number(r.amount || 0);
|
||||
const settle = Number(r.settleAmount || 0);
|
||||
const paid = Boolean(r.paidAt);
|
||||
const payout = r.payout as { paidAt?: string | null; status?: string } | undefined;
|
||||
const paid = Boolean(payout?.paidAt) || payout?.status === 'PAID' || Boolean(r.paidAt);
|
||||
const paidAt = payout?.paidAt || (typeof r.paidAt === 'string' ? r.paidAt : null);
|
||||
const channel = (r.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel;
|
||||
return (
|
||||
<article key={String(r.id)} className="shop-record-card">
|
||||
<div className="shop-record-card-top">
|
||||
<div>
|
||||
<div className="shop-record-order">
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>订单号</span>
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>
|
||||
订单号
|
||||
</span>
|
||||
<span>{r.redeemNo ? String(r.redeemNo) : '—'}</span>
|
||||
</div>
|
||||
<p className="shop-record-time">
|
||||
核销时间: {new Date(String(r.createdAt)).toLocaleString('zh-CN', { hour12: false }).slice(0, 16)}
|
||||
核销时间:{' '}
|
||||
{new Date(String(r.createdAt))
|
||||
.toLocaleString('zh-CN', { hour12: false })
|
||||
.slice(0, 16)}
|
||||
</p>
|
||||
<p className="shop-record-channel">
|
||||
<span
|
||||
className={`shop-record-channel-tag${channel === 'PHONE' ? ' phone' : ''}`}
|
||||
>
|
||||
{channelLabel(channel)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<span className={`shop-record-badge ${paid ? 'paid' : 'pending'}`}>
|
||||
@@ -162,10 +224,16 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="shop-record-footer">
|
||||
<p>{paid ? `打款时间: ${new Date(String(r.createdAt)).toLocaleDateString('zh-CN')}` : '预计打款: T+1工作日'}</p>
|
||||
<p>
|
||||
{paid
|
||||
? `打款时间: ${paidAt ? new Date(String(paidAt)).toLocaleDateString('zh-CN') : '—'}`
|
||||
: '预计打款: T+1工作日'}
|
||||
</p>
|
||||
{storeName && (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 12 }}>restaurant</span>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 12 }}>
|
||||
restaurant
|
||||
</span>
|
||||
{storeName}
|
||||
</span>
|
||||
)}
|
||||
@@ -183,6 +251,80 @@ export default function RecordsPage() {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{statsOpen && (
|
||||
<div className="shop-stats-overlay" role="dialog" aria-modal="true" aria-label="核销方式统计">
|
||||
<button
|
||||
type="button"
|
||||
className="shop-stats-backdrop"
|
||||
aria-label="关闭"
|
||||
onClick={() => setStatsOpen(false)}
|
||||
/>
|
||||
<div className="shop-stats-sheet">
|
||||
<div className="shop-stats-sheet-head">
|
||||
<h2>核销方式统计</h2>
|
||||
<button type="button" className="shop-stats-close" onClick={() => setStatsOpen(false)}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<p className="shop-stats-range-hint">
|
||||
统计区间:{range === 'today' ? '今日' : range === '7d' ? '近7日' : '近30日'}(与上方筛选同步)
|
||||
</p>
|
||||
{statsLoading ? (
|
||||
<p className="shop-records-empty">加载中…</p>
|
||||
) : !stats ? (
|
||||
<p className="shop-records-empty">统计加载失败</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="shop-stats-total">
|
||||
<div>
|
||||
<p className="shop-records-summary-label">合计笔数</p>
|
||||
<p className="shop-stats-total-value">{stats.totalCount}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">核销总额</p>
|
||||
<p className="shop-stats-total-value">¥{formatMoney(stats.totalAmount)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">到账总额</p>
|
||||
<p className="shop-stats-total-value">¥{formatMoney(stats.totalSettleAmount)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="shop-stats-channel-list">
|
||||
{stats.byChannel.map((b) => (
|
||||
<div key={b.channel} className="shop-stats-channel-card">
|
||||
<div className="shop-stats-channel-title">
|
||||
<span
|
||||
className={`shop-record-channel-tag${b.channel === 'PHONE' ? ' phone' : ''}`}
|
||||
>
|
||||
{REDEEM_CHANNEL_LABELS[b.channel]}
|
||||
</span>
|
||||
<strong>{b.count} 笔</strong>
|
||||
</div>
|
||||
<div className="shop-stats-channel-row">
|
||||
<span>核销额</span>
|
||||
<span>¥{formatMoney(b.amount)}</span>
|
||||
</div>
|
||||
<div className="shop-stats-channel-row">
|
||||
<span>到账额</span>
|
||||
<span>¥{formatMoney(b.settleAmount)}</span>
|
||||
</div>
|
||||
<div className="shop-stats-bar">
|
||||
<div
|
||||
className={`shop-stats-bar-fill${b.channel === 'PHONE' ? ' phone' : ''}`}
|
||||
style={{
|
||||
width: `${stats.totalCount > 0 ? Math.round((b.count / stats.totalCount) * 100) : 0}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
STORE_WITHDRAW_STATUS_LABELS,
|
||||
type StoreWithdrawRequestDto,
|
||||
type StoreWithdrawStatus,
|
||||
type StoreWithdrawSummaryDto,
|
||||
} from '@dukang/shared-types';
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
type StatusFilter = 'all' | StoreWithdrawStatus;
|
||||
|
||||
function formatMoney(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export default function WithdrawPage() {
|
||||
const navigate = useNavigate();
|
||||
const [summary, setSummary] = useState<StoreWithdrawSummaryDto | null>(null);
|
||||
const [items, setItems] = useState<StoreWithdrawRequestDto[]>([]);
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [summaryRes, listRes] = await Promise.all([
|
||||
request<StoreWithdrawSummaryDto>('SHOP_H5', '/shop/withdraw/summary'),
|
||||
request<{ items: StoreWithdrawRequestDto[] }>('SHOP_H5', '/shop/withdraw/requests?pageSize=50'),
|
||||
]);
|
||||
setSummary(summaryRes);
|
||||
setItems(listRes.items || []);
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '加载失败');
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (statusFilter === 'all') return items;
|
||||
return items.filter((r) => r.status === statusFilter);
|
||||
}, [items, statusFilter]);
|
||||
|
||||
async function applyWithdraw() {
|
||||
if (!summary || submitting) return;
|
||||
if (!summary.isPrimary) {
|
||||
setMsg('仅主账号可申请提现');
|
||||
return;
|
||||
}
|
||||
if (!(summary.availableAmount > 0)) {
|
||||
setMsg('暂无可提未出账余额');
|
||||
return;
|
||||
}
|
||||
const ok = window.confirm(
|
||||
`确认申请提现 ¥${formatMoney(summary.availableAmount)}?\n审核通过后将打款至入驻收款账户。`,
|
||||
);
|
||||
if (!ok) return;
|
||||
setSubmitting(true);
|
||||
setMsg('');
|
||||
try {
|
||||
await request('SHOP_H5', '/shop/withdraw', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
setMsg('提现申请已提交,请等待总部审核');
|
||||
await load();
|
||||
} catch (e) {
|
||||
setMsg(e instanceof Error ? e.message : '提现申请失败');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const canApply =
|
||||
!!summary?.isPrimary &&
|
||||
summary.availableAmount > 0 &&
|
||||
!summary.hasPendingRequest &&
|
||||
summary.hasBankAccount &&
|
||||
!submitting;
|
||||
|
||||
return (
|
||||
<PullToRefresh onRefresh={load} className="shop-records-page shop-withdraw-page">
|
||||
<header className="shop-records-header" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-withdraw-back"
|
||||
onClick={() => navigate(-1)}
|
||||
aria-label="返回"
|
||||
>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 22 }}>
|
||||
arrow_back
|
||||
</span>
|
||||
</button>
|
||||
<h1 className="app-page-title" style={{ margin: 0 }}>
|
||||
结算提现
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<div className="shop-records-main">
|
||||
<section className="shop-records-summary">
|
||||
<div className="shop-records-summary-grid">
|
||||
<div>
|
||||
<p className="shop-records-summary-label">可提未出账余额</p>
|
||||
<p className="shop-records-summary-value">
|
||||
¥ {formatMoney(summary?.availableAmount ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-records-summary-label">今日剩余额度</p>
|
||||
<p className="shop-records-summary-value">
|
||||
¥ {formatMoney(summary?.remainingDailyLimit ?? 0)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="shop-records-summary-note">
|
||||
<span
|
||||
className="material-symbols-outlined shop-fill-icon"
|
||||
style={{ fontSize: 16, color: 'var(--color-success-green)' }}
|
||||
>
|
||||
info
|
||||
</span>
|
||||
单日上限 ¥{formatMoney(summary?.dailyLimit ?? 5000)}
|
||||
{summary?.hasPendingRequest ? ' · 已有待审核申请' : ''}
|
||||
{!summary?.hasBankAccount ? ' · 请先完善收款账户' : ''}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{summary && !summary.isPrimary ? (
|
||||
<p className="shop-records-empty">仅主账号可申请提现,店员可查看记录</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="shop-withdraw-btn"
|
||||
disabled={!canApply}
|
||||
onClick={() => void applyWithdraw()}
|
||||
>
|
||||
{submitting ? '提交中…' : '申请提现'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{msg ? <p className="shop-withdraw-msg">{msg}</p> : null}
|
||||
|
||||
<nav className="shop-records-filters" style={{ marginTop: 16 }}>
|
||||
<div className="shop-records-status-chips">
|
||||
{(
|
||||
[
|
||||
['all', '全部'],
|
||||
['PENDING_REVIEW', '待审核'],
|
||||
['PAID', '已结算'],
|
||||
['REJECTED', '已驳回'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={`shop-records-chip${statusFilter === key ? ' active' : ''}`}
|
||||
onClick={() => setStatusFilter(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="shop-records-list-head">
|
||||
<h3 className="shop-records-list-title">提现记录</h3>
|
||||
<span className="shop-records-list-count">共 {filtered.length} 笔</span>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<p className="shop-records-empty">暂无提现记录</p>
|
||||
) : (
|
||||
<div className="shop-records-list">
|
||||
{filtered.map((r) => {
|
||||
const status = r.status as StoreWithdrawStatus;
|
||||
const badgeClass =
|
||||
status === 'PAID' ? 'paid' : status === 'REJECTED' ? 'rejected' : 'pending';
|
||||
return (
|
||||
<article key={r.id} className="shop-record-card">
|
||||
<div className="shop-record-card-top">
|
||||
<div>
|
||||
<div className="shop-record-order">
|
||||
<span className="shop-record-time" style={{ margin: 0 }}>
|
||||
单号
|
||||
</span>
|
||||
<span>{r.withdrawNo}</span>
|
||||
</div>
|
||||
<p className="shop-record-time">
|
||||
申请时间:{' '}
|
||||
{new Date(r.appliedAt)
|
||||
.toLocaleString('zh-CN', { hour12: false })
|
||||
.slice(0, 16)}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`shop-record-badge ${badgeClass}`}>
|
||||
{STORE_WITHDRAW_STATUS_LABELS[status] ?? status}
|
||||
</span>
|
||||
</div>
|
||||
<div className="shop-record-amounts">
|
||||
<div>
|
||||
<p className="shop-record-amount-label">提现金额</p>
|
||||
<p className="shop-record-amount-value red">¥{formatMoney(Number(r.amount))}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="shop-record-amount-label">明细笔数</p>
|
||||
<p className="shop-record-amount-value">{r.payoutCount} 笔</p>
|
||||
</div>
|
||||
</div>
|
||||
{status === 'REJECTED' && r.rejectReason ? (
|
||||
<div className="shop-record-footer">
|
||||
<p>驳回原因: {r.rejectReason}</p>
|
||||
</div>
|
||||
) : null}
|
||||
{status === 'PAID' && r.paidAt ? (
|
||||
<div className="shop-record-footer">
|
||||
<p>
|
||||
结算时间:{' '}
|
||||
{new Date(r.paidAt).toLocaleString('zh-CN', { hour12: false }).slice(0, 16)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PullToRefresh>
|
||||
);
|
||||
}
|
||||
@@ -587,6 +587,12 @@
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.shop-home-stat-sub {
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
}
|
||||
|
||||
.shop-home-scan {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1549,18 +1555,42 @@
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.shop-records-status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.shop-records-status-chips {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.shop-records-status-chips::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.shop-records-stats-btn {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border: 1px solid var(--color-primary);
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
border-radius: var(--radius-full);
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-records-chip {
|
||||
flex-shrink: 0;
|
||||
border: none;
|
||||
@@ -1578,6 +1608,142 @@
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
|
||||
.shop-record-channel {
|
||||
margin: 6px 0 0;
|
||||
}
|
||||
|
||||
.shop-record-channel-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 11px;
|
||||
line-height: 1;
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.shop-record-channel-tag.phone {
|
||||
background: rgba(168, 85, 247, 0.12);
|
||||
color: #7e22ce;
|
||||
}
|
||||
|
||||
.shop-stats-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 80;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.shop-stats-backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: none;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.shop-stats-sheet {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
max-height: 78vh;
|
||||
overflow: auto;
|
||||
background: var(--color-surface);
|
||||
border-radius: 16px 16px 0 0;
|
||||
padding: 16px 16px calc(16px + env(safe-area-inset-bottom, 0px));
|
||||
box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
.shop-stats-sheet-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.shop-stats-sheet-head h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.shop-stats-close {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-stats-range-hint {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.shop-stats-total {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--color-surface-container-low, #f5f5f4);
|
||||
}
|
||||
|
||||
.shop-stats-total-value {
|
||||
margin: 4px 0 0;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.shop-stats-channel-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-card {
|
||||
border: 1px solid var(--color-surface-container-highest);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.shop-stats-channel-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
color: var(--color-on-surface-variant);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.shop-stats-bar {
|
||||
margin-top: 8px;
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-surface-container-highest);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.shop-stats-bar-fill {
|
||||
height: 100%;
|
||||
background: #3b82f6;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.shop-stats-bar-fill.phone {
|
||||
background: #a855f7;
|
||||
}
|
||||
|
||||
.shop-records-main {
|
||||
padding-top: 0;
|
||||
}
|
||||
@@ -1714,6 +1880,46 @@
|
||||
color: var(--color-aged-amber);
|
||||
}
|
||||
|
||||
.shop-record-badge.rejected {
|
||||
background: rgba(180, 35, 24, 0.1);
|
||||
color: var(--color-error-red, #b42318);
|
||||
}
|
||||
|
||||
.shop-withdraw-back {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 4px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-withdraw-btn {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
height: 44px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
background: var(--color-primary, #8b1a1a);
|
||||
color: #fff;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-withdraw-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.shop-withdraw-msg {
|
||||
margin-top: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--color-aged-amber);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.shop-record-amounts {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
|
||||
@@ -41,6 +41,7 @@ export default function PayPage() {
|
||||
const [showBindPhone, setShowBindPhone] = useState(false);
|
||||
const [wxSessionKey, setWxSessionKey] = useState<string | null>(null);
|
||||
const [orderNo, setOrderNo] = useState('');
|
||||
const [deliveryType, setDeliveryType] = useState('');
|
||||
|
||||
const refreshPayReadiness = useCallback(async () => {
|
||||
try {
|
||||
@@ -78,9 +79,15 @@ export default function PayPage() {
|
||||
setOrderNo('');
|
||||
return;
|
||||
}
|
||||
request<{ orderNo?: string }>('USER_H5', `/trade/orders/${orderId}`)
|
||||
.then((order) => setOrderNo(order.orderNo || ''))
|
||||
.catch(() => setOrderNo(''));
|
||||
request<{ orderNo?: string; deliveryType?: string }>('USER_H5', `/trade/orders/${orderId}`)
|
||||
.then((order) => {
|
||||
setOrderNo(order.orderNo || '');
|
||||
setDeliveryType(order.deliveryType || '');
|
||||
})
|
||||
.catch(() => {
|
||||
setOrderNo('');
|
||||
setDeliveryType('');
|
||||
});
|
||||
}, [orderId]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -140,11 +147,13 @@ export default function PayPage() {
|
||||
if (!paid) {
|
||||
alert('支付结果确认中,请稍后在订单列表查看');
|
||||
}
|
||||
navigate('/orders?tab=paid');
|
||||
navigate(
|
||||
deliveryType === 'ON_SITE_PICKUP' ? '/orders?tab=completed' : '/orders?tab=paid',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
navigate('/orders?tab=paid');
|
||||
navigate(deliveryType === 'ON_SITE_PICKUP' ? '/orders?tab=completed' : '/orders?tab=paid');
|
||||
} catch (e) {
|
||||
if (isWechatAuthRequiredError(e)) {
|
||||
setNeedsWechatAuth(true);
|
||||
|
||||
@@ -1,13 +1,69 @@
|
||||
import './lib/intl-polyfill';
|
||||
import './lib/text-encoding-polyfill';
|
||||
import { PropsWithChildren } from 'react';
|
||||
import { PropsWithChildren, useRef } from 'react';
|
||||
import Taro, { useDidShow } from '@tarojs/taro';
|
||||
import WechatShareBootstrap from './components/WechatShareBootstrap';
|
||||
import { patchTaroH5Hooks } from './lib/patch-taro-h5-hooks';
|
||||
import { handleWechatOrderConfirmShow } from './lib/wechat-order-confirm';
|
||||
import { installClientErrorReporting } from './lib/client-error';
|
||||
import './app.css';
|
||||
|
||||
// H5:在首屏 page hooks 执行前,把 Taro.useDidShow 等绑到与 createReactApp 同一份 runtime
|
||||
patchTaroH5Hooks();
|
||||
installClientErrorReporting();
|
||||
|
||||
function App({ children }: PropsWithChildren) {
|
||||
const handlingRef = useRef(false);
|
||||
|
||||
useDidShow((options?: {
|
||||
referrerInfo?: {
|
||||
appId?: string;
|
||||
extraData?: { status?: string; errormsg?: string; req_extradata?: Record<string, string> };
|
||||
};
|
||||
}) => {
|
||||
if (process.env.TARO_ENV !== 'weapp') return;
|
||||
if (handlingRef.current) return;
|
||||
|
||||
const referrerInfo =
|
||||
options?.referrerInfo ||
|
||||
(typeof Taro.getEnterOptionsSync === 'function'
|
||||
? (
|
||||
Taro.getEnterOptionsSync() as {
|
||||
referrerInfo?: {
|
||||
appId?: string;
|
||||
extraData?: {
|
||||
status?: string;
|
||||
errormsg?: string;
|
||||
req_extradata?: Record<string, string>;
|
||||
};
|
||||
};
|
||||
}
|
||||
).referrerInfo
|
||||
: undefined);
|
||||
if (!referrerInfo?.appId) return;
|
||||
|
||||
handlingRef.current = true;
|
||||
void handleWechatOrderConfirmShow({ referrerInfo })
|
||||
.then((result) => {
|
||||
if (result.redirectUrl) {
|
||||
Taro.redirectTo({ url: result.redirectUrl }).catch(() => {
|
||||
Taro.reLaunch({ url: result.redirectUrl! });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!result.handled || !result.orderId) return;
|
||||
const pages = Taro.getCurrentPages();
|
||||
const cur = pages[pages.length - 1] as { route?: string } | undefined;
|
||||
const route = cur?.route || '';
|
||||
if (route.includes('pickup-receive')) {
|
||||
Taro.redirectTo({ url: '/pages/orders/index?tab=all' }).catch(() => {});
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
handlingRef.current = false;
|
||||
});
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<WechatShareBootstrap />
|
||||
|
||||
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
import { ClientApp } from '@dukang/shared-types';
|
||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||
import { resetStoresSessionBootstrap } from './stores-session';
|
||||
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||
|
||||
function resolveApiBase(): string {
|
||||
const origin =
|
||||
@@ -56,6 +58,9 @@ export function isLoggedIn(): boolean {
|
||||
|
||||
export function logout() {
|
||||
clearAuth();
|
||||
// 主动退出才重置门店/首页「当次登录」会话;401 清 token 不要打断筛选
|
||||
resetStoresSessionBootstrap();
|
||||
resetHomeCatalogBootstrap();
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
import { CLIENT_APP, getToken, API_BASE } from './api';
|
||||
|
||||
export type ClientErrorLevel = 'fatal' | 'error' | 'warn';
|
||||
export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
| 'other';
|
||||
|
||||
export type ClientErrorPayload = {
|
||||
level: ClientErrorLevel;
|
||||
category: ClientErrorCategory;
|
||||
message: string;
|
||||
stack?: string;
|
||||
pagePath?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function currentPagePath(): string | undefined {
|
||||
try {
|
||||
const pages = Taro.getCurrentPages();
|
||||
const cur = pages[pages.length - 1] as { route?: string; $taroPath?: string } | undefined;
|
||||
return cur?.$taroPath || cur?.route || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 上报客户端错误(失败静默,避免递归) */
|
||||
export function reportClientError(payload: ClientErrorPayload): void {
|
||||
const body = {
|
||||
level: payload.level,
|
||||
category: payload.category,
|
||||
message: String(payload.message || 'unknown').slice(0, 1000),
|
||||
stack: payload.stack ? String(payload.stack).slice(0, 4000) : undefined,
|
||||
pagePath: payload.pagePath || currentPagePath(),
|
||||
clientApp: CLIENT_APP,
|
||||
extra: payload.extra,
|
||||
};
|
||||
|
||||
const header: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': CLIENT_APP,
|
||||
};
|
||||
const token = getToken();
|
||||
if (token) header.Authorization = `Bearer ${token}`;
|
||||
|
||||
void Taro.request({
|
||||
url: `${API_BASE}/common/client-errors`,
|
||||
method: 'POST',
|
||||
data: body,
|
||||
header,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
/** 安装小程序/H5 全局未捕获错误钩子(幂等) */
|
||||
export function installClientErrorReporting(): void {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
|
||||
try {
|
||||
Taro.onError?.((msg) => {
|
||||
reportClientError({
|
||||
level: 'fatal',
|
||||
category: 'js_error',
|
||||
message: typeof msg === 'string' ? msg : String(msg),
|
||||
});
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
try {
|
||||
Taro.onUnhandledRejection?.((res) => {
|
||||
const reason = (res as { reason?: unknown })?.reason;
|
||||
const message =
|
||||
reason instanceof Error
|
||||
? reason.message
|
||||
: typeof reason === 'string'
|
||||
? reason
|
||||
: JSON.stringify(reason);
|
||||
const stack = reason instanceof Error ? reason.stack : undefined;
|
||||
reportClientError({
|
||||
level: 'error',
|
||||
category: 'unhandled_rejection',
|
||||
message: message || 'UnhandledRejection',
|
||||
stack,
|
||||
});
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('error', (ev) => {
|
||||
reportClientError({
|
||||
level: 'fatal',
|
||||
category: 'js_error',
|
||||
message: ev.message || 'window.error',
|
||||
stack: ev.error instanceof Error ? ev.error.stack : undefined,
|
||||
extra: { filename: ev.filename, lineno: ev.lineno, colno: ev.colno },
|
||||
});
|
||||
});
|
||||
window.addEventListener('unhandledrejection', (ev) => {
|
||||
const reason = ev.reason;
|
||||
reportClientError({
|
||||
level: 'error',
|
||||
category: 'unhandled_rejection',
|
||||
message:
|
||||
reason instanceof Error
|
||||
? reason.message
|
||||
: typeof reason === 'string'
|
||||
? reason
|
||||
: 'unhandledrejection',
|
||||
stack: reason instanceof Error ? reason.stack : undefined,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** 格式化为 Asia/Shanghai:2026-08-03 15:14:30(不依赖 Intl,兼容微信小程序) */
|
||||
export function formatShanghaiDateTime(input?: string | Date | null): string {
|
||||
if (input == null || input === '') return '—';
|
||||
if (typeof input === 'string') {
|
||||
const s = input.trim();
|
||||
if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(s)) {
|
||||
return s.slice(0, 19).replace('T', ' ');
|
||||
}
|
||||
}
|
||||
const d = input instanceof Date ? input : new Date(input);
|
||||
if (Number.isNaN(d.getTime())) return '—';
|
||||
// 用 UTC 读数 + 固定东八区偏移,避免依赖 Intl / 设备时区 API 差异
|
||||
const sh = new Date(d.getTime() + 8 * 60 * 60 * 1000);
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${sh.getUTCFullYear()}-${p(sh.getUTCMonth() + 1)}-${p(sh.getUTCDate())} ${p(sh.getUTCHours())}:${p(sh.getUTCMinutes())}:${p(sh.getUTCSeconds())}`;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 首页商品列表「当次登录」会话 —— 切 tab 不重复拉商品;
|
||||
* 城市 / 登录态变化或下拉刷新时再请求。logout 时 clear。
|
||||
*/
|
||||
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
export type HomeCatalogCache = {
|
||||
cityCode: string;
|
||||
authKey: string;
|
||||
products: unknown[];
|
||||
};
|
||||
|
||||
type HomeSession = {
|
||||
bootstrapped: boolean;
|
||||
cache: HomeCatalogCache | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'dukang_home_catalog_session_v1';
|
||||
|
||||
let memory: HomeSession | null = null;
|
||||
|
||||
function emptySession(): HomeSession {
|
||||
return { bootstrapped: false, cache: null };
|
||||
}
|
||||
|
||||
function readSession(): HomeSession {
|
||||
if (memory) return memory;
|
||||
try {
|
||||
const raw = Taro.getStorageSync(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
memory = emptySession();
|
||||
return memory;
|
||||
}
|
||||
const parsed = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Partial<HomeSession>;
|
||||
memory = {
|
||||
bootstrapped: !!parsed.bootstrapped,
|
||||
cache: (parsed.cache as HomeCatalogCache | null) ?? null,
|
||||
};
|
||||
return memory;
|
||||
} catch {
|
||||
memory = emptySession();
|
||||
return memory;
|
||||
}
|
||||
}
|
||||
|
||||
function writeSession(next: HomeSession) {
|
||||
memory = next;
|
||||
try {
|
||||
Taro.setStorageSync(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* ignore quota */
|
||||
}
|
||||
}
|
||||
|
||||
export function isHomeCatalogBootstrapped(): boolean {
|
||||
return readSession().bootstrapped;
|
||||
}
|
||||
|
||||
export function getHomeCatalogCache(): HomeCatalogCache | null {
|
||||
return readSession().cache;
|
||||
}
|
||||
|
||||
export function setHomeCatalogCache(cache: HomeCatalogCache): void {
|
||||
writeSession({ bootstrapped: true, cache });
|
||||
}
|
||||
|
||||
export function resetHomeCatalogBootstrap(): void {
|
||||
memory = emptySession();
|
||||
try {
|
||||
Taro.removeStorageSync(STORAGE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 微信小程序基础库无 Intl。业务代码已避免依赖,此处仅作兜底,
|
||||
* 防止旧包 / 依赖偶发 `new Intl.DateTimeFormat` 直接白屏。
|
||||
*/
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
function shanghaiParts(date: Date) {
|
||||
const sh = new Date(date.getTime() + 8 * 60 * 60 * 1000);
|
||||
return {
|
||||
year: String(sh.getUTCFullYear()),
|
||||
month: pad(sh.getUTCMonth() + 1),
|
||||
day: pad(sh.getUTCDate()),
|
||||
hour: pad(sh.getUTCHours()),
|
||||
minute: pad(sh.getUTCMinutes()),
|
||||
second: pad(sh.getUTCSeconds()),
|
||||
};
|
||||
}
|
||||
|
||||
function installIntlStub() {
|
||||
const root = (typeof globalThis !== 'undefined'
|
||||
? globalThis
|
||||
: typeof global !== 'undefined'
|
||||
? global
|
||||
: typeof wx !== 'undefined'
|
||||
? wx
|
||||
: {}) as typeof globalThis & { Intl?: typeof Intl };
|
||||
|
||||
if (typeof root.Intl !== 'undefined' && typeof root.Intl.DateTimeFormat === 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
class MiniDateTimeFormat {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
constructor(_locales?: string | string[], _options?: Record<string, unknown>) {}
|
||||
|
||||
format(date?: Date | number) {
|
||||
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const p = shanghaiParts(d);
|
||||
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
|
||||
}
|
||||
|
||||
formatToParts(date?: Date | number) {
|
||||
const d = date instanceof Date ? date : new Date(date ?? Date.now());
|
||||
if (Number.isNaN(d.getTime())) return [];
|
||||
const p = shanghaiParts(d);
|
||||
return [
|
||||
{ type: 'year', value: p.year },
|
||||
{ type: 'literal', value: '-' },
|
||||
{ type: 'month', value: p.month },
|
||||
{ type: 'literal', value: '-' },
|
||||
{ type: 'day', value: p.day },
|
||||
{ type: 'literal', value: ' ' },
|
||||
{ type: 'hour', value: p.hour },
|
||||
{ type: 'literal', value: ':' },
|
||||
{ type: 'minute', value: p.minute },
|
||||
{ type: 'literal', value: ':' },
|
||||
{ type: 'second', value: p.second },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
root.Intl = {
|
||||
DateTimeFormat: MiniDateTimeFormat,
|
||||
} as unknown as typeof Intl;
|
||||
}
|
||||
|
||||
installIntlStub();
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,9 @@
|
||||
/** 金额展示(不依赖 Intl / toLocaleString,兼容微信小程序) */
|
||||
export function formatMoney(amount: number | string): string {
|
||||
const n = typeof amount === 'number' ? amount : Number(amount);
|
||||
if (!Number.isFinite(n)) return '0.00';
|
||||
const fixed = n.toFixed(2);
|
||||
const [intPart, dec] = fixed.split('.');
|
||||
const withComma = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
return `${withComma}.${dec}`;
|
||||
}
|
||||
@@ -106,6 +106,8 @@ export function tabNavContentStyle(metrics: NavBarMetrics): Record<string, strin
|
||||
/** 子页/内页顶栏:标题全屏居中,内容区单独留白 */
|
||||
export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, string | number> {
|
||||
const pagePad = 20;
|
||||
// 标题两侧取「右侧避让胶囊」宽度,保证相对屏幕视觉居中
|
||||
const titlePad = Math.max(metrics.navBarPaddingRight, 72);
|
||||
return {
|
||||
paddingTop: `${metrics.statusBarHeight}px`,
|
||||
height: `${metrics.navBarHeight}px`,
|
||||
@@ -113,7 +115,7 @@ export function subPageNavBarStyle(metrics: NavBarMetrics): Record<string, strin
|
||||
'--nav-content-height': `${metrics.navContentHeight}px`,
|
||||
'--nav-status-bar-height': `${metrics.statusBarHeight}px`,
|
||||
'--nav-padding-left': `${pagePad}px`,
|
||||
'--nav-padding-right': `${metrics.navBarPaddingRight}px`,
|
||||
'--nav-padding-right': `${titlePad}px`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/** 商品履约能力(与 HQ / 交易硬闸一致) */
|
||||
|
||||
export type FulfillmentFlags = {
|
||||
allowOnlinePurchase?: boolean | null;
|
||||
allowOnSitePickup?: boolean | null;
|
||||
allowCrossCityDelivery?: boolean | null;
|
||||
};
|
||||
|
||||
/** 未返回时默认允许线上(存量商品) */
|
||||
export function canBuyOnline(p: FulfillmentFlags): boolean {
|
||||
return p.allowOnlinePurchase !== false;
|
||||
}
|
||||
|
||||
/** 仅显式开启才展示现场取货 */
|
||||
export function canPickupOnSite(p: FulfillmentFlags): boolean {
|
||||
return p.allowOnSitePickup === true;
|
||||
}
|
||||
|
||||
export function canCrossCity(p: FulfillmentFlags): boolean {
|
||||
return p.allowCrossCityDelivery !== false;
|
||||
}
|
||||
|
||||
export function normalizeFulfillmentFlags<T extends FulfillmentFlags>(p: T): T {
|
||||
return {
|
||||
...p,
|
||||
allowOnlinePurchase: canBuyOnline(p),
|
||||
allowOnSitePickup: canPickupOnSite(p),
|
||||
allowCrossCityDelivery: canCrossCity(p),
|
||||
};
|
||||
}
|
||||
|
||||
/** 与交易侧一致:收货市 ≠ 开城市且 ≠ 郑州 → 跨城 */
|
||||
export function isCrossCityAddress(
|
||||
addressCity: string | null | undefined,
|
||||
openCityName: string | null | undefined,
|
||||
): boolean {
|
||||
const addr = (addressCity || '').trim();
|
||||
const open = (openCityName || '').trim();
|
||||
if (!addr) return false;
|
||||
if (addr === '郑州市') return false;
|
||||
if (open && addr === open) return false;
|
||||
// 尚无开城信息时,非郑州地址先按可能跨城处理(由预览接口最终裁定)
|
||||
if (!open) return addr !== '郑州市';
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* 门店列表「当次登录」会话 —— 用 Taro Storage 持久化,
|
||||
* 避免模块多实例 / globalThis 不可靠导致切 tab 后当成首次进入。
|
||||
* 仅 logout 时 clear。
|
||||
*/
|
||||
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
export type StoresSessionRegion = {
|
||||
province: string;
|
||||
city: string;
|
||||
district: string;
|
||||
};
|
||||
|
||||
export type StoresSessionCategory = {
|
||||
parentId: string;
|
||||
parentName: string;
|
||||
childId: string;
|
||||
childName: string;
|
||||
};
|
||||
|
||||
export type StoresListCache = {
|
||||
cityKey: string;
|
||||
cityCode: string;
|
||||
/** 登录态指纹:token 变化时需重新拉取(白名单) */
|
||||
authKey: string;
|
||||
listRegion: StoresSessionRegion;
|
||||
items: unknown[];
|
||||
filterRegion: StoresSessionRegion;
|
||||
keyword: string;
|
||||
keywordInput: string;
|
||||
category: StoresSessionCategory;
|
||||
};
|
||||
|
||||
type StoresSession = {
|
||||
bootstrapped: boolean;
|
||||
cache: StoresListCache | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'dukang_stores_session_v1';
|
||||
|
||||
let memory: StoresSession | null = null;
|
||||
|
||||
function emptySession(): StoresSession {
|
||||
return { bootstrapped: false, cache: null };
|
||||
}
|
||||
|
||||
function readSession(): StoresSession {
|
||||
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<StoresSession>;
|
||||
memory = {
|
||||
bootstrapped: !!parsed.bootstrapped,
|
||||
cache: (parsed.cache as StoresListCache | null) ?? null,
|
||||
};
|
||||
return memory;
|
||||
} catch {
|
||||
memory = emptySession();
|
||||
return memory;
|
||||
}
|
||||
}
|
||||
|
||||
function writeSession(next: StoresSession) {
|
||||
memory = next;
|
||||
try {
|
||||
Taro.setStorageSync(STORAGE_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* ignore quota */
|
||||
}
|
||||
}
|
||||
|
||||
export function isStoresSessionBootstrapped(): boolean {
|
||||
return readSession().bootstrapped;
|
||||
}
|
||||
|
||||
export function markStoresSessionBootstrapped(): void {
|
||||
const cur = readSession();
|
||||
writeSession({ ...cur, bootstrapped: true });
|
||||
}
|
||||
|
||||
export function getStoresListCache(): StoresListCache | null {
|
||||
return readSession().cache;
|
||||
}
|
||||
|
||||
export function setStoresListCache(cache: StoresListCache | null): void {
|
||||
const cur = readSession();
|
||||
writeSession({ ...cur, bootstrapped: true, cache });
|
||||
}
|
||||
|
||||
export function patchStoresFilterCache(
|
||||
patch: Partial<
|
||||
Pick<StoresListCache, 'filterRegion' | 'keyword' | 'keywordInput' | 'category'>
|
||||
>,
|
||||
): void {
|
||||
const cur = readSession();
|
||||
if (!cur.cache) {
|
||||
// 列表尚未写入时也要记下用户筛选,避免切回丢失
|
||||
writeSession({
|
||||
bootstrapped: true,
|
||||
cache: {
|
||||
cityKey: '',
|
||||
cityCode: '',
|
||||
listRegion: patch.filterRegion ?? { province: '', city: '', district: '' },
|
||||
items: [],
|
||||
filterRegion: patch.filterRegion ?? { province: '', city: '', district: '' },
|
||||
keyword: patch.keyword ?? '',
|
||||
keywordInput: patch.keywordInput ?? '',
|
||||
category: patch.category ?? {
|
||||
parentId: '',
|
||||
parentName: '',
|
||||
childId: '',
|
||||
childName: '',
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
writeSession({
|
||||
...cur,
|
||||
bootstrapped: true,
|
||||
cache: { ...cur.cache, ...patch },
|
||||
});
|
||||
}
|
||||
|
||||
export function resetStoresSessionBootstrap(): void {
|
||||
memory = emptySession();
|
||||
try {
|
||||
Taro.removeStorageSync(STORAGE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
import { request, toast } from './api';
|
||||
import { fetchClientConfig } from './pay-wechat';
|
||||
|
||||
/** 微信确认收货组件来源 AppId(官方固定) */
|
||||
export const WECHAT_ORDER_CONFIRM_APPID = 'wx1183b055aeec94d1';
|
||||
|
||||
const PENDING_KEY = 'pending_wechat_order_confirm';
|
||||
|
||||
export type WechatConfirmPayload = {
|
||||
merchantId?: string | null;
|
||||
merchantTradeNo?: string | null;
|
||||
transactionId?: string | null;
|
||||
};
|
||||
|
||||
type PendingConfirm = {
|
||||
orderId: string;
|
||||
redirectUrl?: string;
|
||||
};
|
||||
|
||||
type OpenBusinessViewOptions = {
|
||||
businessType: string;
|
||||
extraData: Record<string, string>;
|
||||
success?: () => void;
|
||||
fail?: (err: { errMsg?: string }) => void;
|
||||
complete?: () => void;
|
||||
};
|
||||
|
||||
type MiniWx = {
|
||||
openBusinessView?: (opts: OpenBusinessViewOptions) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 取小程序原生 wx.openBusinessView。
|
||||
* 官方兼容写法:`if (wx.openBusinessView) { ... }`(不要用 canIUse 挡业务组件)。
|
||||
* Taro 未封装该 API;模块作用域下可能读不到全局 wx,需多重回退。
|
||||
*/
|
||||
function getOpenBusinessView(): ((opts: OpenBusinessViewOptions) => void) | null {
|
||||
if (process.env.TARO_ENV !== 'weapp') return null;
|
||||
|
||||
const candidates: Array<MiniWx | null | undefined> = [];
|
||||
|
||||
try {
|
||||
// eslint-disable-next-line no-undef
|
||||
if (typeof wx !== 'undefined') candidates.push(wx as MiniWx);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
const g = globalThis as typeof globalThis & { wx?: MiniWx };
|
||||
candidates.push(g.wx);
|
||||
|
||||
try {
|
||||
// 跳出 bundler 模块作用域,读微信运行时全局
|
||||
const fromRuntime = new Function(
|
||||
'return typeof wx !== "undefined" ? wx : null',
|
||||
)() as MiniWx | null;
|
||||
candidates.push(fromRuntime);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
for (const api of candidates) {
|
||||
if (api && typeof api.openBusinessView === 'function') {
|
||||
return api.openBusinessView.bind(api);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function savePendingWechatOrderConfirm(pending: PendingConfirm) {
|
||||
Taro.setStorageSync(PENDING_KEY, JSON.stringify(pending));
|
||||
}
|
||||
|
||||
export function takePendingWechatOrderConfirm(): PendingConfirm | null {
|
||||
try {
|
||||
const raw = Taro.getStorageSync(PENDING_KEY);
|
||||
if (!raw) return null;
|
||||
Taro.removeStorageSync(PENDING_KEY);
|
||||
return typeof raw === 'string' ? (JSON.parse(raw) as PendingConfirm) : (raw as PendingConfirm);
|
||||
} catch {
|
||||
Taro.removeStorageSync(PENDING_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePayload(payload?: WechatConfirmPayload | null): WechatConfirmPayload {
|
||||
return {
|
||||
merchantId: payload?.merchantId?.trim() || undefined,
|
||||
merchantTradeNo: payload?.merchantTradeNo?.trim() || undefined,
|
||||
transactionId: payload?.transactionId?.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveConfirmPayload(
|
||||
orderId: string,
|
||||
hint?: WechatConfirmPayload | null,
|
||||
): Promise<WechatConfirmPayload> {
|
||||
const fromHint = normalizePayload(hint);
|
||||
if (fromHint.transactionId || (fromHint.merchantId && fromHint.merchantTradeNo)) {
|
||||
return fromHint;
|
||||
}
|
||||
|
||||
const order = await request<{
|
||||
orderNo?: string;
|
||||
payExternalNo?: string | null;
|
||||
payment?: { externalNo?: string | null } | null;
|
||||
wechatConfirm?: WechatConfirmPayload | null;
|
||||
}>(`/trade/orders/${orderId}`);
|
||||
|
||||
const fromApi = normalizePayload(order.wechatConfirm);
|
||||
if (fromApi.transactionId || (fromApi.merchantId && fromApi.merchantTradeNo)) {
|
||||
return fromApi;
|
||||
}
|
||||
|
||||
const transactionId =
|
||||
order.payExternalNo?.trim() || order.payment?.externalNo?.trim() || undefined;
|
||||
return normalizePayload({
|
||||
transactionId,
|
||||
merchantTradeNo: order.orderNo,
|
||||
merchantId: fromApi.merchantId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉起微信「确认收货」半屏组件。
|
||||
* @see https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping-half.html
|
||||
*/
|
||||
export function openWechatOrderConfirm(opts: {
|
||||
orderId: string;
|
||||
payload: WechatConfirmPayload;
|
||||
redirectUrl?: string;
|
||||
}): Promise<'opened' | 'unsupported' | 'missing_pay_ref'> {
|
||||
const open = getOpenBusinessView();
|
||||
if (!open) {
|
||||
console.warn('[wechat-order-confirm] openBusinessView unavailable', {
|
||||
taroEnv: process.env.TARO_ENV,
|
||||
});
|
||||
return Promise.resolve('unsupported');
|
||||
}
|
||||
|
||||
const payload = normalizePayload(opts.payload);
|
||||
const transactionId = payload.transactionId;
|
||||
const merchantId = payload.merchantId;
|
||||
const merchantTradeNo = payload.merchantTradeNo;
|
||||
if (!transactionId && !(merchantId && merchantTradeNo)) {
|
||||
console.warn('[wechat-order-confirm] missing pay ref', payload);
|
||||
return Promise.resolve('missing_pay_ref');
|
||||
}
|
||||
|
||||
const extraData: Record<string, string> = {};
|
||||
if (transactionId) extraData.transaction_id = transactionId;
|
||||
if (merchantId) extraData.merchant_id = merchantId;
|
||||
if (merchantTradeNo) extraData.merchant_trade_no = merchantTradeNo;
|
||||
|
||||
savePendingWechatOrderConfirm({
|
||||
orderId: opts.orderId,
|
||||
redirectUrl: opts.redirectUrl,
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (mode: 'opened' | 'unsupported' | 'missing_pay_ref') => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(mode);
|
||||
};
|
||||
|
||||
try {
|
||||
open({
|
||||
businessType: 'weappOrderConfirm',
|
||||
extraData,
|
||||
success: () => done('opened'),
|
||||
fail: (err) => {
|
||||
Taro.removeStorageSync(PENDING_KEY);
|
||||
console.error('[wechat-order-confirm] openBusinessView fail', err, extraData);
|
||||
toast(err?.errMsg || '无法打开微信确认收货,请稍后重试');
|
||||
done('unsupported');
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
Taro.removeStorageSync(PENDING_KEY);
|
||||
console.error('[wechat-order-confirm] openBusinessView throw', err);
|
||||
toast('无法打开微信确认收货组件');
|
||||
done('unsupported');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type ReferrerExtra = {
|
||||
status?: string;
|
||||
errormsg?: string;
|
||||
req_extradata?: Record<string, string>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理确认收货组件回跳(App/页面 onShow)。
|
||||
* 成功则调用后端同步订单,并返回是否已处理。
|
||||
*/
|
||||
export async function handleWechatOrderConfirmShow(options?: {
|
||||
referrerInfo?: { appId?: string; extraData?: ReferrerExtra };
|
||||
}): Promise<{ handled: boolean; orderId?: string; redirectUrl?: string }> {
|
||||
const info = options?.referrerInfo;
|
||||
if (!info?.appId || info.appId !== WECHAT_ORDER_CONFIRM_APPID) {
|
||||
return { handled: false };
|
||||
}
|
||||
|
||||
const pending = takePendingWechatOrderConfirm();
|
||||
const status = info.extraData?.status;
|
||||
if (status === 'cancel') {
|
||||
toast('已取消确认收货');
|
||||
return { handled: true, orderId: pending?.orderId };
|
||||
}
|
||||
if (status === 'fail') {
|
||||
toast(info.extraData?.errormsg || '微信确认收货失败');
|
||||
return { handled: true, orderId: pending?.orderId };
|
||||
}
|
||||
if (status !== 'success' || !pending?.orderId) {
|
||||
return { handled: true };
|
||||
}
|
||||
|
||||
try {
|
||||
await request(`/trade/orders/${pending.orderId}/confirm-receive`, {
|
||||
method: 'POST',
|
||||
data: { source: 'WECHAT_COMPONENT' },
|
||||
});
|
||||
toast('确认收货成功', 'success');
|
||||
return {
|
||||
handled: true,
|
||||
orderId: pending.orderId,
|
||||
redirectUrl: pending.redirectUrl,
|
||||
};
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '同步订单失败');
|
||||
return { handled: true, orderId: pending.orderId };
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmLocally(opts: {
|
||||
orderId: string;
|
||||
onSitePickup?: boolean;
|
||||
onLocalSuccess?: () => void | Promise<void>;
|
||||
}): Promise<'local'> {
|
||||
await request(`/trade/orders/${opts.orderId}/confirm-receive`, {
|
||||
method: 'POST',
|
||||
data: {
|
||||
onSitePickup: !!opts.onSitePickup,
|
||||
source: 'USER',
|
||||
},
|
||||
});
|
||||
await opts.onLocalSuccess?.();
|
||||
return 'local';
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一入口:
|
||||
* - 小程序 + 真实支付:必须拉起 weappOrderConfirm,禁止静默降级
|
||||
* - Mock / H5:本地确认
|
||||
*/
|
||||
export async function confirmOrderReceive(opts: {
|
||||
orderId: string;
|
||||
wechatConfirm?: WechatConfirmPayload | null;
|
||||
onSitePickup?: boolean;
|
||||
redirectUrl?: string;
|
||||
onLocalSuccess?: () => void | Promise<void>;
|
||||
}): Promise<'wechat' | 'local'> {
|
||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||
|
||||
if (!isWeapp) {
|
||||
return confirmLocally(opts);
|
||||
}
|
||||
|
||||
let mockPay = false;
|
||||
try {
|
||||
const cfg = await fetchClientConfig();
|
||||
mockPay = !!cfg.mockPay;
|
||||
} catch {
|
||||
mockPay = false;
|
||||
}
|
||||
|
||||
if (mockPay) {
|
||||
return confirmLocally(opts);
|
||||
}
|
||||
|
||||
const payload = await resolveConfirmPayload(opts.orderId, opts.wechatConfirm);
|
||||
const mode = await openWechatOrderConfirm({
|
||||
orderId: opts.orderId,
|
||||
payload,
|
||||
redirectUrl: opts.redirectUrl,
|
||||
});
|
||||
|
||||
if (mode === 'opened') return 'wechat';
|
||||
|
||||
if (mode === 'missing_pay_ref') {
|
||||
throw new Error('缺少微信支付单号,无法打开确认收货组件');
|
||||
}
|
||||
throw new Error('当前环境无法打开微信确认收货组件,请用微信最新版打开小程序后重试');
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
import Taro from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request } from '../../lib/api';
|
||||
@@ -28,7 +29,17 @@ export default function BenefitDetailPage() {
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="benefit-detail-page">
|
||||
<SubPageHeader title="权益明细" />
|
||||
<SubPageHeader
|
||||
title="权益明细"
|
||||
onBack={() => {
|
||||
const pages = Taro.getCurrentPages();
|
||||
if (pages.length > 1) {
|
||||
Taro.navigateBack();
|
||||
return;
|
||||
}
|
||||
Taro.switchTab({ url: '/pages/mine/index' });
|
||||
}}
|
||||
/>
|
||||
<View className="sub-page-body">
|
||||
<View className="order-card">
|
||||
{loading ? <View className="u-empty">加载中…</View> : null}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
@@ -13,6 +12,8 @@ import {
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
import iconBenefit from '../../assets/tabbar/benefit-active.png';
|
||||
|
||||
type BenefitSummary = {
|
||||
totalBalance: number;
|
||||
@@ -30,9 +31,13 @@ type CouponItem = {
|
||||
sourceProduct: string;
|
||||
};
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
type RedeemHistoryItem = {
|
||||
id: string;
|
||||
redeemNo: string;
|
||||
amount: number;
|
||||
storeName: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function usagePercent(coupon: CouponItem) {
|
||||
const total = Number(coupon.totalAmount);
|
||||
@@ -45,11 +50,13 @@ export default function BenefitPage() {
|
||||
const [loggedIn, setLoggedIn] = useState(() => isLoggedIn());
|
||||
const [summary, setSummary] = useState<BenefitSummary | null>(null);
|
||||
const [coupons, setCoupons] = useState<CouponItem[]>([]);
|
||||
const [redeemHistory, setRedeemHistory] = useState<RedeemHistoryItem[]>([]);
|
||||
const [tab, setTab] = useState<'available' | 'history'>('available');
|
||||
|
||||
const resetGuestState = useCallback(() => {
|
||||
setSummary(null);
|
||||
setCoupons([]);
|
||||
setRedeemHistory([]);
|
||||
}, []);
|
||||
|
||||
const loadBenefit = useCallback(() => {
|
||||
@@ -57,10 +64,17 @@ export default function BenefitPage() {
|
||||
return Promise.all([
|
||||
request<BenefitSummary>('/benefit/summary'),
|
||||
request<CouponItem[]>('/benefit/coupons'),
|
||||
request<{ list?: RedeemHistoryItem[] } | RedeemHistoryItem[]>('/redeem/records?page=1&pageSize=50'),
|
||||
])
|
||||
.then(([s, list]) => {
|
||||
.then(([s, list, records]) => {
|
||||
setSummary(s);
|
||||
setCoupons(Array.isArray(list) ? list : []);
|
||||
const hist = Array.isArray(records)
|
||||
? records
|
||||
: Array.isArray(records?.list)
|
||||
? records.list
|
||||
: [];
|
||||
setRedeemHistory(hist);
|
||||
})
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
}, []);
|
||||
@@ -88,8 +102,6 @@ export default function BenefitPage() {
|
||||
});
|
||||
|
||||
const available = coupons.filter((c) => c.status === 'ACTIVE' && c.balance > 0);
|
||||
const history = coupons.filter((c) => c.status === 'USED_UP' || c.status === 'VOID');
|
||||
const visible = tab === 'available' ? available : history;
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => ({
|
||||
@@ -122,9 +134,6 @@ export default function BenefitPage() {
|
||||
<View className="benefit-header-city-pin" />
|
||||
<Text>郑州市</Text>
|
||||
</View>
|
||||
<View className="benefit-header__share page-nav-bar__right-slot">
|
||||
<ShareNavButton payload={sharePayload} />
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -153,7 +162,7 @@ export default function BenefitPage() {
|
||||
</View>
|
||||
</View>
|
||||
<View className="benefit-hero-logo">
|
||||
<Text>康</Text>
|
||||
<Image className="benefit-hero-logo-img" src={iconBenefit} mode="aspectFit" />
|
||||
</View>
|
||||
</View>
|
||||
<View
|
||||
@@ -179,10 +188,11 @@ export default function BenefitPage() {
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<View className="u-empty">{tab === 'available' ? '暂无可用权益' : '暂无历史记录'}</View>
|
||||
{tab === 'available' ? (
|
||||
available.length === 0 ? (
|
||||
<View className="u-empty">暂无可用权益</View>
|
||||
) : (
|
||||
visible.map((c) => (
|
||||
available.map((c) => (
|
||||
<View key={c.id} className="benefit-coupon">
|
||||
<View className="benefit-coupon-notch" />
|
||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||
@@ -198,7 +208,6 @@ export default function BenefitPage() {
|
||||
<Text className="benefit-coupon-meta">
|
||||
已用 ¥{formatMoney(c.usedAmount)} / 总额 ¥{formatMoney(c.totalAmount)}
|
||||
</Text>
|
||||
{tab === 'available' ? (
|
||||
<Text
|
||||
className="benefit-coupon-btn"
|
||||
onClick={() =>
|
||||
@@ -209,7 +218,26 @@ export default function BenefitPage() {
|
||||
>
|
||||
立即核销
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
))
|
||||
)
|
||||
) : redeemHistory.length === 0 ? (
|
||||
<View className="u-empty">暂无核销记录</View>
|
||||
) : (
|
||||
redeemHistory.map((r) => (
|
||||
<View key={r.id} className="benefit-coupon">
|
||||
<View className="benefit-coupon-notch" />
|
||||
<View className="benefit-coupon-notch benefit-coupon-notch--right" />
|
||||
<View className="benefit-coupon-head">
|
||||
<Text className="benefit-coupon-name">{r.storeName || '门店核销'}</Text>
|
||||
<Text className="benefit-coupon-balance">-¥{formatMoney(Number(r.amount))}</Text>
|
||||
</View>
|
||||
<Text className="benefit-coupon-no">NO. {r.redeemNo}</Text>
|
||||
<View className="benefit-coupon-footer">
|
||||
<Text className="benefit-coupon-meta">
|
||||
{r.createdAt ? String(r.createdAt).slice(0, 19).replace('T', ' ') : '-'}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
))
|
||||
|
||||
@@ -1,23 +1,39 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
usePageScroll,
|
||||
usePullDownRefresh,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import TabMainHeader from '../../components/TabMainHeader';
|
||||
import CouponBadge from '../../components/CouponBadge';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||
import { getToken, isLoggedIn, request, toast } from '../../lib/api';
|
||||
import {
|
||||
getHomeCatalogCache,
|
||||
isHomeCatalogBootstrapped,
|
||||
setHomeCatalogCache,
|
||||
} from '../../lib/home-catalog-session';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { capturePromoSceneAndTouchScan } from '../../lib/promo';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
import {
|
||||
canBuyOnline,
|
||||
canCrossCity,
|
||||
canPickupOnSite,
|
||||
normalizeFulfillmentFlags,
|
||||
} from '../../lib/product-fulfillment';
|
||||
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
|
||||
type Product = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -29,8 +45,26 @@ type Product = {
|
||||
carouselUrls?: string[] | null;
|
||||
aromaType: string;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
};
|
||||
|
||||
type FulfillmentFilter = 'ALL' | 'ONLINE' | 'CROSS_CITY' | 'ON_SITE';
|
||||
|
||||
const FULFILLMENT_FILTERS: Array<{ key: FulfillmentFilter; label: string }> = [
|
||||
{ key: 'ALL', label: '全部' },
|
||||
{ key: 'ONLINE', label: '线上' },
|
||||
{ key: 'CROSS_CITY', label: '跨城' },
|
||||
{ key: 'ON_SITE', label: '现场' },
|
||||
];
|
||||
|
||||
function matchFulfillmentFilter(p: Product, filter: FulfillmentFilter): boolean {
|
||||
if (filter === 'ALL') return true;
|
||||
if (filter === 'ONLINE') return canBuyOnline(p);
|
||||
if (filter === 'CROSS_CITY') return canCrossCity(p);
|
||||
return canPickupOnSite(p);
|
||||
}
|
||||
|
||||
type MiniHomeConfig = {
|
||||
banners: string[];
|
||||
footerUrl: string | null;
|
||||
@@ -38,17 +72,30 @@ type MiniHomeConfig = {
|
||||
|
||||
const AROMA_TABS = [
|
||||
{ key: 'QINGXIANG', label: '清香型' },
|
||||
{ key: 'NONGXIANG', label: '浓香型' },
|
||||
{ key: 'JIANGXIANG', label: '酱香型' },
|
||||
{ key: 'NONGXIANG', label: '浓香型' },
|
||||
] as const;
|
||||
|
||||
type AromaKey = (typeof AROMA_TABS)[number]['key'];
|
||||
|
||||
/** sticky 香型导航高度(与 CSS 大致一致),锚点滚动时预留 */
|
||||
const AROMA_NAV_OFFSET_PX = 44;
|
||||
|
||||
function aromaSectionId(key: AromaKey) {
|
||||
return `aroma-section-${key}`;
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const [tab, setTab] = useState('QINGXIANG');
|
||||
const [activeAroma, setActiveAroma] = useState<AromaKey>('QINGXIANG');
|
||||
const [fulfillmentFilter, setFulfillmentFilter] = useState<FulfillmentFilter>('ALL');
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [displayCity, setDisplayCity] = useState('郑州市');
|
||||
const [cityCode, setCityCode] = useState('410100');
|
||||
const [miniHome, setMiniHome] = useState<MiniHomeConfig>({ banners: [], footerUrl: null });
|
||||
const scrollingToRef = useRef<AromaKey | null>(null);
|
||||
const scrollLockTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastScrollSyncAtRef = useRef(0);
|
||||
|
||||
const loadMiniHome = useCallback(() => {
|
||||
return request<{ miniHome?: MiniHomeConfig }>('/common/client-config')
|
||||
@@ -67,31 +114,60 @@ export default function HomePage() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const applyProductList = useCallback((list: Product[], nextCode: string, authKey: string) => {
|
||||
const normalized = Array.isArray(list) ? list.map((p) => normalizeFulfillmentFlags(p)) : [];
|
||||
setProducts(normalized);
|
||||
setHomeCatalogCache({ cityCode: nextCode, authKey, products: normalized });
|
||||
}, []);
|
||||
|
||||
const fetchProducts = useCallback(
|
||||
(nextCode: string, authKey: string) => {
|
||||
setLoading(true);
|
||||
return request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`)
|
||||
.then((list) => applyProductList(list, nextCode, authKey))
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[applyProductList],
|
||||
);
|
||||
|
||||
/**
|
||||
* 首次进入 / 城市或登录态变化:拉商品。
|
||||
* 同次再切 tab:只同步选中态,不重复请求(对齐门店页)。
|
||||
*/
|
||||
useDidShow(() => {
|
||||
syncTabBarSelected(0);
|
||||
void capturePromoSceneAndTouchScan();
|
||||
void loadMiniHome();
|
||||
void resolveUserCity().then((resolved) => {
|
||||
|
||||
const authKey = getToken() || '';
|
||||
void (async () => {
|
||||
const resolved = await resolveUserCity();
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
setDisplayCity(resolved.displayCity);
|
||||
setCityCode(getCityCodeForCatalog(resolved));
|
||||
});
|
||||
});
|
||||
setCityCode(nextCode);
|
||||
|
||||
const 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]);
|
||||
const cache = getHomeCatalogCache();
|
||||
if (
|
||||
isHomeCatalogBootstrapped() &&
|
||||
cache &&
|
||||
cache.cityCode === nextCode &&
|
||||
cache.authKey === authKey &&
|
||||
Array.isArray(cache.products)
|
||||
) {
|
||||
setProducts(cache.products as Product[]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void loadProducts();
|
||||
}, [loadProducts]);
|
||||
await fetchProducts(nextCode, authKey);
|
||||
})();
|
||||
});
|
||||
|
||||
usePullDownRefresh(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const authKey = getToken() || '';
|
||||
const resolved = await resolveUserCity();
|
||||
setDisplayCity(resolved.displayCity);
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
@@ -101,7 +177,11 @@ export default function HomePage() {
|
||||
request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
|
||||
loadMiniHome(),
|
||||
]);
|
||||
setProducts(Array.isArray(list) ? list : []);
|
||||
applyProductList(
|
||||
Array.isArray(list) ? list : [],
|
||||
nextCode,
|
||||
authKey,
|
||||
);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
@@ -110,22 +190,6 @@ export default function HomePage() {
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
const availableAromas = useMemo(
|
||||
() =>
|
||||
AROMA_TABS.filter((item) =>
|
||||
products.some((product) => product.aromaType === item.key),
|
||||
),
|
||||
[products],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || availableAromas.length === 0) return;
|
||||
if (!availableAromas.some((item) => item.key === tab)) {
|
||||
setTab(availableAromas[0].key);
|
||||
}
|
||||
}, [availableAromas, loading, tab]);
|
||||
|
||||
function openProductDetail(id: string) {
|
||||
Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
|
||||
}
|
||||
@@ -141,7 +205,24 @@ export default function HomePage() {
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
const filtered = products.filter((p) => p.aromaType === tab);
|
||||
const filteredProducts = useMemo(
|
||||
() => products.filter((p) => matchFulfillmentFilter(p, fulfillmentFilter)),
|
||||
[products, fulfillmentFilter],
|
||||
);
|
||||
|
||||
const productsByAroma = useMemo(() => {
|
||||
const map: Record<AromaKey, Product[]> = {
|
||||
QINGXIANG: [],
|
||||
JIANGXIANG: [],
|
||||
NONGXIANG: [],
|
||||
};
|
||||
for (const p of filteredProducts) {
|
||||
const key = p.aromaType as AromaKey;
|
||||
if (key in map) map[key].push(p);
|
||||
}
|
||||
return map;
|
||||
}, [filteredProducts]);
|
||||
|
||||
const banners = miniHome.banners;
|
||||
const footerUrl = miniHome.footerUrl;
|
||||
|
||||
@@ -162,6 +243,102 @@ export default function HomePage() {
|
||||
imageUrl: sharePayload.imgUrl,
|
||||
}));
|
||||
|
||||
function scrollToAroma(key: AromaKey) {
|
||||
setActiveAroma(key);
|
||||
scrollingToRef.current = key;
|
||||
if (scrollLockTimerRef.current) clearTimeout(scrollLockTimerRef.current);
|
||||
scrollLockTimerRef.current = setTimeout(() => {
|
||||
scrollingToRef.current = null;
|
||||
}, 450);
|
||||
|
||||
const query = Taro.createSelectorQuery();
|
||||
query.select(`#${aromaSectionId(key)}`).boundingClientRect();
|
||||
query.selectViewport().scrollOffset();
|
||||
query.exec((res) => {
|
||||
const rect = res?.[0] as { top?: number } | undefined;
|
||||
const viewport = res?.[1] as { scrollTop?: number } | undefined;
|
||||
if (rect?.top == null || viewport?.scrollTop == null) return;
|
||||
const scrollTop = Math.max(0, viewport.scrollTop + rect.top - AROMA_NAV_OFFSET_PX);
|
||||
void Taro.pageScrollTo({ scrollTop, duration: 280 });
|
||||
});
|
||||
}
|
||||
|
||||
usePageScroll(() => {
|
||||
if (scrollingToRef.current) return;
|
||||
const now = Date.now();
|
||||
if (now - lastScrollSyncAtRef.current < 80) return;
|
||||
lastScrollSyncAtRef.current = now;
|
||||
const query = Taro.createSelectorQuery();
|
||||
AROMA_TABS.forEach((t) => {
|
||||
query.select(`#${aromaSectionId(t.key)}`).boundingClientRect();
|
||||
});
|
||||
query.exec((rects) => {
|
||||
if (!Array.isArray(rects) || rects.length === 0) return;
|
||||
let next: AromaKey = AROMA_TABS[0].key;
|
||||
for (let i = 0; i < AROMA_TABS.length; i++) {
|
||||
const rect = rects[i] as { top?: number } | null;
|
||||
if (!rect || rect.top == null) continue;
|
||||
// 区块顶进入导航下方一带时视为当前香型
|
||||
if (rect.top <= AROMA_NAV_OFFSET_PX + 24) {
|
||||
next = AROMA_TABS[i].key;
|
||||
}
|
||||
}
|
||||
setActiveAroma((prev) => (prev === next ? prev : next));
|
||||
});
|
||||
});
|
||||
|
||||
function renderProductCard(p: Product) {
|
||||
const thumb = getProductMainImage(p);
|
||||
const spec = p.subtitle || p.spec || '';
|
||||
return (
|
||||
<View key={p.id} className="home-product-card">
|
||||
<View className="home-product-card-inner" onClick={() => openProductDetail(p.id)}>
|
||||
<View className="home-product-thumb-wrap">
|
||||
{thumb ? (
|
||||
<Image className="home-product-thumb" src={thumb} mode="aspectFill" />
|
||||
) : (
|
||||
<View className="home-product-thumb home-product-thumb--empty" />
|
||||
)}
|
||||
</View>
|
||||
<View className="home-product-main">
|
||||
<View className="home-product-row">
|
||||
<Text className="home-product-name">{p.name}</Text>
|
||||
<Text className="home-product-price">¥{Number(p.price).toFixed(0)}</Text>
|
||||
</View>
|
||||
{spec ? <Text className="home-product-sub">{spec}</Text> : null}
|
||||
<View className="home-product-footer">
|
||||
<CouponBadge amount={p.benefitDisplay ?? p.price} label="好客权益" />
|
||||
</View>
|
||||
<View className="home-product-actions">
|
||||
{canPickupOnSite(p) ? (
|
||||
<Text
|
||||
className="home-pickup-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
void goOnSitePickup(p.id);
|
||||
}}
|
||||
>
|
||||
现场取货
|
||||
</Text>
|
||||
) : null}
|
||||
{canBuyOnline(p) ? (
|
||||
<Text
|
||||
className="home-buy-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
openProductDetail(p.id);
|
||||
}}
|
||||
>
|
||||
立即购买
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell variant="tab" className="home-page no-tab-header">
|
||||
<WechatShareReady payload={sharePayload} />
|
||||
@@ -187,11 +364,11 @@ export default function HomePage() {
|
||||
|
||||
<View className="home-aroma-nav">
|
||||
<View className="home-aroma-tabs">
|
||||
{availableAromas.map((t) => (
|
||||
{AROMA_TABS.map((t) => (
|
||||
<Text
|
||||
key={t.key}
|
||||
className={`home-aroma-tab${tab === t.key ? ' home-aroma-tab--active' : ''}`}
|
||||
onClick={() => setTab(t.key)}
|
||||
className={`home-aroma-tab${activeAroma === t.key ? ' home-aroma-tab--active' : ''}`}
|
||||
onClick={() => scrollToAroma(t.key)}
|
||||
>
|
||||
{t.label}
|
||||
</Text>
|
||||
@@ -200,61 +377,38 @@ export default function HomePage() {
|
||||
<Text className="home-aroma-city">{displayCity}</Text>
|
||||
</View>
|
||||
|
||||
<View className="home-fulfillment-filters">
|
||||
{FULFILLMENT_FILTERS.map((f) => (
|
||||
<Text
|
||||
key={f.key}
|
||||
className={`home-fulfillment-chip${fulfillmentFilter === f.key ? ' home-fulfillment-chip--active' : ''}`}
|
||||
onClick={() => setFulfillmentFilter(f.key)}
|
||||
>
|
||||
{f.label}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
|
||||
<View className="home-product-list">
|
||||
{loading ? <View className="home-empty">加载中…</View> : null}
|
||||
{!loading && products.length === 0 ? (
|
||||
<View className="home-empty">当前城市暂无在售商品</View>
|
||||
) : null}
|
||||
{!loading &&
|
||||
filtered.map((p) => {
|
||||
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">
|
||||
{p.allowOnSitePickup ? (
|
||||
<Text
|
||||
className="home-pickup-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
void goOnSitePickup(p.id);
|
||||
}}
|
||||
>
|
||||
现场取货
|
||||
</Text>
|
||||
{!loading && products.length > 0 && filteredProducts.length === 0 ? (
|
||||
<View className="home-empty">暂无符合履约方式的商品</View>
|
||||
) : null}
|
||||
<Text
|
||||
className="home-buy-btn"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation?.();
|
||||
openProductDetail(p.id);
|
||||
}}
|
||||
>
|
||||
立即购买
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
{!loading &&
|
||||
filteredProducts.length > 0 &&
|
||||
AROMA_TABS.map((t) => {
|
||||
const list = productsByAroma[t.key];
|
||||
return (
|
||||
<View key={t.key} id={aromaSectionId(t.key)} className="home-aroma-section">
|
||||
<Text className="home-aroma-section-title">{t.label}</Text>
|
||||
{list.length === 0 ? (
|
||||
<View className="home-empty home-empty--section">该香型暂未上线</View>
|
||||
) : (
|
||||
list.map((p) => renderProductCard(p))
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -23,32 +23,38 @@ import {
|
||||
} from '../../lib/mini-wechat-profile';
|
||||
import { isLoggedIn, logout, request, toast, type UserProfile } from '../../lib/api';
|
||||
import { isWechatEnv } from '../../lib/weixin';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
toWeappShareMessage,
|
||||
} from '../../lib/wechat-share';
|
||||
import iconPendingPay from '../../assets/icons/待付款.png';
|
||||
import iconPaid from '../../assets/icons/已付款.png';
|
||||
import iconCompleted from '../../assets/icons/已完成.png';
|
||||
import iconAddress from '../../assets/icons/地址管理.png';
|
||||
import iconStores from '../../assets/icons/可用门店.png';
|
||||
import iconCs from '../../assets/icons/联系客服.png';
|
||||
import iconQualification from '../../assets/icons/资质公示.png';
|
||||
import iconAbout from '../../assets/icons/关于我们.png';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const ORDER_SHORTCUTS = [
|
||||
{ tab: 'pending_pay', icon: '付', label: '待付款' },
|
||||
{ tab: 'paid', icon: '包', label: '已付款' },
|
||||
{ tab: 'completed', icon: '成', label: '已完成' },
|
||||
{ tab: 'pending_pay', icon: iconPendingPay, label: '待付款' },
|
||||
{ tab: 'paid', icon: iconPaid, label: '已付款' },
|
||||
{ tab: 'completed', icon: iconCompleted, label: '已完成' },
|
||||
] as const;
|
||||
|
||||
const SERVICES = [
|
||||
{ icon: '址', label: '地址管理', url: '/pages/addresses/index' },
|
||||
{ icon: '店', label: '可用门店', tab: '/pages/stores/index' },
|
||||
{ icon: '服', label: '联系客服', url: '/pages/customer-service/index' },
|
||||
{ icon: '资', label: '资质公示', action: 'qualification' as const },
|
||||
{ icon: '关', label: '关于我们', action: 'about' as const },
|
||||
{ icon: iconAddress, label: '地址管理', url: '/pages/addresses/index' },
|
||||
{ icon: iconStores, label: '可用门店', tab: '/pages/stores/index' },
|
||||
{ icon: iconCs, label: '联系客服', url: '/pages/customer-service/index' },
|
||||
{ icon: iconQualification, label: '资质公示', action: 'qualification' as const },
|
||||
{ icon: iconAbout, label: '关于我们', action: 'about' as const },
|
||||
] as const;
|
||||
|
||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export default function MinePage() {
|
||||
const [authed, setAuthed] = useState(() => isLoggedIn());
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||
@@ -212,7 +218,10 @@ export default function MinePage() {
|
||||
|
||||
/** 点击头像:绑定账号后用 chooseAvatar + nickname 获取头像昵称 */
|
||||
async function handleAvatarTap() {
|
||||
if (bindingWx || savingProfile) return;
|
||||
if (bindingWx || savingProfile) {
|
||||
toast(savingProfile ? '资料保存中…' : '请稍候…');
|
||||
return;
|
||||
}
|
||||
if (!isLoggedIn()) {
|
||||
goLogin('/pages/mine/index');
|
||||
return;
|
||||
@@ -341,13 +350,15 @@ export default function MinePage() {
|
||||
const nickname = display.nickname || '用户';
|
||||
const needProfileFill = isWeapp && needsWxProfileFill(display);
|
||||
const avatarProfileReady = isWeapp ? !needProfileFill : hasWechat;
|
||||
const memberLabel = needProfileFill
|
||||
const maskedPhone = profile?.phone ? maskPhone(String(profile.phone)) : '';
|
||||
// 昵称下优先展示脱敏手机号;无手机号时再提示完善资料/授权
|
||||
const memberLabel =
|
||||
maskedPhone ||
|
||||
(needProfileFill
|
||||
? '点击头像完善资料'
|
||||
: isWeapp || hasWechat
|
||||
? '好客会员'
|
||||
: canWxAuth
|
||||
: !isWeapp && !hasWechat && canWxAuth
|
||||
? '点击头像授权'
|
||||
: '好客会员';
|
||||
: '未绑定手机');
|
||||
const avatarClickable = isWeapp || (!hasWechat && canWxAuth);
|
||||
const previewAvatar = draftAvatarUrl || display.avatarUrl;
|
||||
|
||||
@@ -411,7 +422,7 @@ export default function MinePage() {
|
||||
<Text className="mine-card-title">我的资产</Text>
|
||||
<Text
|
||||
className="mine-card-link"
|
||||
onClick={() => Taro.switchTab({ url: '/pages/benefit/index' })}
|
||||
onClick={() => Taro.navigateTo({ url: '/pages/benefit-detail/index' })}
|
||||
>
|
||||
查看明细 ›
|
||||
</Text>
|
||||
@@ -455,7 +466,7 @@ export default function MinePage() {
|
||||
}
|
||||
>
|
||||
<View className="mine-order-icon">
|
||||
<Text>{item.icon}</Text>
|
||||
<Image className="mine-order-icon-img" src={item.icon} mode="aspectFit" />
|
||||
</View>
|
||||
{count > 0 ? (
|
||||
<Text className="mine-order-badge">{count > 99 ? '99+' : count}</Text>
|
||||
@@ -479,7 +490,7 @@ export default function MinePage() {
|
||||
onClick={() => handleService(item)}
|
||||
>
|
||||
<View className="mine-service-icon">
|
||||
<Text>{item.icon}</Text>
|
||||
<Image className="mine-service-icon-img" src={item.icon} mode="aspectFit" />
|
||||
</View>
|
||||
<Text className="mine-service-label">{item.label}</Text>
|
||||
</View>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { goLogin } from '../../lib/auth-nav';
|
||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||
import { request } from '../../lib/api';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
|
||||
type PreviewProduct = {
|
||||
@@ -75,7 +75,14 @@ export default function OrderConfirmPickupPage() {
|
||||
const canSubmit = !!preview && quantityOk && !loading && !previewLoading;
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < minQty) return;
|
||||
if (next < minQty) {
|
||||
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
}
|
||||
|
||||
@@ -95,9 +102,13 @@ export default function OrderConfirmPickupPage() {
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit) {
|
||||
if (!quantityOk) setMsg(`现场提货至少购买 ${minQty} 瓶`);
|
||||
if (!quantityOk) {
|
||||
const tip = `现场提货至少购买 ${minQty} 瓶`;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=${quantity}`;
|
||||
|
||||
@@ -185,8 +196,8 @@ export default function OrderConfirmPickupPage() {
|
||||
<Text>购买数量</Text>
|
||||
<View className="order-qty-controls">
|
||||
<View
|
||||
className={`order-qty-btn${quantity <= minQty ? ' order-qty-btn--disabled' : ''}`}
|
||||
onClick={() => updateQuantity(Math.max(minQty, quantity - 1))}
|
||||
className="order-qty-btn"
|
||||
onClick={() => updateQuantity(quantity - 1)}
|
||||
>
|
||||
<Text>−</Text>
|
||||
</View>
|
||||
|
||||
@@ -9,7 +9,8 @@ import { tryGetClientGpsLocation } from '../../lib/client-location';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
import { fetchUserProfile } from '../../lib/pay-wechat';
|
||||
import { request } from '../../lib/api';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { canCrossCity, isCrossCityAddress } from '../../lib/product-fulfillment';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
|
||||
type Address = {
|
||||
@@ -31,6 +32,8 @@ type PreviewProduct = {
|
||||
price: number;
|
||||
mainImageUrl?: string | null;
|
||||
carouselUrls?: string[] | null;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
};
|
||||
|
||||
type OrderPreview = {
|
||||
@@ -41,12 +44,18 @@ type OrderPreview = {
|
||||
freightPayType: 'COD' | null;
|
||||
payAmount: number;
|
||||
benefitAmount: number;
|
||||
city?: { localMinQty: number; crossMinQty: number };
|
||||
city?: { name?: string; localMinQty: number; crossMinQty: number };
|
||||
quantityOk?: boolean;
|
||||
quantityMessage?: string | null;
|
||||
addressOk?: boolean;
|
||||
addressMessage?: string | null;
|
||||
minQty?: number;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
};
|
||||
|
||||
const CROSS_CITY_BLOCK_MSG = '该商品不支持跨城配送,请更换为开城城市内的收货地址';
|
||||
|
||||
function formatAddress(a: Address) {
|
||||
return `${a.province}${a.city}${a.district}${a.detail}`;
|
||||
}
|
||||
@@ -64,6 +73,7 @@ export default function OrderConfirmPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
const phonePromptSkipped = useRef(false);
|
||||
const toastedAddressBlockRef = useRef('');
|
||||
|
||||
useEffect(() => {
|
||||
request<Address[]>('/user/addresses')
|
||||
@@ -94,7 +104,24 @@ export default function OrderConfirmPage() {
|
||||
.then((data) => {
|
||||
if (!cancelled) {
|
||||
setPreview(data);
|
||||
setMsg(data.quantityOk === false ? (data.quantityMessage || '') : '');
|
||||
const nextMsg =
|
||||
data.addressOk === false
|
||||
? data.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||
: data.quantityOk === false
|
||||
? data.quantityMessage || ''
|
||||
: '';
|
||||
setMsg(nextMsg);
|
||||
if (
|
||||
data.addressOk === false &&
|
||||
addressId &&
|
||||
toastedAddressBlockRef.current !== addressId
|
||||
) {
|
||||
toastedAddressBlockRef.current = addressId;
|
||||
toast(data.addressMessage || CROSS_CITY_BLOCK_MSG);
|
||||
}
|
||||
if (data.addressOk !== false) {
|
||||
toastedAddressBlockRef.current = '';
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
@@ -117,16 +144,40 @@ export default function OrderConfirmPage() {
|
||||
[addresses, addressId],
|
||||
);
|
||||
|
||||
const isCross = forceCross || preview?.deliveryType === 'CROSS_CITY';
|
||||
const allowCross =
|
||||
preview?.allowCrossCityDelivery !== undefined
|
||||
? canCrossCity({ allowCrossCityDelivery: preview.allowCrossCityDelivery })
|
||||
: canCrossCity(preview?.product ?? {});
|
||||
const localCross =
|
||||
!!selectedAddress &&
|
||||
isCrossCityAddress(selectedAddress.city, preview?.city?.name);
|
||||
const isCross =
|
||||
forceCross || preview?.deliveryType === 'CROSS_CITY' || localCross;
|
||||
const crossBlocked = isCross && !allowCross;
|
||||
const addressOk = preview ? preview.addressOk !== false && !crossBlocked : !crossBlocked;
|
||||
const minQty =
|
||||
preview?.minQty ??
|
||||
(isCross ? (preview?.city?.crossMinQty ?? 6) : (preview?.city?.localMinQty ?? 2));
|
||||
const quantityOk = preview ? preview.quantityOk !== false && quantity >= minQty : false;
|
||||
const canSubmit = !!addressId && !!preview && quantityOk && !loading && !previewLoading;
|
||||
const canSubmit =
|
||||
!!addressId && !!preview && quantityOk && addressOk && !loading && !previewLoading;
|
||||
|
||||
const addressHint = !addressOk
|
||||
? preview?.addressMessage || CROSS_CITY_BLOCK_MSG
|
||||
: '';
|
||||
|
||||
function updateQuantity(next: number) {
|
||||
if (next < minQty) {
|
||||
const tip = isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`;
|
||||
toast(tip);
|
||||
setMsg(tip);
|
||||
if (next < 1) return;
|
||||
setQuantity(next);
|
||||
return;
|
||||
}
|
||||
setQuantity(next);
|
||||
}
|
||||
|
||||
async function doSubmit() {
|
||||
@@ -162,12 +213,18 @@ export default function OrderConfirmPage() {
|
||||
setMsg('请选择收货地址');
|
||||
return;
|
||||
}
|
||||
if (!addressOk) {
|
||||
const tip = addressHint || CROSS_CITY_BLOCK_MSG;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
return;
|
||||
}
|
||||
if (!quantityOk) {
|
||||
setMsg(
|
||||
isCross
|
||||
const tip = isCross
|
||||
? `跨城配送至少购买 ${minQty} 瓶(1箱)`
|
||||
: `同城配送至少购买 ${minQty} 瓶`,
|
||||
);
|
||||
: `同城配送至少购买 ${minQty} 瓶`;
|
||||
setMsg(tip);
|
||||
toast(tip);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -219,9 +276,12 @@ export default function OrderConfirmPage() {
|
||||
? '提交中…'
|
||||
: !addressId
|
||||
? '请选择地址'
|
||||
: !addressOk
|
||||
? '请更换地址'
|
||||
: !quantityOk
|
||||
? `至少购买 ${minQty} 瓶`
|
||||
: '提交订单';
|
||||
const displayMsg = msg || addressHint;
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="order-confirm-page" hasFixedFooter>
|
||||
@@ -254,7 +314,13 @@ export default function OrderConfirmPage() {
|
||||
)}
|
||||
</View>
|
||||
|
||||
{isCross ? (
|
||||
{!addressOk && addressId ? (
|
||||
<View className="order-card order-card--warn">
|
||||
<Text className="order-warn-text">{addressHint || CROSS_CITY_BLOCK_MSG}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{isCross && addressOk ? (
|
||||
<View className="order-card">
|
||||
<Text className="u-muted">
|
||||
该地址超出同城配送范围,将由总部物流发货,运费到付
|
||||
@@ -286,7 +352,7 @@ export default function OrderConfirmPage() {
|
||||
<Text>购买数量</Text>
|
||||
<View className="order-qty-controls">
|
||||
<View
|
||||
className={`order-qty-btn${quantity <= 1 ? ' order-qty-btn--disabled' : ''}`}
|
||||
className="order-qty-btn"
|
||||
onClick={() => updateQuantity(quantity - 1)}
|
||||
>
|
||||
<Text>−</Text>
|
||||
@@ -333,9 +399,9 @@ export default function OrderConfirmPage() {
|
||||
{!previewLoading && !preview && productId ? (
|
||||
<View className="u-empty">无法加载商品信息</View>
|
||||
) : null}
|
||||
{msg ? (
|
||||
<Text className="u-muted" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
||||
{msg}
|
||||
{displayMsg ? (
|
||||
<Text className="order-warn-text" style={{ display: 'block', marginTop: 8, textAlign: 'center' }}>
|
||||
{displayMsg}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
import Taro, { useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, { useDidShow, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
@@ -9,6 +9,7 @@ import ContactCsButton from '../../components/ContactCsButton';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -43,6 +44,7 @@ type OrderDetail = {
|
||||
isProxyOrder?: boolean;
|
||||
proxyPartnerName?: string | null;
|
||||
items?: OrderItem[];
|
||||
wechatConfirm?: WechatConfirmPayload | null;
|
||||
};
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
@@ -82,6 +84,14 @@ export default function OrderDetailPage() {
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [orderId]);
|
||||
|
||||
useDidShow(() => {
|
||||
if (!orderId) return;
|
||||
// 从微信确认收货组件返回后刷新
|
||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||
.then(setOrder)
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
const isReship = !!order?.originOrderId;
|
||||
const isProxy = !!order && (order.isProxyOrder || order.orderType === 'PROXY');
|
||||
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
||||
@@ -127,7 +137,9 @@ export default function OrderDetailPage() {
|
||||
|
||||
const { confirm } = await Taro.showModal({
|
||||
title: '确认收货?',
|
||||
content: '请确认已收到商品。确认后订单将完成,好客权益可正常使用。',
|
||||
content: isWeapp
|
||||
? '将打开微信确认收货,完成后订单即完结,无需再点服务通知。'
|
||||
: '请确认已收到商品。确认后订单将完成,好客权益可正常使用。',
|
||||
confirmText: '确认收货',
|
||||
cancelText: '再想想',
|
||||
});
|
||||
@@ -135,12 +147,19 @@ export default function OrderDetailPage() {
|
||||
|
||||
setConfirming(true);
|
||||
try {
|
||||
const updated = await request<OrderDetail>(`/trade/orders/${order.id}/confirm-receive`, {
|
||||
method: 'POST',
|
||||
data: {},
|
||||
});
|
||||
const mode = await confirmOrderReceive({
|
||||
orderId: order.id,
|
||||
wechatConfirm: order.wechatConfirm,
|
||||
onLocalSuccess: async () => {
|
||||
const updated = await request<OrderDetail>(`/trade/orders/${order.id}`);
|
||||
setOrder(updated);
|
||||
toast('已确认收货');
|
||||
},
|
||||
});
|
||||
if (mode === 'wechat') {
|
||||
// 回跳后由 App.onShow / 本页 useDidShow 处理
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '确认收货失败');
|
||||
} finally {
|
||||
@@ -161,6 +180,17 @@ export default function OrderDetailPage() {
|
||||
<WechatShareReady payload={sharePayload} />
|
||||
<SubPageHeader
|
||||
title="订单详情"
|
||||
onBack={() => {
|
||||
// 支付完成后 reLaunch 进详情:栈仅一页时 navigateBack 会退出小程序,统一回首页
|
||||
const fromPay = String(router.params.from || '') === 'pay';
|
||||
if (fromPay || Taro.getCurrentPages().length <= 1) {
|
||||
Taro.switchTab({ url: '/pages/home/index' }).catch(() => {
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
});
|
||||
return;
|
||||
}
|
||||
Taro.navigateBack();
|
||||
}}
|
||||
right={<ShareNavButton payload={sharePayload} />}
|
||||
/>
|
||||
<View className="sub-page-body">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { usePullDownRefresh, useRouter } from '@tarojs/taro';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
@@ -15,10 +15,16 @@ const TABS = [
|
||||
{ key: 'completed', label: '已完成' },
|
||||
] as const;
|
||||
|
||||
function orderStatusLabel(tab: string, status?: string): string {
|
||||
if (tab !== 'all') {
|
||||
return TABS.find((t) => t.key === tab)?.label || status || '';
|
||||
/** 兼容历史链接 tab=done */
|
||||
function normalizeOrdersTab(raw?: string): string {
|
||||
if (!raw) return 'all';
|
||||
if (raw === 'done') return 'completed';
|
||||
return TABS.some((t) => t.key === raw) ? raw : 'all';
|
||||
}
|
||||
|
||||
function orderStatusLabel(tab: string, status?: string): string {
|
||||
const tabLabel = TABS.find((t) => t.key === tab)?.label;
|
||||
if (tab !== 'all' && tabLabel) return tabLabel;
|
||||
if (!status) return '';
|
||||
return ORDER_STATUS_LABELS[status] || status;
|
||||
}
|
||||
@@ -47,8 +53,7 @@ type OrderRow = {
|
||||
|
||||
export default function OrdersPage() {
|
||||
const router = useRouter();
|
||||
const initialTab = (router.params.tab as string) || 'all';
|
||||
const [tab, setTab] = useState(initialTab);
|
||||
const [tab, setTab] = useState(() => normalizeOrdersTab(router.params.tab as string));
|
||||
const [orders, setOrders] = useState<OrderRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -72,6 +77,12 @@ export default function OrdersPage() {
|
||||
void loadOrders();
|
||||
}, [loadOrders]);
|
||||
|
||||
useDidShow(() => {
|
||||
const next = normalizeOrdersTab(router.params.tab as string);
|
||||
if (next !== tab) setTab(next);
|
||||
else void loadOrders();
|
||||
});
|
||||
|
||||
usePullDownRefresh(() => {
|
||||
void loadOrders().finally(() => Taro.stopPullDownRefresh());
|
||||
});
|
||||
@@ -82,7 +93,14 @@ export default function OrdersPage() {
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="orders-page">
|
||||
<SubPageHeader title="我的订单" />
|
||||
<SubPageHeader
|
||||
title="我的订单"
|
||||
onBack={() => {
|
||||
Taro.switchTab({ url: '/pages/home/index' }).catch(() => {
|
||||
Taro.reLaunch({ url: '/pages/home/index' });
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<View className="order-tabs">
|
||||
{TABS.map((t) => (
|
||||
<Text
|
||||
|
||||
@@ -144,9 +144,10 @@ export default function PayPage() {
|
||||
toast('支付成功', 'success');
|
||||
}
|
||||
if (deliveryType === 'ON_SITE_PICKUP') {
|
||||
Taro.redirectTo({ url: `/pages/pickup-receive/index?id=${orderId}` });
|
||||
// 现场提货支付即完成 → 订单详情;from=pay 返回强制回首页,避免 navigateBack 退出小程序
|
||||
Taro.reLaunch({ url: `/pages/order-detail/index?id=${orderId}&from=pay` });
|
||||
} else {
|
||||
Taro.redirectTo({ url: '/pages/orders/index?tab=paid' });
|
||||
Taro.reLaunch({ url: '/pages/orders/index?tab=paid&from=pay' });
|
||||
}
|
||||
} catch (e) {
|
||||
if (isWechatAuthRequiredError(e)) {
|
||||
|
||||
@@ -5,6 +5,9 @@ import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { getProductMainImage } from '../../lib/product-images';
|
||||
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
||||
|
||||
const isWeapp = process.env.TARO_ENV === 'weapp';
|
||||
|
||||
type OrderDetail = {
|
||||
id: string;
|
||||
@@ -20,10 +23,19 @@ type OrderDetail = {
|
||||
mainImageUrl?: string | null;
|
||||
carouselUrls?: string[] | null;
|
||||
};
|
||||
items?: Array<{
|
||||
productName?: string;
|
||||
productSpec?: string;
|
||||
productImage?: string;
|
||||
quantity?: number;
|
||||
}>;
|
||||
imageUrl?: string | null;
|
||||
mainImageUrl?: string | null;
|
||||
wechatConfirm?: WechatConfirmPayload | null;
|
||||
};
|
||||
|
||||
const ORDERS_ALL_URL = '/pages/orders/index?tab=all';
|
||||
|
||||
export default function PickupReceivePage() {
|
||||
const router = useRouter();
|
||||
const orderId = router.params.id ?? router.params.orderId ?? '';
|
||||
@@ -45,17 +57,33 @@ export default function PickupReceivePage() {
|
||||
});
|
||||
|
||||
async function confirmReceive() {
|
||||
if (!orderId || submitting) return;
|
||||
if (!orderId || !order || submitting) return;
|
||||
|
||||
if (isWeapp) {
|
||||
const { confirm } = await Taro.showModal({
|
||||
title: '确认收货?',
|
||||
content: '将打开微信确认收货,完成后订单即完结,无需再点服务通知。',
|
||||
confirmText: '确认收货',
|
||||
cancelText: '再想想',
|
||||
});
|
||||
if (!confirm) return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await request(`/trade/orders/${orderId}/confirm-receive`, {
|
||||
method: 'POST',
|
||||
data: {},
|
||||
});
|
||||
const mode = await confirmOrderReceive({
|
||||
orderId,
|
||||
wechatConfirm: order.wechatConfirm,
|
||||
onSitePickup: true,
|
||||
redirectUrl: ORDERS_ALL_URL,
|
||||
onLocalSuccess: async () => {
|
||||
toast('确认收货成功', 'success');
|
||||
setTimeout(() => {
|
||||
Taro.redirectTo({ url: '/pages/orders/index?tab=done' });
|
||||
Taro.redirectTo({ url: ORDERS_ALL_URL });
|
||||
}, 500);
|
||||
},
|
||||
});
|
||||
if (mode === 'wechat') return;
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '确认失败');
|
||||
} finally {
|
||||
@@ -63,9 +91,11 @@ export default function PickupReceivePage() {
|
||||
}
|
||||
}
|
||||
|
||||
const name = order?.productName || order?.product?.name || '商品';
|
||||
const spec = order?.productSpec || order?.product?.spec;
|
||||
const item = order?.items?.[0];
|
||||
const name = item?.productName || order?.productName || order?.product?.name || '商品';
|
||||
const spec = item?.productSpec || order?.productSpec || order?.product?.spec;
|
||||
const image =
|
||||
(item?.productImage || '').trim() ||
|
||||
order?.mainImageUrl ||
|
||||
order?.imageUrl ||
|
||||
(order?.product ? getProductMainImage(order.product) : '') ||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { usePageScroll, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
usePageScroll,
|
||||
useRouter,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import type { ProductDetailContentDto } from '@dukang/shared-types';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import PageNavBar from '../../components/PageNavBar';
|
||||
@@ -16,6 +22,11 @@ import {
|
||||
getProductMainImage,
|
||||
type ProductImageSource,
|
||||
} from '../../lib/product-images';
|
||||
import {
|
||||
canBuyOnline,
|
||||
canPickupOnSite,
|
||||
normalizeFulfillmentFlags,
|
||||
} from '../../lib/product-fulfillment';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -31,6 +42,9 @@ type Product = ProductImageSource & {
|
||||
benefitAmount?: number;
|
||||
benefitDisplay?: number;
|
||||
detailContent?: ProductDetailContentDto | null;
|
||||
allowOnSitePickup?: boolean;
|
||||
allowOnlinePurchase?: boolean;
|
||||
allowCrossCityDelivery?: boolean;
|
||||
};
|
||||
|
||||
export default function ProductDetailPage() {
|
||||
@@ -43,13 +57,32 @@ export default function ProductDetailPage() {
|
||||
setHeaderSolid(scrollTop > 100);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const loadProduct = useCallback(() => {
|
||||
if (!productId) return;
|
||||
request<Product>(`/catalog/products/${productId}`)
|
||||
.then(setProduct)
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
request<Product | null>(`/catalog/products/${productId}`)
|
||||
.then((p) => {
|
||||
if (!p) {
|
||||
setProduct(null);
|
||||
toast('商品不存在或暂未开放');
|
||||
return;
|
||||
}
|
||||
setProduct(normalizeFulfillmentFlags(p));
|
||||
})
|
||||
.catch((e) => {
|
||||
setProduct(null);
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
});
|
||||
}, [productId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProduct();
|
||||
}, [loadProduct]);
|
||||
|
||||
// 登录后返回详情须带 token 重拉,否则白名单商品会一直空白
|
||||
useDidShow(() => {
|
||||
loadProduct();
|
||||
});
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => ({
|
||||
title: product?.name || DEFAULT_SHARE_TITLE,
|
||||
@@ -92,6 +125,18 @@ export default function ProductDetailPage() {
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
async function goOnSitePickup() {
|
||||
if (!productId) return;
|
||||
const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=1`;
|
||||
if (!isLoggedIn()) {
|
||||
goLogin(returnPath);
|
||||
return;
|
||||
}
|
||||
const ready = await ensurePayReady(returnPath);
|
||||
if (!ready) return;
|
||||
Taro.navigateTo({ url: returnPath });
|
||||
}
|
||||
|
||||
if (!product) {
|
||||
return (
|
||||
<PageShell variant="scroll" className="product-detail-page">
|
||||
@@ -101,6 +146,8 @@ export default function ProductDetailPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const allowOnline = canBuyOnline(product);
|
||||
const allowOnSite = canPickupOnSite(product);
|
||||
const benefit = Number(product.benefitDisplay ?? product.benefitAmount ?? product.price);
|
||||
const carouselImages = getProductCarouselImages(product);
|
||||
const detailImages = getProductDetailImages(product);
|
||||
@@ -199,9 +246,21 @@ export default function ProductDetailPage() {
|
||||
<Image className="product-detail-bar-home-icon" src={iconHome} mode="aspectFit" />
|
||||
<Text className="product-detail-bar-home-label">首页</Text>
|
||||
</View>
|
||||
{allowOnSite ? (
|
||||
<View className="product-detail-pickup-btn" onClick={() => void goOnSitePickup()}>
|
||||
<Text className="product-detail-pickup-btn-text">现场取货</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{allowOnline ? (
|
||||
<View className="product-detail-buy-btn" onClick={() => void goBuy()}>
|
||||
<Text className="product-detail-buy-btn-text">立即购买</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{!allowOnline && !allowOnSite ? (
|
||||
<View className="product-detail-buy-btn product-detail-buy-btn--disabled">
|
||||
<Text className="product-detail-buy-btn-text">暂不可购</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</PageShell>
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import PageShell from '../../components/PageShell';
|
||||
import RedeemQrCode from '../../components/RedeemQrCode';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const POLL_INTERVAL_MS = 2500;
|
||||
const LAST_REDEEM_RECORD_KEY = 'lastRedeemRecordId';
|
||||
@@ -26,10 +27,6 @@ type RedeemTokenStatus =
|
||||
}
|
||||
| { status: 'EXPIRED' };
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
function formatTimer(seconds: number) {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
@@ -44,6 +41,20 @@ export default function RedeemCodePage() {
|
||||
const [timerSec, setTimerSec] = useState(REDEEM_TOKEN_TTL_SECONDS);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const successHandled = useRef(false);
|
||||
const lastTokenTapAt = useRef(0);
|
||||
|
||||
function onTokenTap() {
|
||||
if (!token) return;
|
||||
const now = Date.now();
|
||||
if (now - lastTokenTapAt.current < 350) {
|
||||
lastTokenTapAt.current = 0;
|
||||
void Taro.setClipboardData({ data: token })
|
||||
.then(() => toast('核销码编号已复制', 'success'))
|
||||
.catch(() => toast('复制失败'));
|
||||
return;
|
||||
}
|
||||
lastTokenTapAt.current = now;
|
||||
}
|
||||
|
||||
const stopTimer = useCallback(() => {
|
||||
if (timerRef.current != null) {
|
||||
@@ -144,9 +155,10 @@ export default function RedeemCodePage() {
|
||||
<Text className="u-muted">待核销金额</Text>
|
||||
<Text className="redeem-code-amount">¥ {formatMoney(amount)}</Text>
|
||||
{token ? (
|
||||
<View className="redeem-code-token-wrap">
|
||||
<View className="redeem-code-token-wrap" onClick={onTokenTap}>
|
||||
<Text className="redeem-code-token-label">核销码编号(供追查)</Text>
|
||||
<Text className="redeem-code-token">{token}</Text>
|
||||
<Text className="redeem-code-token-hint">双击复制</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { View, Text } from '@tarojs/components';
|
||||
import Taro, { useRouter } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
const LAST_REDEEM_RESULT_KEY = 'lastRedeemResult';
|
||||
|
||||
@@ -15,12 +18,43 @@ type RedeemRecord = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
/** 与权益「历史记录」一致:2026-08-03 13:53:03(Asia/Shanghai) */
|
||||
function formatChinaDateTime(input?: string | null) {
|
||||
return formatShanghaiDateTime(input ?? new Date());
|
||||
}
|
||||
|
||||
function StarRating({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
onChange: (score: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="redeem-rating-row">
|
||||
<Text className="redeem-rating-label">{label}</Text>
|
||||
<View className="redeem-star-row">
|
||||
{[1, 2, 3, 4, 5].map((score) => (
|
||||
<Text
|
||||
key={score}
|
||||
className={`redeem-star-btn${score <= value ? ' redeem-star-btn--active' : ''}`}
|
||||
onClick={() => onChange(score)}
|
||||
>
|
||||
★
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RedeemSuccessPage() {
|
||||
const router = useRouter();
|
||||
const [serviceScore, setServiceScore] = useState(5);
|
||||
const [envScore, setEnvScore] = useState(5);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const record = useMemo<RedeemRecord | null>(() => {
|
||||
try {
|
||||
@@ -34,18 +68,51 @@ export default function RedeemSuccessPage() {
|
||||
const amount = Number(record?.amount ?? router.params.amount ?? 0);
|
||||
const storeName = record?.storeName || '门店';
|
||||
const redeemNo = record?.redeemNo || '—';
|
||||
const redeemedAt = record?.createdAt
|
||||
? new Date(record.createdAt).toLocaleString('zh-CN')
|
||||
: new Date().toLocaleString('zh-CN');
|
||||
const redeemedAt = formatChinaDateTime(record?.createdAt);
|
||||
|
||||
function clearCache() {
|
||||
try {
|
||||
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function goBenefit() {
|
||||
Taro.removeStorageSync(LAST_REDEEM_RESULT_KEY);
|
||||
clearCache();
|
||||
Taro.switchTab({ url: '/pages/benefit/index' });
|
||||
}
|
||||
|
||||
function goHome() {
|
||||
clearCache();
|
||||
Taro.switchTab({ url: '/pages/home/index' });
|
||||
}
|
||||
|
||||
async function submitRatingAndFinish() {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (record?.id) {
|
||||
await request('/redeem/ratings', {
|
||||
method: 'POST',
|
||||
data: {
|
||||
redeemRecordId: record.id,
|
||||
serviceScore,
|
||||
envScore,
|
||||
},
|
||||
});
|
||||
toast('评价已提交', 'success');
|
||||
}
|
||||
} catch {
|
||||
/* 评价失败不阻塞返回 */
|
||||
} finally {
|
||||
setLoading(false);
|
||||
goBenefit();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="redeem-success-page">
|
||||
<SubPageHeader title="核销成功" />
|
||||
<SubPageHeader title="核销成功" onBack={goBenefit} />
|
||||
<View className="sub-page-body">
|
||||
<View className="redeem-success-icon">
|
||||
<Text>✓</Text>
|
||||
@@ -69,14 +136,21 @@ export default function RedeemSuccessPage() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="redeem-submit" onClick={goBenefit}>
|
||||
<Text>返回权益</Text>
|
||||
<View className="redeem-success-rating">
|
||||
<Text className="redeem-success-rating-title">为门店服务评分</Text>
|
||||
<StarRating label="服务态度" value={serviceScore} onChange={setServiceScore} />
|
||||
<StarRating label="用餐环境" value={envScore} onChange={setEnvScore} />
|
||||
</View>
|
||||
|
||||
<View
|
||||
className="u-btn u-btn--ghost u-btn--block"
|
||||
style={{ margin: '0 20px', boxSizing: 'border-box' }}
|
||||
onClick={() => Taro.switchTab({ url: '/pages/home/index' })}
|
||||
className={`redeem-submit${loading ? ' redeem-submit--disabled' : ''}`}
|
||||
onClick={() => {
|
||||
if (!loading) void submitRatingAndFinish();
|
||||
}}
|
||||
>
|
||||
<Text>{loading ? '提交中…' : '提交评价并返回'}</Text>
|
||||
</View>
|
||||
<View className="redeem-cancel-btn" onClick={goHome}>
|
||||
<Text>回到首页</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -5,6 +5,7 @@ import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
import { isLoggedIn, request, toast } from '../../lib/api';
|
||||
import { formatMoney } from '../../lib/money';
|
||||
|
||||
type BenefitSummary = {
|
||||
totalBalance: number;
|
||||
@@ -13,10 +14,6 @@ type BenefitSummary = {
|
||||
|
||||
const MIN_REDEEM_AMOUNT = 0.01;
|
||||
|
||||
function formatMoney(amount: number) {
|
||||
return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
/**
|
||||
* 核销金额输入清洗:
|
||||
* - 只保留数字与一个小数点
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { usePageScroll, useRouter, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import Taro, {
|
||||
useDidShow,
|
||||
useLoad,
|
||||
usePageScroll,
|
||||
useRouter,
|
||||
useShareAppMessage,
|
||||
useShareTimeline,
|
||||
} from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import PageNavBar from '../../components/PageNavBar';
|
||||
import ProductCarousel from '../../components/ProductCarousel';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -43,6 +52,13 @@ type Store = {
|
||||
category?: { name: string } | null;
|
||||
};
|
||||
|
||||
type RecentRedeem = {
|
||||
userLabel: string;
|
||||
amount: number | string;
|
||||
createdAt: string;
|
||||
text?: string;
|
||||
};
|
||||
|
||||
function uniqueUrls(urls: Array<string | null | undefined>) {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
@@ -68,30 +84,145 @@ function fullAddress(store: Store) {
|
||||
return `${store.province || ''}${city}${store.district || ''}${store.address || ''}`.trim();
|
||||
}
|
||||
|
||||
function pickStoreId(raw?: string | null) {
|
||||
return String(raw || '')
|
||||
.trim()
|
||||
.replace(/[^\d]/g, '');
|
||||
}
|
||||
|
||||
/** 与历史记录一致:2026-08-03 15:14:30(Asia/Shanghai) */
|
||||
function formatRedeemTime(input?: string | null) {
|
||||
return formatShanghaiDateTime(input);
|
||||
}
|
||||
|
||||
function formatRedeemAmountYuan(amount: number | string) {
|
||||
const n = typeof amount === 'number' ? amount : Number(amount);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
if (Math.abs(n - Math.round(n)) < 1e-9) return String(Math.round(n));
|
||||
return n.toFixed(2).replace(/\.?0+$/, '');
|
||||
}
|
||||
|
||||
function formatRecentRedeemLine(row: RecentRedeem) {
|
||||
try {
|
||||
// 优先用服务端拼好的 text,避免客户端时区 / Intl 差异
|
||||
if (row.text?.trim()) return row.text.trim();
|
||||
const label = String(row.userLabel || '用户***').trim() || '用户***';
|
||||
const rawTime = String(row.createdAt || '').trim();
|
||||
const time =
|
||||
/^\d{4}-\d{2}-\d{2}/.test(rawTime)
|
||||
? rawTime.slice(0, 19).replace('T', ' ')
|
||||
: formatRedeemTime(row.createdAt);
|
||||
const amount = formatRedeemAmountYuan(row.amount);
|
||||
return `${label} ${time} 核销${amount}元`;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRecentRedeems(payload: unknown): RecentRedeem[] {
|
||||
try {
|
||||
if (Array.isArray(payload)) return payload as RecentRedeem[];
|
||||
if (payload && typeof payload === 'object') {
|
||||
const list =
|
||||
(payload as { list?: unknown; items?: unknown; data?: unknown }).list ??
|
||||
(payload as { items?: unknown }).items ??
|
||||
(payload as { data?: unknown }).data;
|
||||
if (Array.isArray(list)) return list as RecentRedeem[];
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export default function StoreDetailPage() {
|
||||
const router = useRouter();
|
||||
const storeId = router.params.id ?? '';
|
||||
const [storeId, setStoreId] = useState(() => pickStoreId(router.params.id));
|
||||
const [store, setStore] = useState<Store | null>(null);
|
||||
const [recentRedeems, setRecentRedeems] = useState<RecentRedeem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [headerSolid, setHeaderSolid] = useState(false);
|
||||
const storeRef = useRef<Store | null>(null);
|
||||
storeRef.current = store;
|
||||
|
||||
usePageScroll(({ scrollTop }) => {
|
||||
setHeaderSolid(scrollTop > 100);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!storeId) return;
|
||||
request<Store>(`/stores/${storeId}`)
|
||||
.then(setStore)
|
||||
.catch(() => {
|
||||
request<Store[]>('/stores')
|
||||
.then((list) => {
|
||||
const found = (Array.isArray(list) ? list : []).find((s) => s.id === storeId);
|
||||
if (found) setStore(found);
|
||||
else toast('门店不存在');
|
||||
})
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
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(() => {
|
||||
const fromRouter = pickStoreId(router.params.id);
|
||||
if (fromRouter && fromRouter !== storeId) {
|
||||
bootstrap(fromRouter);
|
||||
}
|
||||
}, [router.params.id, storeId, bootstrap]);
|
||||
|
||||
// 登录态变化后回到本页:重拉详情与走马灯
|
||||
useDidShow(() => {
|
||||
const id = pickStoreId(storeId || router.params.id);
|
||||
if (!id) return;
|
||||
void loadStore(id);
|
||||
void loadRecentRedeems(id);
|
||||
});
|
||||
}, [storeId]);
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => {
|
||||
@@ -106,6 +237,11 @@ export default function StoreDetailPage() {
|
||||
[store, storeId],
|
||||
);
|
||||
|
||||
const marqueeLines = useMemo(
|
||||
() => recentRedeems.map(formatRecentRedeemLine).filter(Boolean),
|
||||
[recentRedeems],
|
||||
);
|
||||
|
||||
useShareAppMessage(() => toWeappShareMessage(sharePayload));
|
||||
useShareTimeline(() => ({
|
||||
title: sharePayload.title || DEFAULT_SHARE_TITLE,
|
||||
@@ -161,7 +297,9 @@ export default function StoreDetailPage() {
|
||||
return (
|
||||
<PageShell variant="scroll" className="store-detail-page">
|
||||
<PageNavBar title="门店详情" solid onBack={goBack} />
|
||||
<View className="page-with-nav-bar u-empty">加载中…</View>
|
||||
<View className="page-with-nav-bar u-empty">
|
||||
{loading ? '加载中…' : loadError || '门店不存在或暂不可见'}
|
||||
</View>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -245,6 +383,12 @@ export default function StoreDetailPage() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{marqueeLines.length > 0 ? (
|
||||
<View className="store-detail-marquee-wrap">
|
||||
<StoreRedeemMarquee key={marqueeLines.join('|')} lines={marqueeLines} />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{intro ? (
|
||||
<View className="store-detail-section">
|
||||
<Text className="store-detail-section-title">门店详情</Text>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image, Input } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
@@ -27,7 +27,14 @@ import {
|
||||
} from '../../lib/user-location';
|
||||
import { FALLBACK_CITY_CODE } from '../../lib/product-images';
|
||||
import { formatDistanceMeters } from '../../lib/geo';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { getToken, request, toast } from '../../lib/api';
|
||||
import {
|
||||
getStoresListCache,
|
||||
isStoresSessionBootstrapped,
|
||||
markStoresSessionBootstrapped,
|
||||
patchStoresFilterCache,
|
||||
setStoresListCache,
|
||||
} from '../../lib/stores-session';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
DEFAULT_SHARE_TITLE,
|
||||
@@ -55,20 +62,49 @@ type Store = {
|
||||
distanceMeters?: number | null;
|
||||
};
|
||||
|
||||
function makeCityKey(region: Pick<RegionSelection, 'province' | 'city'>): string {
|
||||
return `${region.province}|${region.city}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位城市若未开城,接口会 fallback 到郑州 cityCode;
|
||||
* 筛选器必须与真实拉取城市一致,否则列表被客户端滤空。
|
||||
*/
|
||||
function regionForCatalogFetch(resolved: {
|
||||
openCity: boolean;
|
||||
cityCode?: string;
|
||||
region: RegionSelection;
|
||||
}): { cityCode: string; region: RegionSelection } {
|
||||
const cityCode = getCityCodeForCatalog(resolved);
|
||||
if (resolved.openCity && resolved.cityCode) {
|
||||
return { cityCode, region: toCityWideRegion(resolved.region) };
|
||||
}
|
||||
return { cityCode: FALLBACK_CITY_CODE, region: toCityWideRegion(DEFAULT_REGION) };
|
||||
}
|
||||
|
||||
export default function StoresPage() {
|
||||
const [stores, setStores] = useState<Store[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [keywordInput, setKeywordInput] = useState('');
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [region, setRegion] = useState<RegionSelection>(DEFAULT_REGION);
|
||||
const cached = getStoresListCache();
|
||||
const [stores, setStores] = useState<Store[]>(() => (cached?.items as Store[] | undefined) ?? []);
|
||||
const [loading, setLoading] = useState(() => !cached && !isStoresSessionBootstrapped());
|
||||
const [keywordInput, setKeywordInput] = useState(() => cached?.keywordInput ?? '');
|
||||
const [keyword, setKeyword] = useState(() => cached?.keyword ?? '');
|
||||
const [region, setRegion] = useState<RegionSelection>(
|
||||
() => cached?.filterRegion ?? cached?.listRegion ?? DEFAULT_REGION,
|
||||
);
|
||||
const [regionOpen, setRegionOpen] = useState(false);
|
||||
const [category, setCategory] = useState<CategorySelection>(EMPTY_CATEGORY);
|
||||
const [category, setCategory] = useState<CategorySelection>(
|
||||
() => cached?.category ?? EMPTY_CATEGORY,
|
||||
);
|
||||
const [categoryOpen, setCategoryOpen] = useState(false);
|
||||
const [categoryTree, setCategoryTree] = useState<StoreCategoryNode[]>([]);
|
||||
const [cityCode, setCityCode] = useState<string>(FALLBACK_CITY_CODE);
|
||||
const [userCoords, setUserCoords] = useState<UserCoords | null>(() => readCachedUserCoords());
|
||||
const [locating, setLocating] = useState(false);
|
||||
const fetchCityKeyRef = useRef<string | null>(cached?.cityKey ?? null);
|
||||
const fetchSeqRef = useRef(0);
|
||||
const regionRef = useRef(region);
|
||||
regionRef.current = region;
|
||||
const regionLabel = formatRegionLabel(region);
|
||||
const categoryLabel = formatCategoryLabel(category);
|
||||
const showBootLoading = loading && stores.length === 0;
|
||||
|
||||
const childIdsByParent = useMemo(() => {
|
||||
const map = new Map<string, string[]>();
|
||||
@@ -81,13 +117,118 @@ export default function StoresPage() {
|
||||
return map;
|
||||
}, [categoryTree]);
|
||||
|
||||
async function fetchStores(
|
||||
nextCode: string,
|
||||
coords: UserCoords | null,
|
||||
cityKey: string,
|
||||
listRegion: RegionSelection,
|
||||
/** 写入会话的筛选器;默认保留用户当前选择 */
|
||||
filterRegion: RegionSelection = regionRef.current,
|
||||
) {
|
||||
const seq = ++fetchSeqRef.current;
|
||||
const qs = new URLSearchParams();
|
||||
if (nextCode) qs.set('cityCode', nextCode);
|
||||
if (coords) {
|
||||
qs.set('lat', String(coords.latitude));
|
||||
qs.set('lng', String(coords.longitude));
|
||||
}
|
||||
const path = qs.toString() ? `/stores?${qs}` : '/stores';
|
||||
try {
|
||||
const list = await request<Store[]>(path);
|
||||
if (seq !== fetchSeqRef.current) return;
|
||||
const items = Array.isArray(list) ? list : [];
|
||||
setStores(items);
|
||||
fetchCityKeyRef.current = cityKey;
|
||||
const prev = getStoresListCache();
|
||||
setStoresListCache({
|
||||
cityKey,
|
||||
cityCode: nextCode,
|
||||
authKey: getToken() || '',
|
||||
listRegion: toCityWideRegion(listRegion),
|
||||
items,
|
||||
filterRegion,
|
||||
keyword: prev?.keyword ?? keyword,
|
||||
keywordInput: prev?.keywordInput ?? keywordInput,
|
||||
category: prev?.category ?? category,
|
||||
});
|
||||
} catch (e) {
|
||||
if (seq !== fetchSeqRef.current) return;
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
if (seq === fetchSeqRef.current) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次进入:弹窗 + 定位 + 拉列表。
|
||||
* 同次再切回:只同步 tab 选中态(登录态未变)。
|
||||
* 登录/退出后 token 变化:按缓存失效重新拉列表(白名单)。
|
||||
*/
|
||||
useDidShow(() => {
|
||||
syncTabBarSelected(1);
|
||||
void resolveUserCity().then((resolved) => {
|
||||
setRegion(toCityWideRegion(resolved.region));
|
||||
setCityCode(getCityCodeForCatalog(resolved));
|
||||
setUserCoords(readCachedUserCoords());
|
||||
});
|
||||
|
||||
const authKey = getToken() || '';
|
||||
const cache = getStoresListCache();
|
||||
if (isStoresSessionBootstrapped()) {
|
||||
if (cache && (cache.authKey ?? '') === authKey) {
|
||||
return;
|
||||
}
|
||||
// 登录态变了:保留筛选,重新拉列表
|
||||
void (async () => {
|
||||
setLoading(true);
|
||||
const nextCode = cache?.cityCode || FALLBACK_CITY_CODE;
|
||||
const listRegion = cache?.listRegion
|
||||
? {
|
||||
province: cache.listRegion.province,
|
||||
city: cache.listRegion.city,
|
||||
district: cache.listRegion.district || '全部',
|
||||
}
|
||||
: regionRef.current;
|
||||
const nextCityKey = cache?.cityKey || makeCityKey(listRegion);
|
||||
await fetchStores(
|
||||
nextCode,
|
||||
readCachedUserCoords(),
|
||||
nextCityKey,
|
||||
listRegion,
|
||||
regionRef.current,
|
||||
);
|
||||
})();
|
||||
return;
|
||||
}
|
||||
markStoresSessionBootstrapped();
|
||||
|
||||
void (async () => {
|
||||
const { confirm } = await Taro.showModal({
|
||||
title: '获取当前位置',
|
||||
content: '是否允许获取当前位置来搜索附近门店?拒绝后将按默认城市展示,可下拉刷新重新定位。',
|
||||
confirmText: '允许',
|
||||
cancelText: '暂不',
|
||||
}).catch(() => ({ confirm: false, cancel: true }));
|
||||
|
||||
if (confirm) {
|
||||
setLoading(true);
|
||||
const resolved = await resolveUserCity(true);
|
||||
const { cityCode, region: nextRegion } = regionForCatalogFetch(resolved);
|
||||
const nextCityKey = makeCityKey(nextRegion);
|
||||
setRegion(nextRegion);
|
||||
regionRef.current = nextRegion;
|
||||
await fetchStores(
|
||||
cityCode,
|
||||
readCachedUserCoords(),
|
||||
nextCityKey,
|
||||
nextRegion,
|
||||
nextRegion,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextRegion = toCityWideRegion(DEFAULT_REGION);
|
||||
const nextCityKey = makeCityKey(nextRegion);
|
||||
setRegion(nextRegion);
|
||||
regionRef.current = nextRegion;
|
||||
setLoading(true);
|
||||
await fetchStores(FALLBACK_CITY_CODE, null, nextCityKey, nextRegion, nextRegion);
|
||||
})();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -96,49 +237,29 @@ export default function StoresPage() {
|
||||
.catch(() => setCategoryTree([]));
|
||||
}, []);
|
||||
|
||||
const loadStores = useCallback(() => {
|
||||
setLoading(true);
|
||||
const qs = new URLSearchParams();
|
||||
if (cityCode) qs.set('cityCode', cityCode);
|
||||
const coords = userCoords ?? readCachedUserCoords();
|
||||
if (coords) {
|
||||
qs.set('lat', String(coords.latitude));
|
||||
qs.set('lng', String(coords.longitude));
|
||||
}
|
||||
const path = qs.toString() ? `/stores?${qs}` : '/stores';
|
||||
return request<Store[]>(path)
|
||||
.then((list) => setStores(Array.isArray(list) ? list : []))
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [cityCode, userCoords]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadStores();
|
||||
}, [loadStores]);
|
||||
|
||||
usePullDownRefresh(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const resolved = await resolveUserCity(true);
|
||||
setRegion(toCityWideRegion(resolved.region));
|
||||
const nextCode = getCityCodeForCatalog(resolved);
|
||||
setCityCode(nextCode);
|
||||
const coords = readCachedUserCoords();
|
||||
setUserCoords(coords);
|
||||
const { cityCode, region: nextRegion } = regionForCatalogFetch(resolved);
|
||||
const nextCityKey = makeCityKey(nextRegion);
|
||||
setRegion(nextRegion);
|
||||
regionRef.current = nextRegion;
|
||||
if (fetchCityKeyRef.current !== nextCityKey) {
|
||||
setStores([]);
|
||||
setLoading(true);
|
||||
const qs = new URLSearchParams();
|
||||
if (nextCode) qs.set('cityCode', nextCode);
|
||||
if (coords) {
|
||||
qs.set('lat', String(coords.latitude));
|
||||
qs.set('lng', String(coords.longitude));
|
||||
}
|
||||
const path = qs.toString() ? `/stores?${qs}` : '/stores';
|
||||
const list = await request<Store[]>(path);
|
||||
setStores(Array.isArray(list) ? list : []);
|
||||
await fetchStores(
|
||||
cityCode,
|
||||
readCachedUserCoords(),
|
||||
nextCityKey,
|
||||
nextRegion,
|
||||
nextRegion,
|
||||
);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
} finally {
|
||||
Taro.stopPullDownRefresh();
|
||||
}
|
||||
})();
|
||||
@@ -165,7 +286,9 @@ export default function StoresPage() {
|
||||
});
|
||||
|
||||
function applySearch() {
|
||||
setKeyword(keywordInput.trim());
|
||||
const next = keywordInput.trim();
|
||||
setKeyword(next);
|
||||
patchStoresFilterCache({ keyword: next, keywordInput });
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
@@ -173,6 +296,49 @@ export default function StoresPage() {
|
||||
setKeyword('');
|
||||
setCategory(EMPTY_CATEGORY);
|
||||
setRegion(DEFAULT_REGION);
|
||||
regionRef.current = DEFAULT_REGION;
|
||||
patchStoresFilterCache({
|
||||
keyword: '',
|
||||
keywordInput: '',
|
||||
category: EMPTY_CATEGORY,
|
||||
filterRegion: DEFAULT_REGION,
|
||||
});
|
||||
}
|
||||
|
||||
async function locateToUserRegion() {
|
||||
if (locating) return;
|
||||
const { confirm } = await Taro.showModal({
|
||||
title: '获取当前位置',
|
||||
content: '是否允许获取当前位置,并将筛选定位到您所在的城市与区县?',
|
||||
confirmText: '允许',
|
||||
cancelText: '暂不',
|
||||
}).catch(() => ({ confirm: false, cancel: true }));
|
||||
if (!confirm) return;
|
||||
|
||||
setLocating(true);
|
||||
setLoading(true);
|
||||
try {
|
||||
const resolved = await resolveUserCity(true);
|
||||
// 筛选器用真实省市+区县;拉数仍按开城 cityCode(未开城则郑州)
|
||||
const filterRegion = resolved.region;
|
||||
const { cityCode, region: listRegion } = regionForCatalogFetch(resolved);
|
||||
const nextCityKey = makeCityKey(listRegion);
|
||||
setRegion(filterRegion);
|
||||
regionRef.current = filterRegion;
|
||||
await fetchStores(
|
||||
cityCode,
|
||||
readCachedUserCoords(),
|
||||
nextCityKey,
|
||||
listRegion,
|
||||
filterRegion,
|
||||
);
|
||||
toast(`已定位到${formatRegionLabel(filterRegion)}`, 'success');
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : '定位失败');
|
||||
setLoading(false);
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
}
|
||||
|
||||
function formatHours(store: Store) {
|
||||
@@ -226,16 +392,32 @@ export default function StoresPage() {
|
||||
<Text className="store-filter-chip-text">{categoryLabel}</Text>
|
||||
<Text className="store-filter-chip-arrow">▾</Text>
|
||||
</View>
|
||||
<Text className="store-filter-reset" onClick={resetFilters}>
|
||||
重置
|
||||
</Text>
|
||||
<View
|
||||
className="store-filter-icon-btn"
|
||||
onClick={resetFilters}
|
||||
aria-label="重置筛选"
|
||||
>
|
||||
{/* 小程序 View 伪元素不稳定,用 Text 保证真机可见 */}
|
||||
<Text className="store-filter-icon-glyph">↺</Text>
|
||||
</View>
|
||||
<View
|
||||
className={`store-filter-icon-btn${locating ? ' store-filter-icon-btn--busy' : ''}`}
|
||||
onClick={() => {
|
||||
void locateToUserRegion();
|
||||
}}
|
||||
aria-label="获取当前位置"
|
||||
>
|
||||
<Text className="store-filter-icon-glyph">⌖</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="store-list">
|
||||
{loading ? <View className="u-empty">加载中…</View> : null}
|
||||
{!loading && filtered.length === 0 ? <View className="u-empty">暂无营业中门店</View> : null}
|
||||
{!loading &&
|
||||
{showBootLoading ? <View className="u-empty">加载中…</View> : null}
|
||||
{!showBootLoading && filtered.length === 0 ? (
|
||||
<View className="u-empty">暂无营业中门店</View>
|
||||
) : null}
|
||||
{!showBootLoading &&
|
||||
filtered.map((s) => (
|
||||
<View
|
||||
key={s.id}
|
||||
@@ -282,14 +464,21 @@ export default function StoresPage() {
|
||||
value={region}
|
||||
levels={3}
|
||||
onClose={() => setRegionOpen(false)}
|
||||
onConfirm={(next) => setRegion(next)}
|
||||
onConfirm={(next) => {
|
||||
setRegion(next);
|
||||
regionRef.current = next;
|
||||
patchStoresFilterCache({ filterRegion: next });
|
||||
}}
|
||||
/>
|
||||
<CategoryPicker
|
||||
open={categoryOpen}
|
||||
tree={categoryTree}
|
||||
value={category}
|
||||
onClose={() => setCategoryOpen(false)}
|
||||
onConfirm={(next) => setCategory(next)}
|
||||
onConfirm={(next) => {
|
||||
setCategory(next);
|
||||
patchStoresFilterCache({ category: next });
|
||||
}}
|
||||
/>
|
||||
</PageShell>
|
||||
);
|
||||
|
||||
@@ -126,6 +126,13 @@
|
||||
color: var(--color-heritage-red);
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.benefit-hero-logo-img {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.benefit-hero-cta {
|
||||
|
||||
@@ -103,6 +103,30 @@
|
||||
border-bottom-color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.home-fulfillment-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px var(--space-page) 2px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.home-fulfillment-chip {
|
||||
flex-shrink: 0;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--color-subtle-gray);
|
||||
background: rgba(0, 0, 0, 0.04);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.home-fulfillment-chip--active {
|
||||
color: var(--color-heritage-red);
|
||||
background: rgba(179, 38, 30, 0.1);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.home-product-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -110,6 +134,32 @@
|
||||
padding: 8px var(--space-page) 12px;
|
||||
}
|
||||
|
||||
.home-aroma-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
scroll-margin-top: 48px;
|
||||
}
|
||||
|
||||
.home-aroma-section + .home-aroma-section {
|
||||
margin-top: 8px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
|
||||
.home-aroma-section-title {
|
||||
font-family: var(--font-headline);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 22px;
|
||||
color: var(--color-on-surface);
|
||||
padding: 2px 2px 0;
|
||||
}
|
||||
|
||||
.home-empty--section {
|
||||
padding: 16px 0 8px;
|
||||
}
|
||||
|
||||
.home-product-card {
|
||||
background: var(--color-card);
|
||||
border-radius: 12px;
|
||||
|
||||
@@ -10,9 +10,10 @@
|
||||
|
||||
.mine-header {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
padding: 16px var(--space-page) 44px;
|
||||
background: linear-gradient(135deg, #820012 0%, var(--color-heritage-red) 40%, #d4a373 100%);
|
||||
overflow: hidden;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.mine-header-texture {
|
||||
@@ -33,11 +34,12 @@
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
z-index: 1;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.mine-avatar-wrap {
|
||||
position: relative;
|
||||
z-index: 4;
|
||||
flex-shrink: 0;
|
||||
margin-right: 12px;
|
||||
}
|
||||
@@ -160,7 +162,7 @@
|
||||
.mine-main {
|
||||
margin-top: -28px;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
z-index: 1;
|
||||
padding: 0 var(--space-page) 0;
|
||||
}
|
||||
|
||||
@@ -255,16 +257,18 @@
|
||||
.mine-order-icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
background: rgba(166, 29, 36, 0.08);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--color-heritage-red);
|
||||
font-size: 16px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.mine-order-icon-img {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.mine-order-badge {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
@@ -300,18 +304,20 @@
|
||||
}
|
||||
|
||||
.mine-service-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: var(--color-surface-container-low);
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--color-heritage-red);
|
||||
font-size: 14px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.mine-service-icon-img {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.mine-service-label {
|
||||
font-size: 11px;
|
||||
color: var(--color-on-surface);
|
||||
|
||||
@@ -203,7 +203,8 @@
|
||||
height: var(--nav-content-height);
|
||||
line-height: var(--nav-content-height);
|
||||
text-align: center;
|
||||
padding: 0 88px 0 56px;
|
||||
/* 左右等宽留白,避免右侧分享/胶囊导致标题视觉偏左 */
|
||||
padding: 0 max(72px, var(--nav-padding-right, 96px));
|
||||
box-sizing: border-box;
|
||||
opacity: 0;
|
||||
font-family: var(--font-headline);
|
||||
|
||||
@@ -81,6 +81,19 @@
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.order-card--warn {
|
||||
background: rgba(166, 29, 36, 0.06);
|
||||
box-shadow: none;
|
||||
border: 1px solid rgba(166, 29, 36, 0.15);
|
||||
}
|
||||
|
||||
.order-warn-text {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-card-title {
|
||||
display: block;
|
||||
font-family: var(--font-headline);
|
||||
|
||||
@@ -301,6 +301,25 @@
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.product-detail-pickup-btn {
|
||||
flex: 1;
|
||||
height: 48px;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
border: 1px solid var(--color-heritage-red);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.product-detail-pickup-btn-text {
|
||||
color: var(--color-heritage-red);
|
||||
font-family: var(--font-headline);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.product-detail-buy-btn {
|
||||
flex: 1;
|
||||
height: 48px;
|
||||
@@ -312,6 +331,12 @@
|
||||
box-shadow: 0 8px 24px rgba(166, 29, 36, 0.2);
|
||||
}
|
||||
|
||||
.product-detail-buy-btn--disabled {
|
||||
background: #c4c4c4;
|
||||
box-shadow: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.product-detail-buy-btn-text {
|
||||
color: #fff;
|
||||
font-family: var(--font-headline);
|
||||
|
||||
@@ -304,9 +304,19 @@
|
||||
display: block;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 11px;
|
||||
word-break: break-all;
|
||||
color: var(--color-on-surface);
|
||||
line-height: 1.5;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.redeem-code-token-hint {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 11px;
|
||||
color: var(--color-subtle-gray);
|
||||
}
|
||||
|
||||
.redeem-success-icon {
|
||||
@@ -378,6 +388,49 @@
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.redeem-success-rating {
|
||||
margin: 16px var(--space-page) 0;
|
||||
padding: 16px;
|
||||
background: var(--color-card);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.redeem-success-rating-title {
|
||||
display: block;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--color-on-surface);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.redeem-rating-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.redeem-rating-label {
|
||||
font-size: 14px;
|
||||
color: var(--color-on-surface);
|
||||
}
|
||||
|
||||
.redeem-star-row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.redeem-star-btn {
|
||||
font-size: 22px;
|
||||
color: #d0d0d0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.redeem-star-btn--active {
|
||||
color: #f5a623;
|
||||
}
|
||||
|
||||
.ledger-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -127,6 +127,36 @@
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.store-detail-marquee-wrap {
|
||||
margin: 0 var(--space-page) 12px;
|
||||
}
|
||||
|
||||
.store-detail-marquee {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-radius: 8px;
|
||||
background: #fff7f6;
|
||||
border: 1px solid rgba(166, 29, 36, 0.12);
|
||||
overflow: hidden;
|
||||
height: 40px;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.store-detail-marquee-inner {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
margin-top: -10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-detail-marquee-text {
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
color: #a61d24;
|
||||
}
|
||||
|
||||
.store-detail-section {
|
||||
background: var(--color-card);
|
||||
margin: 0 var(--space-page) 16px;
|
||||
|
||||