Compare commits
51 Commits
d6d4a77473
...
v3.5.2
| Author | SHA1 | Date | |
|---|---|---|---|
| ee493823bf | |||
| 8b5bb6a981 | |||
| 0a36188b35 | |||
| 6cf66c722c | |||
| 4db21cf1a1 | |||
| 2f633b307c | |||
| 62353a6800 | |||
| 233ed0af3b | |||
| 7dd5fdfb12 | |||
| 48d6900ab6 | |||
| 5ca9aa00aa | |||
| c0d04ee500 | |||
| 3ac008a217 | |||
| cd1e9ae488 | |||
| 18147e157f | |||
| f7c94b4f16 | |||
| cc750dc1d6 | |||
| 984dec79ee | |||
| f84614bbb4 | |||
| c0ce494732 | |||
| 69e201f927 | |||
| ecd9973d8f | |||
| bbd7e52e70 | |||
| 1c91e6bae9 | |||
| 029fd690a5 | |||
| 0bfc19b1a4 | |||
| bafb342600 | |||
| bac5c7ad80 | |||
| c05cd0e96d | |||
| 8de41796fb | |||
| 4b3b1f76ae | |||
| 75d820b574 | |||
| 0f48d7abda | |||
| 4a0e18472b | |||
| 491f03e825 | |||
| 88053353ab | |||
| ceacce9ed5 | |||
| 3913bf3bf3 | |||
| 478291e2b3 | |||
| 6754caf076 | |||
| 92c3175acf | |||
| 46361ec713 | |||
| 5586ed90cd | |||
| 4cec5b1fe5 | |||
| 07630c9046 | |||
| 4488b0c006 | |||
| 99c74f20d2 | |||
| a598d1cd30 | |||
| da6a38daa4 | |||
| c5926bd593 | |||
| df546ff39f |
@@ -0,0 +1,34 @@
|
||||
---
|
||||
description: 小程序子页不要画与原生导航栏重复的二级 title,标题只用 navigationBarTitleText
|
||||
globs: apps/mini-user/**/*.{tsx,ts}
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# mini-user · 小程序导航标题
|
||||
|
||||
微信小程序已有原生导航栏。页面内再画一层 `SubPageHeader` / 自定义 title,会与原生标题叠成**二级 title**。
|
||||
|
||||
## weapp
|
||||
|
||||
- 页面标题只走 `index.config.ts` 的 `navigationBarTitleText`
|
||||
- **不要**设 `navigationStyle: 'custom'`(除非该页需要完全自定义导航,如滚动透明顶栏、商品详情)
|
||||
- **不要**在页面内再渲染与原生标题重复的 `SubPageHeader`
|
||||
- H5 没有原生导航栏:可保留 `SubPageHeader`(仅返回键;H5 实现已隐藏 title 文案)
|
||||
|
||||
```tsx
|
||||
// ✅ weapp 用原生标题;H5 保留返回栏
|
||||
export default definePageConfig({
|
||||
navigationBarTitleText: '申请发票',
|
||||
});
|
||||
|
||||
{process.env.TARO_ENV === 'h5' ? (
|
||||
<SubPageHeader title="申请发票" onBack={...} />
|
||||
) : null}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ 未配页标题 + 再画一层 SubPageHeader(weapp 会双标题)
|
||||
<SubPageHeader title="申请发票" />
|
||||
```
|
||||
|
||||
弹层/区块标题(如「编辑发票抬头」)不是导航二级 title,可保留。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 2026-08-12 工作记录
|
||||
|
||||
## 杜康好客 · 三项功能需求落地(dev_jacy 分支)
|
||||
|
||||
### 需求1:管理端用户列表增加好客权益金额列
|
||||
- 后端 `server/dukang-api/src/modules/ops/admin-users.service.ts`:
|
||||
- 新增常量 `BENEFIT_STAT_STATUSES = ['ACTIVE','USED_UP']`、`UserBenefitStat` 类型、`EMPTY_BENEFIT_STAT`、`toAmount()`。
|
||||
- `list()` / `detail()` 均调用新增私有方法 `loadBenefitStats(userIds)`,用 `benefitCoupon.groupBy({ by:['userId'], where:{status:{in:[...BENEFIT_STAT_STATUSES]}}, _sum:{totalAmount,usedAmount,balance} })` 批量聚合,避免 N+1。
|
||||
- `mapAdminUserRow` 增加 `benefit` 参数并展开到返回对象。统计口径与 C 端 `listCoupons` 一致(排除 VOID)。
|
||||
- 前端 `apps/admin-web/src/lib/api.ts`:`AdminUserRow` 增加 `benefitTotalAmount?/benefitUsedAmount?/benefitBalance?: number`。
|
||||
- 前端 `apps/admin-web/src/pages/UsersPage.tsx`:新增「剩余权益/已用权益/累计权益」三列(右对齐、可排序,scroll x 改为 1830),详情抽屉 Descriptions 增加「好客权益」项。
|
||||
|
||||
### 需求2:管理端门店入驻合同支持多图上传
|
||||
- 新建共享工具 `server/dukang-api/src/common/store-media/contract-urls.util.ts`:`MAX_CONTRACT_FILES=20`、`normalizeContractUrls(urls?, legacy?)`、`contractMediaType(url)`(.pdf→FILE 否则 IMAGE)。
|
||||
- 后端 `admin-stores.service.ts`:import 上述工具;create(645 行)/ update(451 行)路径由单条 `contractUrl` 改为遍历建立多条 `bizType:'CONTRACT'` 记录(`sortOrder:i`、`mediaType` 按扩展名判定)。
|
||||
- DTO `admin-mutate.dto.ts`:`contractUrl?:string` 标记 `@deprecated`,新增 `contractUrls?:string[]`(`@IsArray @IsString({each:true}) @ArrayMaxSize(20)`)。
|
||||
- 前端 `apps/admin-web/src/lib/storeCreate.ts`:`StoreCreateForm.contractUrl?:string` → `contractUrls?:string[]`。
|
||||
- `MultiImageUpload.tsx`:新增 `isPdf()`、`FilePdfOutlined`、PDF 缩略图卡片、`buttonText` prop。
|
||||
- `StoresPage.tsx`:编辑抽屉 + 创建 step1 表单均改用 `MultiImageUpload`(name=contractUrls, maxCount=20, accept=image/*,.pdf, buttonText="批量上传合同"),回显/保存 payload 改为 `contractUrls:string[]`。
|
||||
|
||||
### 需求3:合伙人 H5 门店入驻合同支持多图上传
|
||||
|
||||
## 发布流水线(同一会话,22:45 后)
|
||||
|
||||
完整跑通 dukang-release 标准流程:`dev_jacy` → push → merge `dev` → merge `main` → 发生产。
|
||||
- 提交 `8805335` feat(ops,store,partner): 用户权益列 + 门店合同多图上传(13 文件,356+/59-)
|
||||
- `dev_jacy` push → `origin/dev_jacy`(8805335)
|
||||
- merge `dev_jacy`→`dev` → `491f03e`,push `origin/dev`
|
||||
- merge `dev`→`main` → `4a0e184`,push `origin/main`
|
||||
- `deploy/deploy-prod.sh -- --skip-db`(无 Prisma schema 变更,故 --skip-db)→ `DEPLOY_EXIT=0`,`==> 发版完成 (production)`
|
||||
- 生产 PM2 全 online:`dukang-api`(8090) / admin-web / h5-partner / h5-shop / h5-user;健康检查 `api:200` `mini-user(h5):200`;版本记录 commit=4a0e184
|
||||
|
||||
### 踩坑/注意
|
||||
- `git checkout main` 时本机工作树出现 `server/dukang-api` 大量 `D`(误删)假象:实为 sandbox 下 checkout 未刷新工作树,非仓库损坏。用 `git checkout -f main` 重新填充即恢复;`origin/main` 始终正确(ls-remote 核对 4a0e184)。
|
||||
- 提交/合并后 `git status` 报 "ahead of origin by N" 为本地 tracking ref 陈旧,非真实分歧(ls-remote 已核对远程三分支均含本次提交)。
|
||||
- 仅提交 13 个需求文件 + 新建 `server/dukang-api/src/common/store-media/`,已排除 `.workbuddy/` 与 `fix_acl.ps1`。
|
||||
- 发布命令在 sandbox 下直接运行 SSH 部署成功(未强制禁用沙箱)。
|
||||
- `apps/h5-partner/src/lib/storeDraft.ts`:`StoreDraftForm.contractUrl:string` → `contractUrls:string[]`;`defaultStoreForm` 改为 `contractUrls:[]`;新增 `MAX_CONTRACT_COUNT=20`;`normalizeStoreDraftForm` 新增 `contractUrls` 计算(兼容旧 `contractUrl` 迁移为数组,去重限 20);`validateStoreStep2` 参数/校验改为 `contractUrls`,不足 1 张返回「请上传签约合同」。
|
||||
- `MultiOssUploadField.tsx`:新增 `accept?`、`unit?` props,`isPdf()`,PDF 缩略图卡片。
|
||||
- `StoreCreatePage.tsx`:签约合同区块 `OssUploadField` → `MultiOssUploadField`(value=`form.contractUrls ?? []`, maxCount=MAX_CONTRACT_COUNT, unit="个", accept="image/*,.pdf");提交体 `contractUrl` → `contractUrls`,新增 `const contractUrls = Array.from(new Set(...)).slice(0, MAX_CONTRACT_COUNT)`;envPhotoUrls slice 上限由 3 改为 20。修正了渲染块误用未定义变量 `contractUrls`(已改为从 form 读取)。
|
||||
|
||||
### 验证
|
||||
- 后端 `npx tsc --noEmit`(server/dukang-api)通过,exit 0。
|
||||
- admin-web / h5-partner 使用 `git stash` 基线对比法:本次改动**未引入任何新类型错误**(现存错误均为预存在基线问题:css module 声明、`import.meta.env`、过期 config 类型、TabLayout `end`、staff `staffRole` 等)。
|
||||
- 向后兼容:旧 `contractUrl` 字段保留并标记 deprecated,H5 草稿旧数据自动迁移;避免破坏现有 API 客户端。
|
||||
@@ -0,0 +1,79 @@
|
||||
# 2026-08-16
|
||||
|
||||
## 新增:线上库同步本地 CLI 工具
|
||||
- 文件:`deploy/sync-prod-db-to-local.sh`(新建,未提交)
|
||||
- 用途:将生产库 `dukang_prod`(阿里云 RDS `rm-bp139andp1aa385i9.mysql.rds.aliyuncs.com:3306`,用户 `dukangadmin`)同步到本地 Docker MySQL `dukang_haoke`(localhost:6016 / 容器内 `dukang-v1-mysql`,root/root)。
|
||||
- 原理:SSH 隧道借道 `dukang-server`(`-L 6018:rds:3306`)→ 本地无 mysql 客户端,故在 `dukang-v1-mysql` 容器内跑 mysqldump/mysql,经 `host.docker.internal:TUNNEL_PORT` 连隧道;管道直导,不落临时文件。
|
||||
- 安全:默认先 `docker exec mysqldump` 备份本地到 `deploy/backups/`;需 `--yes` 跳过交互确认;`--dry-run` 只读远端 DATABASE_URL 并打印计划。
|
||||
- 远端凭据从 `/opt/dukang/server/dukang-api/.env.production` 的 DATABASE_URL 运行时解析(密码经 `MYSQL_PWD` 环境变量传入,避免命令行暴露)。
|
||||
- 已知限制:不支持密码含 `@`;prod DB 名与本地不同(dukang_prod→dukang_haoke)靠 mysqldump 不带 `--databases` 实现库名映射。
|
||||
- 状态:仅跑通 `--dry-run`,未执行真实同步(待用户确认,因会覆盖本地库并拉取生产数据)。
|
||||
|
||||
## 修复:首次同步失败的根因
|
||||
- 失败现象:`mysqldump` 退出码 2,提示 `本地库可能处于不一致状态`(工具自身的失败兜底提示)。
|
||||
- 真实根因有两条:
|
||||
1. **密码解析错误**:生产 DB 密码含 `@` 字符(`passHasAt=true`)。原 bash 解析用「第一个 @」切分 userinfo/host,把密码里 `@` 之后的部分截断,导致 Access denied。
|
||||
修复:改为在服务端用 `new URL()` 解析,base64 回传各字段(user/host/port/db/password),本地 `base64 -d` 还原,彻底免疫 `@`/`:`/`$` 等特殊字符。服务端 auth 测试 `authTestStatus=0` 验证密码正确。
|
||||
2. **权限不足**:`dukangadmin`(应用库用户)无 `RELOAD`/`FLUSH_TABLES` 权限。`--single-transaction` 仍会触发全局 `FLUSH TABLES` → Access denied。
|
||||
修复:`mysqldump` 改用 `--lock-tables=0`(不发起 FTWRL)+ `--set-gtid-purged=OFF`(RDS 启用 GTID,否则本地恢复会报 GTID_PURGED 错误),并保留 `--skip-routines --skip-events --column-statistics=0 --no-tablespaces --add-drop-table --skip-triggers --no-create-db`。
|
||||
- 验证:结构导出(--no-data)在 4 组 flag 中仅 `--lock-tables=0` / `--skip-lock-tables`(不含 --single-transaction)退出 0。
|
||||
- 现工具已修正并实际执行同步(--yes,先自动备份本地到 deploy/backups/)。
|
||||
- 注意:`--lock-tables=0` 无事务一致性快照;生产库在线写入期间导出可能有极小不一致,但恢复时 mysqldump 自带 `FOREIGN_KEY_CHECKS=0`,_dev 库可接受。若需完全一致快照,可给 dukangadmin 授 RELOAD 后用 --single-transaction。
|
||||
|
||||
## 修改:套餐审核导航样式恢复一致
|
||||
- 文件:`apps/admin-web/src/layouts/AdminLayout.tsx` 的 `attachPackageAuditBadge`(`/store-package-audits` 项)。
|
||||
- 诉求演变:用户先要求「文字恒为白色」→ 后改为「不要单独处理,保持与子菜单一致,只是多一个待审徽章图标」。
|
||||
- 最终实现:label 改为 `<span style={{display:'inline-flex',gap:6}}>套餐审核{pendingCount>0 && <Badge count size="small"/>}</span>`。文字无强制颜色,随菜单主题继承 normal/hover/selected 颜色;徽章仅 pendingCount>0 时作为图标提示,不参与着色。
|
||||
|
||||
## 发布流水线(本次收尾,含之前未上线的 8+1 文件)
|
||||
- 背景:此前「联系电话脱敏+套餐多行输入+同步工具」等 9 文件 commit `8de4179` 已 push dev_jacy/dev/main,但**生产发布失败**(deploy.env 丢失导致 `未配置 DEPLOY_HOST`)。
|
||||
- 修复发布:`deploy.env` 是 gitignore 的本地密钥文件,已丢失不可找回;改用 SSH 别名 `dukang-server`(~/.ssh/config:HostName 47.110.129.57 / User root / IdentityFile pem)覆盖:`bash deploy/deploy-prod.sh --host dukang-server -- --skip-db`。
|
||||
- 关键排查:`origin/*` 本地缓存 ref 多次陈旧(误报 ahead/behind),必须以 `git ls-remote` 为准。本次真实远端:dev_jacy=8de4179、dev=c05cd0e、main=bac5c7a,与本地一致,无丢失。
|
||||
- 本次提交:`bafb342` fix(admin) 套餐审核样式 → push dev_jacy → merge dev(`0bfc19b`) → merge main(`029fd69`) → push。
|
||||
- 发布结果:`DEPLOY_EXIT=0`,`==> 发版完成 (production)`,健康检查 api:200 / mini-user(h5):200,系统版本记录 commit `029fd69`。
|
||||
- 提示:以后若想恢复标准 `bash deploy/deploy-prod.sh`(不带 --host),需重建 `deploy/deploy.env`(从 `deploy.env.example` 复制,填入 DEPLOY_HOST=47.110.129.57 等;该文件 gitignore,勿提交)。
|
||||
|
||||
## 排查:h5-partner 本地 /login 调 /partner/me 报 401
|
||||
- 现象:`http://localhost:5176/login` 启动后控制台报 `GET /api/v1/partner/me 401 (Unauthorized)`。
|
||||
- 结论:**不是 bug,是登录页的「过期 token 探测」**。链路:Vite 代理 `/api`→`localhost:3010`(正常);后端返回 `{"code":401,"message":"Missing token"}`(说明后端在线、代理通)。`ensureSession()`(api.ts:244)只在 localStorage 有 token 时才打 `/partner/me`;无 token 直接返回未登录。所以 401 来自之前测试残留的失效 token → 前端静默清除并展示登录表单,不崩、不弹错。刷新页面(token 已清)即不再出现。
|
||||
- 本地登录方式(关键,README 已过期):
|
||||
- `MOCK_SMS=true`(.env),短信走 mock,不连运营商;固定码 `MOCK_SMS_FIXED_CODE` 默认 `999888`(README 写的 123456 已不准)。
|
||||
- README 的测试号 `13700000001` **不在本地同步库**;本地 `partner_account` 共 9 个,可用真实号如 `18049821889`(Jacy) / `13073729990`(queen)(均 ACTIVE)。
|
||||
- 流程:填真实合伙人手机号 → 获取验证码 → **验证码打印在 `pnpm dev:api` 后端终端**(`Mock SMS → 180****8889 code=XXXXXX`)→ 填码登录。
|
||||
- 注意 h5-partner 默认 5175,本次因 5175 被占自动落到 5176,代理是路径匹配不受影响。
|
||||
|
||||
## 发布:v3.4.17 门店套餐审核快捷入口 上生产
|
||||
- 提交 `1c91e6b`(dev_jacy 上,含后端 admin-stores.service.ts + AdminStorePackagesSection/StorePackageAuditsPage/StoresPage 三前端 + 开发计划文档)。
|
||||
- 流水线:直接快进推送(避免 git checkout 工作树不刷新):`git push origin dev_jacy` + `dev_jacy:dev` + `dev_jacy:main`,三分支统一到 `1c91e6b`;本地 `git branch -f dev/main origin/*` 同步。
|
||||
- 部署:`bash deploy/deploy-prod.sh --host dukang-server -- --skip-db`(后端仅给列表响应加字段,无 schema 变更,故 skip-db)。
|
||||
- 结果:`DEPLOY_EXIT=0`,新 tag `v3.4.17`,全部应用构建通过,PM2 重启 dukang-api/h5-shop/h5-partner/admin-web(另拉起 h5-user),健康检查 api:200 / mini-user(h5):200,系统版本记录 commit `1c91e6b`。
|
||||
|
||||
## 发布:v3.4.18 套餐变更对比逐字段列出变动明细
|
||||
- 需求:套餐变更对比「将变动的地方详细列出来」(之前只给「新增/删除/变更/未变」粗粒度标记,不列具体字段)。
|
||||
- 改动仅在 `apps/admin-web/src/pages/StorePackageAuditsPage.tsx`:
|
||||
- 新增 `fieldChanges(live, proposed)`:逐字段比对 价格/套餐名称/菜品内容/可用时间/其他说明/图片,产出 `label+旧值→新值` 明细。
|
||||
- `diffPackages` 给「变更」行附 `changes`。
|
||||
- `PackageDetailCard` 在「待审核」卡片底部渲染「变更明细」块(旧值删除线 → 新值加粗,橙色块)。
|
||||
- 抽屉顶部加「新增 X · 删除 Y · 变更 Z · 未变 W」汇总条。
|
||||
- 提交 `bbd7e52`(feat(admin) 套餐变更对比逐字段列出变动明细),快进推送 dev_jacy/dev/main。
|
||||
- 部署:`bash deploy/deploy-prod.sh --host dukang-server -- --skip-db`(无 schema 变更)。
|
||||
- 结果:构建通过、PM2 重启 admin-web 等、健康检查 api:200 / mini-user(h5):200,系统版本记录 commit `bbd7e52`(无精确 tag,记 tag=-,无害)。
|
||||
- 已知局限:配对按「套餐名称」(空则索引) 位置匹配;若套餐被**改名**,会误判为「删除旧名+新增新名」而非「变更」,故名称变更不会出现在逐字段明细里。
|
||||
|
||||
## 优化:套餐变更对比·逐字差异 + 文档并入 v3.4.17
|
||||
- 需求:变动明细要能**定位到文本中具体哪些字变了(逐字检查)**,且把开发计划文档合并到 v3.4.17 文档里(不再单独留 v3.4.18 文档)。
|
||||
- 代码改动(仍仅 `StorePackageAuditsPage.tsx`):
|
||||
- `diffText(a,b)`:LCS 动态规划 (`dp[i][j]`)+回溯,产出 `equal/delete/insert` 段落并合并相邻同类型;`O(|a|·|b|)`,字段长度可控。
|
||||
- `TextDiff({oldText,newText})`:两行渲染——「原:」红删线标被删字、「新:」绿标新增字。
|
||||
- `FieldChange` 增加 `kind: 'text'|'value'`:价格/图片走 `旧→新`;套餐名称/菜品内容/可用时间/其他说明走 `TextDiff` 逐字高亮。
|
||||
- `杜康好客-v3.4.17-门店套餐审核快捷入口.md` 新增第 F 节「套餐变更对比·逐字段/逐字明细」,并把原先 v3.4.18 的字段级说明并入,删去独立 v3.4.18 文档计划。
|
||||
- 提交 `ecd9973`,快进推送 dev_jacy/dev/main,部署 `--host dukang-server -- --skip-db`。
|
||||
- 结果:构建通过、健康检查 api:200 / mini-user(h5):200,系统版本记录 commit `ecd9973`(tag=-,无害)。
|
||||
- 验证要点:开任一「变更」套餐的待审核卡片 → 底部「变更明细」→ 菜品/说明等文本以红删+绿增逐字呈现。
|
||||
|
||||
## 优化:h5-partner 门店详情·门店套餐「编辑套餐」按钮
|
||||
- 需求:按钮**缩小、靠最右侧、保持美观**。根因:`.partner-btn-outline` 是整行大按钮(`flex:1; height:48px; font-size:16px`),放在卡片标题右侧会被拉伸成大块。
|
||||
- 改动:`apps/h5-partner/src/styles.css` 新增 `.partner-btn-outline--compact`(`flex:none; height:30px; padding:0 14px; font-size:13px; font-weight:500; border-radius:var(--radius-sm); color:var(--color-primary)`,hover 用 `color-mix` 8% 底色);`StoreDetailPage.tsx:288` 的「编辑套餐」按钮加该类(父级 `space-between` 已保证贴右)。
|
||||
- 提交 `69e201f`,快进推送 dev_jacy/dev/main,部署 `--host dukang-server -- --skip-db`。
|
||||
- 结果:构建通过、PM2 重启 h5-partner、健康检查 api:200 / mini-user(h5):200,系统版本记录 commit `69e201f`(tag=-,无害)。
|
||||
- 注意:`StoreDetailPage.tsx:311` 有个历史遗留 TS 错误(`status === 'CLOSED'` 类型无重叠),与本改动无关,未动。
|
||||
@@ -0,0 +1,70 @@
|
||||
# 2026-08-17 工作日志
|
||||
|
||||
## 杜康好客 v3.4.18 门店体验与登录态优化(含 F 项)
|
||||
|
||||
### 已实现并发布
|
||||
- **A** mini-user 门店座机脱敏:改 `apps/mini-user/src/lib/phone.ts` 的 `maskPhone` 座机分支,中间四位 `****`(保留区号+首2+末2)。
|
||||
- **B** 套餐详情图 1/5 计数 + 自动轮播:`ProductCarousel.tsx` detail 变体加 autoplay(3.5s) + 右下角 `1/N` 计数。
|
||||
- **C** 合伙人暂停禁止登录:`auth.service.ts` 三处非 ACTIVE 抛「该账号已暂停使用,请联系客服人员」;`h5-partner/LoginPage.tsx` 同步文案;复用 `DISABLED` 枚举,无迁移。
|
||||
- **D** 门店端提现/筛选栏留白对齐:`h5-shop/styles.css` 补 `--space-page`。
|
||||
- **E** 休息中核销→是否开启营业:`PhoneRedeemPage`/`RedeemConfirmPage` 弹「是否开启营业?」,确认调 `PUT /shop/store/status` 开张后继续。
|
||||
- **F(本次新增)** 门店套餐图片自适应完整显示:`ProductCarousel` 新增 `imageFit="adaptive"`(`mode="widthFix"` + 按真实比例动态算 Swiper 高度),`product-detail.css` 加 `.detail-carousel-wrap--adaptive` 覆盖固定 1:1 裁剪;仅 `store-package-detail` 使用。根因:原 `.detail-carousel-wrap` 固定 `aspect-ratio:1` + `overflow:hidden` + `aspectFill` 裁掉非正方形图。
|
||||
|
||||
### 发布状态
|
||||
- 文档:`杜康好客-v3.4.18-门店体验与登录态优化.md`(含 A–F 范围、实现位置、验收清单)。
|
||||
- git:本地 `dev_jacy` 提交 v3.4.18 各功能 + F 修复;已 `git push origin dev_jacy:main`(干净快进 `984dec7..18147e1`)。
|
||||
- 生产部署:后台运行 `deploy/deploy-prod.sh --host dukang-server`(/opt/dukang, main)。SSH 配置主机 `dukang-server` 即生产机;`deploy.env` 缺失,用 `--host` 覆盖。
|
||||
|
||||
### 注意
|
||||
- 本次 git 发布前曾遇 origin/main 比本地新、working tree 异常删除 503 文件(已 `reset --hard HEAD` 还原,提交完好);最终 fetch 后确认本地领先可快进,安全发布。
|
||||
- 四端 tsc 仅余项目既有环境类报错(CSS 导入/ImportMeta.env),本次改动文件无新增类型错误。
|
||||
|
||||
### F 项方案 A 改写(22:18)
|
||||
- 放弃手算高度逻辑(SelectorQuery + onLoad 测自然宽高),改用 swiper 原生 `autoHeight`:海报有多高轮播就有多高,无裁切。
|
||||
- `ProductCarousel.tsx`:删 `wrapWidth`/`imgHeights`/`handleImageLoad`/`swiperStyle`,adaptive 模式加 `autoHeight={isAdaptive}`,image 保持 `mode="widthFix"`。
|
||||
- `product-detail.css`:`.detail-carousel-wrap--adaptive` 覆盖(删 `aspect-ratio:1`/`overflow:hidden`),并给 `.detail-carousel`/`.detail-carousel-item`/`.detail-carousel-image` 在 adaptive 下 `height:auto`。
|
||||
- 已提交 `cd1e9ae` 并 `git push origin dev_jacy:main`(干净快进 `18147e1..cd1e9ae`)。
|
||||
- 重要:F 是原生微信小程序端改动,服务器部署只覆盖 H5-user 构建;真机小程序用户需经「微信开发者工具上传 + 微信审核」才能生效。
|
||||
|
||||
### E 项缺陷修复(22:46 测试不通过)
|
||||
- **根因**:门店非 OPEN 时,后端 `redeem.service.ts:loadOpenStoreAccount`(previewRedeem/confirmRedeem 共用)抛「门店未营业」,导致 `RedeemConfirmPage` 的 `preview` 拉取失败 → `preview` 为 null → 「确认核销」按钮 `disabled={!preview}` → 点击不了 → 开张弹窗永远不触发。手机号路径因弹窗在「发送验证码」时触发故未暴露。
|
||||
- **修复**:`RedeemConfirmPage` 把 preview 拉取抽成 `loadPreview()`;确认按钮改为 `disabled={loading || (!preview && !storeClosed)}`(闭店时仍可点→弹框);`openStoreAndContinue` 开张成功后 `await loadPreview()` 再 `doConfirm()`。
|
||||
- 弹窗文案对齐需求:「门店目前休息中无法核销,是否开启营业」(两页 modal title=门店休息中 / desc=该句;内联提示改为「门店目前休息中无法核销,开启营业后可继续」)。
|
||||
- 提交 `3ac008a`,`git push origin dev_jacy:main`(快进 `cd1e9ae..3ac008a`),生产重新部署中(deploy-prod.sh --host dukang-server)。
|
||||
- 注意:后端 `updateShopStatus` 对 CLOSED(永久关闭) 门店拒绝开张(抛「门店已永久关闭...」),属预期;需求针对 闭店/休息中(PAUSED) 场景,OK。
|
||||
|
||||
### E 项方案二次修正(23:00 用户纠正:前置到点击扫码)
|
||||
- **用户新要求**:门店 PAUSED 时,**点击「扫码核销」按钮那一刻就弹窗**,而不是扫完码进确认页才弹。
|
||||
- **改动**:`apps/h5-shop/src/pages/HomePage.tsx`(门店端首页)。
|
||||
- 复用 dashboard 已加载的 `status`(`dash?.store?.status`,L384 `status = String(store?.status||'')`)。
|
||||
- `handleScan()` 开头:`if (status !== 'OPEN') { setShowOpenModal(true); return; }` —— 不进入 isWechatEnv/scanQrCode 流程。
|
||||
- 新增 `openStoreAndContinue()`:`PUT /shop/store/status {OPEN}`,成功后 `loadDashboard()` 刷新状态(开关/扫码按钮同步),用户可再次点击扫码。
|
||||
- 弹窗复用全局 `.shop-redeem-modal` 样式(与确认页一致),文案「门店目前休息中无法核销,是否开启营业?」。
|
||||
- `RedeemConfirmPage` 的弹窗保留为带码直入确认页的兜底。
|
||||
- 提交 `c0d04ee`,`git push origin dev_jacy:main`(快进 `3ac008a..c0d04ee`),生产重新部署中(deploy-prod.sh --host dukang-server)。文档 E 节已同步更新方案描述。
|
||||
|
||||
### C 项缺陷修复(合伙人端 DISABLED 仍登录 - 微信路径)
|
||||
- **现象**:手机号(短信)路径已正确拦截(login 前先 `POST /partner/auth/phone/check` 校验非 ACTIVE 即拒),但**微信 OAuth 路径**报错被吞 → 用户无任何提示。
|
||||
- **根因**:`apps/h5-partner/src/contexts/PartnerSessionContext.tsx` L118 `catch { stripOAuthParamsFromLocation(); }` 把微信回调里 `processPartnerWechatOAuthCallback` 抛出的「该账号已暂停使用」错误吞掉。
|
||||
- **修复**:`catch (e) { stripOAuthParamsFromLocation(); toastError(e); }`(`toastError` 从 `@/lib/toast` 引入),让微信登录被暂停时同样弹「该账号已暂停使用,请联系客服人员」。
|
||||
- 提交 `5ca9aa0`,`git push origin dev_jacy:main`(快进 `c0d04ee..5ca9aa0`)。
|
||||
- 生产部署完成(deploy-prod.sh --host dukang-server, 38s):dukang-api 200、各 h5/partner 服务 online。mini-user(h5) 健康检查 FAIL 与本次无关(非 v3.4.18 改动范围,本次改 native 小程序 + h5-shop + h5-partner)。
|
||||
- **验收状态**:A/B/C/D/E/F 全部提交并发布生产;C 项的短信 + 微信两条路径拦截逻辑均已落地,建议真机/微信环境复测一次确认 toast 文案展示。
|
||||
|
||||
### C 项双拦截增强(23:37 用户要求“两个都要拦”)
|
||||
- **澄清**:city 合伙人有两个独立状态字段,别混:
|
||||
- `partner_account.status`(AccountStatus: ACTIVE/DISABLED)= **登录账号启用态**,feature 原拦截查的就是它(子账号自身)。
|
||||
- `partner_account.bindingStatus`(CityPartnerStatus: ACTIVE/PAUSED)= **城市合伙人绑定态**,主账号为准;子账号取父主账号的此字段。
|
||||
- **需求**:子账号 `status=DISABLED` 与 主账号 `bindingStatus=PAUSED` **都要拦**。
|
||||
- **实现**:`auth.service.ts` 新增统一闸门 `assertPartnerAccountActive(account)`(L313),同时拦上述两种;替换三处旧校验:`assertPartnerAccountByPhone`(L334) / `loginPartner`(L1086) / `loginPartnerWechat`(L1748)。
|
||||
- 自身非 ACTIVE → 「该账号已暂停使用,请联系客服人员」
|
||||
- 主账号 bindingStatus 非 ACTIVE → 「该合伙人合作已暂停,请联系客服人员」
|
||||
- **文档**:`杜康好客-v3.4.18-...md` C 节重写为双拦截;顶部范围表 + 验收清单同步。
|
||||
- 提交 `48d6900`,`git push origin dev_jacy:main`(快进 `5ca9aa0..48d6900`),生产部署完成(task I2mWSU, 37s):commit=48d6900、api 200、各服务 online。
|
||||
- **生产实测双拦截均生效**:
|
||||
- `status=DISABLED`(id=7 临时翻转→测试→已还原 ACTIVE):`phone/check` 返回 400「该账号已暂停使用,请联系客服人员」;还原后 201 ok:true。
|
||||
- `bindingStatus=PAUSED`(18049821889 等 3 个主账号):`phone/check` 返回 400「该合伙人合作已暂停,请联系客服人员」(修复前为 200 ok:true)。
|
||||
- 库内 status!=ACTIVE 数量=0;binding_status!=ACTIVE 数量=3(均为主账号 PAUSED)。
|
||||
- **遗留未提交文件(非本次改动,需用户决策)**:
|
||||
- `apps/h5-shop/src/styles.css`:`shop-records-status-chips` 由 `padding:0` → `padding-bottom:10px`(D 项后续微调,未提交)。
|
||||
- `apps/mini-user/src/styles/product-detail.css`:工作区版本把方案A(`aspect-ratio:auto`/`height:auto`)改回固定 4:3(`aspect-ratio:1.33`/`height:100%`),与已上线方案A矛盾,疑似另一轮实验性改动。已与用户确认前**暂不提交**。
|
||||
@@ -139,6 +139,7 @@ C 端门店仅 status=OPEN
|
||||
|
||||
**iOS 微信 H5 JSSDK**:登录/OAuth 后禁止仅 SPA 跳转再调扫码;见 `packages/weixin-sdk/GOTCHAS.md`、知识库「门店端 · 踩坑」。
|
||||
**微信小程序 open-type**:`chooseAvatar` 等 Button 的祖先禁止 `stopPropagation`(会编成 catchtap);见知识库「C 端 · 踩坑」、`.cursor/rules/mini-user-weapp-opentype.mdc`。
|
||||
**微信小程序页面标题**:weapp 只用原生 `navigationBarTitleText`,不要再画一层与导航栏重复的 `SubPageHeader` title;见 `.cursor/rules/mini-user-weapp-nav-title.mdc`。
|
||||
|
||||
## 环境与发版
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.5.1",
|
||||
"@dukang/domain": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"antd": "^5.22.0",
|
||||
|
||||
@@ -5,6 +5,7 @@ import LoginPage from './pages/LoginPage';
|
||||
import DashboardPage from './pages/DashboardPage';
|
||||
import UsersPage from './pages/UsersPage';
|
||||
import OrdersPage from './pages/OrdersPage';
|
||||
import BigScreenPage from './pages/BigScreenPage';
|
||||
import StorePackageAuditsPage from './pages/StorePackageAuditsPage';
|
||||
import StoresPage from './pages/StoresPage';
|
||||
import StoreRatingsPage from './pages/StoreRatingsPage';
|
||||
@@ -65,6 +66,14 @@ export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="/orders/big-screen"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<BigScreenPage />
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
element={
|
||||
<RequireAuth>
|
||||
|
||||
@@ -86,3 +86,656 @@ body,
|
||||
.admin-table-nowrap .ant-table-cell-ellipsis {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin-package-audit-cols {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.admin-package-audit-col {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-package-audit-text {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow: visible;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* v3.5.1 #1 订单大屏:发布会现场 */
|
||||
html:has(.big-screen-page),
|
||||
body:has(.big-screen-page),
|
||||
#root:has(.big-screen-page) {
|
||||
overflow: hidden;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.big-screen-page {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: radial-gradient(ellipse at 50% 18%, #163a6b 0%, #0b1e3a 42%, #061224 100%);
|
||||
color: #d6e8ff;
|
||||
padding: 20px 48px 24px;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.big-screen-stars {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image:
|
||||
radial-gradient(1px 1px at 8% 18%, rgba(255, 255, 255, 0.35), transparent),
|
||||
radial-gradient(1px 1px at 22% 72%, rgba(160, 210, 255, 0.28), transparent),
|
||||
radial-gradient(1.5px 1.5px at 78% 24%, rgba(255, 255, 255, 0.22), transparent),
|
||||
radial-gradient(1px 1px at 91% 68%, rgba(160, 210, 255, 0.3), transparent),
|
||||
radial-gradient(1px 1px at 46% 88%, rgba(255, 255, 255, 0.18), transparent),
|
||||
radial-gradient(1.5px 1.5px at 61% 12%, rgba(160, 210, 255, 0.25), transparent);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.big-screen-frame {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
inset: 14px 18px;
|
||||
}
|
||||
|
||||
.big-screen-corner {
|
||||
position: absolute;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid rgba(105, 192, 255, 0.7);
|
||||
}
|
||||
|
||||
.big-screen-corner--tl {
|
||||
top: 0;
|
||||
left: 0;
|
||||
border-right: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.big-screen-corner--tr {
|
||||
top: 0;
|
||||
right: 0;
|
||||
border-left: none;
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.big-screen-corner--bl {
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
border-right: none;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.big-screen-corner--br {
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
border-left: none;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.big-screen-header {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid rgba(105, 192, 255, 0.18);
|
||||
}
|
||||
|
||||
.big-screen-brand {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.big-screen-title {
|
||||
margin: 0;
|
||||
font-size: 28px;
|
||||
line-height: 1;
|
||||
font-weight: 700;
|
||||
letter-spacing: 4px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.big-screen-subtitle {
|
||||
font-size: 16px;
|
||||
color: rgba(200, 220, 245, 0.55);
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.big-screen-live-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.big-screen-live-label {
|
||||
font-size: 18px;
|
||||
color: rgba(230, 244, 255, 0.88);
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
|
||||
.big-screen-live {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 12px 4px 10px;
|
||||
border: 1px solid rgba(64, 169, 255, 0.7);
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
letter-spacing: 2px;
|
||||
background: rgba(8, 28, 56, 0.55);
|
||||
}
|
||||
|
||||
.big-screen-live-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #ff4d4f;
|
||||
box-shadow: 0 0 8px #ff4d4f;
|
||||
animation: big-screen-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes big-screen-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
transform: scale(0.75);
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-hero {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
text-align: center;
|
||||
padding: 16px 0 12px;
|
||||
}
|
||||
|
||||
.big-screen-clock {
|
||||
font-size: 84px;
|
||||
line-height: 1;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: 10px;
|
||||
color: #9fd3ff;
|
||||
text-shadow: 0 0 28px rgba(105, 192, 255, 0.45);
|
||||
}
|
||||
|
||||
.big-screen-date {
|
||||
margin-top: 8px;
|
||||
font-size: 16px;
|
||||
letter-spacing: 4px;
|
||||
color: rgba(180, 210, 240, 0.65);
|
||||
}
|
||||
|
||||
.big-screen-list {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.big-screen-list-head,
|
||||
.big-screen-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 18%) minmax(0, 1fr) minmax(140px, 16%) minmax(160px, 18%);
|
||||
align-items: center;
|
||||
column-gap: 16px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.big-screen-list-body {
|
||||
flex: 1 1 0%;
|
||||
min-height: 0;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.big-screen-track {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.big-screen-track.is-rolling {
|
||||
animation: big-screen-marquee-up var(--marquee-ms, 20s) linear infinite;
|
||||
}
|
||||
|
||||
.big-screen-track.is-paused {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
@keyframes big-screen-marquee-up {
|
||||
from {
|
||||
transform: translateY(0);
|
||||
}
|
||||
to {
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-row {
|
||||
position: relative;
|
||||
flex: 0 0 auto;
|
||||
height: 68px;
|
||||
margin-bottom: 12px;
|
||||
padding: 0 28px 0 40px;
|
||||
background: rgba(18, 48, 88, 0.45);
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
font-size: 22px;
|
||||
color: #e8f4ff;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.big-screen-row.is-latest {
|
||||
border-color: rgba(64, 169, 255, 0.85);
|
||||
box-shadow: 0 0 16px rgba(24, 144, 255, 0.28);
|
||||
}
|
||||
|
||||
.big-screen-row--t1 {
|
||||
background: rgba(22, 54, 98, 0.48);
|
||||
border-color: rgba(105, 192, 255, 0.16);
|
||||
}
|
||||
|
||||
.big-screen-row--t1 .big-screen-amount {
|
||||
color: #e6f4ff;
|
||||
}
|
||||
|
||||
.big-screen-row--t2.is-latest {
|
||||
border-color: rgba(255, 229, 143, 0.95);
|
||||
box-shadow: 0 0 18px rgba(255, 229, 143, 0.42);
|
||||
}
|
||||
|
||||
.big-screen-row--t3.is-latest {
|
||||
border-color: #ffd666;
|
||||
box-shadow: 0 0 22px rgba(250, 173, 20, 0.55);
|
||||
}
|
||||
|
||||
.big-screen-row--t2 {
|
||||
background: rgba(64, 48, 8, 0.42);
|
||||
border-color: rgba(255, 229, 143, 0.45);
|
||||
color: #fff7d6;
|
||||
}
|
||||
|
||||
.big-screen-row--t2 .big-screen-amount {
|
||||
color: #ffe58f;
|
||||
text-shadow: 0 0 10px rgba(255, 229, 143, 0.45);
|
||||
}
|
||||
|
||||
.big-screen-row--t3 {
|
||||
background: rgba(72, 48, 0, 0.5);
|
||||
border-color: rgba(250, 173, 20, 0.75);
|
||||
color: #ffe7a3;
|
||||
box-shadow: 0 0 18px rgba(250, 173, 20, 0.28);
|
||||
}
|
||||
|
||||
.big-screen-row--t3 .big-screen-amount {
|
||||
color: #ffd666;
|
||||
text-shadow: 0 0 14px rgba(255, 214, 102, 0.7);
|
||||
}
|
||||
|
||||
.big-screen-row-mark {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
top: 50%;
|
||||
width: 10px;
|
||||
height: 22px;
|
||||
margin-top: -11px;
|
||||
border-radius: 6px;
|
||||
background: #40a9ff;
|
||||
box-shadow: 0 0 10px #40a9ff;
|
||||
}
|
||||
|
||||
.big-screen-row--t2 .big-screen-row-mark {
|
||||
background: #ffe58f;
|
||||
box-shadow: 0 0 10px #ffe58f;
|
||||
}
|
||||
|
||||
.big-screen-row--t3 .big-screen-row-mark {
|
||||
background: #ffd666;
|
||||
box-shadow: 0 0 12px #ffd666;
|
||||
}
|
||||
|
||||
.big-screen-amount {
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
letter-spacing: 0.5px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.big-screen-amount--6d {
|
||||
font-size: 0.86em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.big-screen-items {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.big-screen-time,
|
||||
.big-screen-phone {
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: 1px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.big-screen-empty {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
/* 全屏高度黄金分割点(≈0.382),略偏上 */
|
||||
top: 38.2%;
|
||||
transform: translateY(-50%);
|
||||
z-index: 2;
|
||||
text-align: center;
|
||||
color: rgba(145, 190, 230, 0.42);
|
||||
padding: 0 40px;
|
||||
font-size: 60px;
|
||||
letter-spacing: 6px;
|
||||
font-weight: 400;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.big-screen-fx {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
background: rgba(4, 12, 28, 0.38);
|
||||
}
|
||||
|
||||
.big-screen-fx-canvas {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.big-screen-fx-shock {
|
||||
position: absolute;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
border: 3px solid rgba(255, 214, 102, 0.85);
|
||||
animation: big-screen-shock 1.1s ease-out forwards;
|
||||
}
|
||||
|
||||
@keyframes big-screen-shock {
|
||||
0% {
|
||||
transform: scale(0.2);
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
transform: scale(28);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-fx-sweep {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
115deg,
|
||||
transparent 38%,
|
||||
rgba(255, 245, 200, 0.22) 50%,
|
||||
transparent 62%
|
||||
);
|
||||
background-size: 220% 100%;
|
||||
animation: big-screen-sweep 1.4s ease-out 0.15s both;
|
||||
}
|
||||
|
||||
.big-screen-fx-sweep--alt {
|
||||
animation-delay: 0.55s;
|
||||
background: linear-gradient(
|
||||
65deg,
|
||||
transparent 38%,
|
||||
rgba(255, 214, 102, 0.2) 50%,
|
||||
transparent 62%
|
||||
);
|
||||
}
|
||||
|
||||
.big-screen-fx-shock--late {
|
||||
animation-delay: 0.35s;
|
||||
border-color: rgba(255, 236, 179, 0.55);
|
||||
}
|
||||
|
||||
@keyframes big-screen-sweep {
|
||||
from {
|
||||
background-position: 120% 0;
|
||||
opacity: 0;
|
||||
}
|
||||
30% {
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
background-position: -40% 0;
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-fx-card {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
min-width: min(420px, 92vw);
|
||||
max-width: min(920px, 92vw);
|
||||
padding: 28px 40px 32px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
background: rgba(8, 22, 48, 0.82);
|
||||
backdrop-filter: blur(8px);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t1 {
|
||||
border: 2px solid rgba(105, 192, 255, 0.85);
|
||||
box-shadow: 0 0 32px rgba(24, 144, 255, 0.45);
|
||||
animation: big-screen-card-in-t1 0.55s cubic-bezier(0.2, 0.9, 0.2, 1) both;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t2 {
|
||||
border: 2px solid rgba(255, 229, 143, 0.95);
|
||||
box-shadow: 0 0 40px rgba(255, 214, 102, 0.5);
|
||||
animation: big-screen-card-in-t2 0.6s cubic-bezier(0.16, 1.2, 0.3, 1) both;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t3 {
|
||||
min-width: min(560px, 94vw);
|
||||
padding: 36px 48px 40px;
|
||||
border: 3px solid #ffd666;
|
||||
box-shadow:
|
||||
0 0 28px rgba(255, 214, 102, 0.85),
|
||||
0 0 80px rgba(250, 173, 20, 0.45);
|
||||
animation: big-screen-card-in-t3 0.7s cubic-bezier(0.12, 1.4, 0.2, 1) both;
|
||||
}
|
||||
|
||||
@keyframes big-screen-card-in-t1 {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(80px) scale(0.92);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes big-screen-card-in-t2 {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.6);
|
||||
}
|
||||
70% {
|
||||
transform: scale(1.06);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes big-screen-card-in-t3 {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.4) rotate(-4deg);
|
||||
}
|
||||
55% {
|
||||
transform: scale(1.12) rotate(1deg);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1) rotate(0);
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-fx-kicker {
|
||||
font-size: 16px;
|
||||
letter-spacing: 8px;
|
||||
color: rgba(230, 244, 255, 0.7);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t2 .big-screen-fx-kicker,
|
||||
.big-screen-fx-card--t3 .big-screen-fx-kicker {
|
||||
color: #ffe58f;
|
||||
}
|
||||
|
||||
.big-screen-fx-amount {
|
||||
font-size: clamp(44px, 8.5vw, 64px);
|
||||
font-weight: 800;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: 2px;
|
||||
line-height: 1.1;
|
||||
color: #e6f7ff;
|
||||
max-width: 100%;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
.big-screen-fx-amount--6d {
|
||||
font-size: clamp(36px, 7vw, 52px) !important;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t1 .big-screen-fx-amount {
|
||||
color: #91d5ff;
|
||||
text-shadow: 0 0 18px rgba(105, 192, 255, 0.6);
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t2 .big-screen-fx-amount {
|
||||
color: #ffe58f;
|
||||
text-shadow: 0 0 20px rgba(255, 229, 143, 0.7);
|
||||
animation: big-screen-amount-pop 0.8s ease-out 0.15s both;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t3 .big-screen-fx-amount {
|
||||
font-size: clamp(52px, 10vw, 84px);
|
||||
color: #ffd666;
|
||||
text-shadow:
|
||||
0 0 12px #ffd666,
|
||||
0 0 36px rgba(250, 173, 20, 0.8);
|
||||
animation: big-screen-amount-flash 0.9s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.big-screen-fx-card--t3 .big-screen-fx-amount--6d {
|
||||
font-size: clamp(44px, 8.5vw, 68px) !important;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
@keyframes big-screen-amount-pop {
|
||||
0% {
|
||||
transform: scale(0.7);
|
||||
}
|
||||
70% {
|
||||
transform: scale(1.12);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes big-screen-amount-flash {
|
||||
0%,
|
||||
100% {
|
||||
filter: brightness(1);
|
||||
}
|
||||
50% {
|
||||
filter: brightness(1.35);
|
||||
}
|
||||
}
|
||||
|
||||
.big-screen-fx-items {
|
||||
margin-top: 12px;
|
||||
font-size: 22px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.big-screen-fx-meta {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 28px;
|
||||
font-size: 16px;
|
||||
color: rgba(210, 228, 250, 0.75);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.big-screen-clock {
|
||||
font-size: 56px;
|
||||
}
|
||||
.big-screen-row {
|
||||
grid-template-columns: minmax(140px, 20%) minmax(0, 1fr) minmax(110px, 16%) minmax(130px, 18%);
|
||||
font-size: 16px;
|
||||
}
|
||||
.big-screen-amount--6d {
|
||||
font-size: 0.82em;
|
||||
}
|
||||
.big-screen-fx-amount {
|
||||
font-size: clamp(36px, 8vw, 44px);
|
||||
}
|
||||
.big-screen-fx-card--t3 .big-screen-fx-amount {
|
||||
font-size: clamp(40px, 9vw, 56px);
|
||||
}
|
||||
.big-screen-fx-amount--6d {
|
||||
font-size: clamp(32px, 6.5vw, 40px) !important;
|
||||
}
|
||||
.big-screen-fx-card--t3 .big-screen-fx-amount--6d {
|
||||
font-size: clamp(34px, 7vw, 48px) !important;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,12 +1,20 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Alert, Button, Form, Input, InputNumber, Modal, Space, Typography, message } from 'antd';
|
||||
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import type { StorePackageItemDto } from '@dukang/shared-types';
|
||||
import type { StorePackageItemDto, StorePackagesResponse } from '@dukang/shared-types';
|
||||
import { STORE_PACKAGE_IMAGE_MAX_COUNT, STORE_PACKAGE_MAX_COUNT, normalizeStorePackageImageUrls } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
import { PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
||||
import PackageImagesUpload from './PackageImagesUpload';
|
||||
|
||||
type PackageRow = StorePackageItemDto;
|
||||
|
||||
export type AdminStorePackagesHandle = {
|
||||
/** 套餐已加载时写入;加载中则跳过,避免空数据覆盖线上套餐 */
|
||||
saveIfLoaded: (opts?: { quiet?: boolean }) => Promise<{ skipped: boolean }>;
|
||||
};
|
||||
|
||||
function emptyRow(index = 0): PackageRow {
|
||||
return {
|
||||
name: '',
|
||||
@@ -20,16 +28,181 @@ function emptyRow(index = 0): PackageRow {
|
||||
};
|
||||
}
|
||||
|
||||
export default function AdminStorePackagesSection({ storeId }: { storeId: string }) {
|
||||
const [items, setItems] = useState<PackageRow[]>([emptyRow()]);
|
||||
const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId: string }>(
|
||||
function AdminStorePackagesSection({ storeId }, ref) {
|
||||
const [items, setItems] = useState<PackageRow[]>([emptyRow()]);
|
||||
const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [pendingRequest, setPendingRequest] = useState<StorePackagesResponse['pendingRequest']>(null);
|
||||
const itemsRef = useRef(items);
|
||||
const loadingRef = useRef(loading);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
request<{ live: PackageRow[] }>(`/admin/stores/${storeId}/packages`)
|
||||
.then((data) => {
|
||||
useEffect(() => {
|
||||
itemsRef.current = items;
|
||||
}, [items]);
|
||||
|
||||
useEffect(() => {
|
||||
loadingRef.current = loading;
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
setPendingRequest(null);
|
||||
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
||||
.then((data) => {
|
||||
setPendingRequest(data.pendingRequest ?? null);
|
||||
setItems(
|
||||
data.live?.length
|
||||
? data.live.map((p, i) => {
|
||||
const imageUrls = normalizeStorePackageImageUrls(p);
|
||||
return {
|
||||
...p,
|
||||
price: String(p.price),
|
||||
imageUrl: imageUrls[0] ?? '',
|
||||
imageUrls,
|
||||
sortOrder: i,
|
||||
};
|
||||
})
|
||||
: [],
|
||||
);
|
||||
})
|
||||
.catch((e) => message.error(e instanceof Error ? e.message : '加载套餐失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [storeId]);
|
||||
|
||||
// 在审核页完成审核后,自动刷新本页「有待审核套餐」提醒
|
||||
useEffect(() => {
|
||||
const onChanged = () => {
|
||||
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
|
||||
.then((data) => setPendingRequest(data.pendingRequest ?? null))
|
||||
.catch(() => undefined);
|
||||
};
|
||||
window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
||||
return () => window.removeEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
||||
}, [storeId]);
|
||||
|
||||
function goAudit() {
|
||||
if (pendingRequest) navigate(`/store-package-audits?requestId=${pendingRequest.id}`);
|
||||
}
|
||||
|
||||
const pendingReminder =
|
||||
pendingRequest && pendingRequest.status === 'PENDING' ? (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="该门店有待审核套餐"
|
||||
description={
|
||||
<Space>
|
||||
<Button size="small" type="primary" onClick={goAudit}>
|
||||
审核
|
||||
</Button>
|
||||
<Button size="small" onClick={goAudit}>
|
||||
对比
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
function updateAt(index: number, patch: Partial<PackageRow>) {
|
||||
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||
}
|
||||
|
||||
function addRow() {
|
||||
if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
|
||||
setItems((prev) => [...prev, emptyRow(prev.length)]);
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
const run = () => {
|
||||
setItems((prev) => {
|
||||
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
||||
return next.length ? next : [];
|
||||
});
|
||||
setCollapsed((prev) => {
|
||||
const next: Record<number, boolean> = {};
|
||||
Object.entries(prev).forEach(([k, v]) => {
|
||||
const i = Number(k);
|
||||
if (i < index) next[i] = v;
|
||||
else if (i > index) next[i - 1] = v;
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
if (items.length === 1) {
|
||||
Modal.confirm({
|
||||
title: '清空门店套餐',
|
||||
content: '删除最后一条套餐后,该门店将无展示套餐,确认继续?',
|
||||
okText: '确认删除',
|
||||
cancelText: '取消',
|
||||
onOk: run,
|
||||
});
|
||||
return;
|
||||
}
|
||||
run();
|
||||
}
|
||||
|
||||
function toggleCollapse(index: number) {
|
||||
setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
|
||||
}
|
||||
|
||||
async function save(opts?: { quiet?: boolean }) {
|
||||
const currentItems = itemsRef.current;
|
||||
const filled = currentItems
|
||||
.map((item, index) => {
|
||||
const imageUrls = normalizeStorePackageImageUrls(item);
|
||||
return {
|
||||
name: item.name.trim(),
|
||||
price: item.price.trim(),
|
||||
dishes: item.dishes.trim(),
|
||||
usableTime: item.usableTime?.trim() || null,
|
||||
otherNotes: item.otherNotes?.trim() || null,
|
||||
imageUrl: imageUrls[0] ?? null,
|
||||
imageUrls,
|
||||
sortOrder: index,
|
||||
};
|
||||
})
|
||||
// 允许整店无套餐:忽略空白占位行(默认 price=0 不算已填)
|
||||
.filter((item) => {
|
||||
const hasText = !!(item.name || item.dishes || item.usableTime || item.otherNotes);
|
||||
const hasImages = item.imageUrls.length > 0;
|
||||
const hasNonZeroPrice = item.price !== '' && Number(item.price) !== 0;
|
||||
return hasText || hasImages || hasNonZeroPrice;
|
||||
});
|
||||
|
||||
for (let i = 0; i < filled.length; i++) {
|
||||
const item = filled[i];
|
||||
if (!item.name) {
|
||||
message.warning(`第 ${i + 1} 条套餐名称不能为空`);
|
||||
throw new Error('套餐校验失败');
|
||||
}
|
||||
if (!item.dishes) {
|
||||
message.warning(`第 ${i + 1} 条套餐菜品不能为空`);
|
||||
throw new Error('套餐校验失败');
|
||||
}
|
||||
const price = Number(item.price);
|
||||
if (!Number.isFinite(price) || price < 0) {
|
||||
message.warning(`第 ${i + 1} 条套餐价格须为非负数字`);
|
||||
throw new Error('套餐校验失败');
|
||||
}
|
||||
if ((item.imageUrls?.length ?? 0) > STORE_PACKAGE_IMAGE_MAX_COUNT) {
|
||||
message.warning(`第 ${i + 1} 条套餐图片最多 ${STORE_PACKAGE_IMAGE_MAX_COUNT} 张`);
|
||||
throw new Error('套餐校验失败');
|
||||
}
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const data = await request<{ live: PackageRow[] }>(`/admin/stores/${storeId}/packages`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
packages: filled.map((p) => ({ ...p, price: Number(p.price).toFixed(2) })),
|
||||
}),
|
||||
});
|
||||
if (!opts?.quiet) message.success('套餐已保存并生效');
|
||||
setItems(
|
||||
data.live?.length
|
||||
? data.live.map((p, i) => {
|
||||
@@ -42,241 +215,167 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
sortOrder: i,
|
||||
};
|
||||
})
|
||||
: [emptyRow()],
|
||||
: [],
|
||||
);
|
||||
})
|
||||
.catch((e) => message.error(e instanceof Error ? e.message : '加载套餐失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [storeId]);
|
||||
|
||||
function updateAt(index: number, patch: Partial<PackageRow>) {
|
||||
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||
}
|
||||
|
||||
function addRow() {
|
||||
if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
|
||||
setItems((prev) => [...prev, emptyRow(prev.length)]);
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
const run = () => {
|
||||
setItems((prev) => {
|
||||
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
||||
return next.length ? next : [];
|
||||
});
|
||||
setCollapsed((prev) => {
|
||||
const next: Record<number, boolean> = {};
|
||||
Object.entries(prev).forEach(([k, v]) => {
|
||||
const i = Number(k);
|
||||
if (i < index) next[i] = v;
|
||||
else if (i > index) next[i - 1] = v;
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
if (items.length === 1) {
|
||||
Modal.confirm({
|
||||
title: '清空门店套餐',
|
||||
content: '删除最后一条套餐后,该门店将无展示套餐,确认继续?',
|
||||
okText: '确认删除',
|
||||
cancelText: '取消',
|
||||
onOk: run,
|
||||
});
|
||||
return;
|
||||
}
|
||||
run();
|
||||
}
|
||||
function toggleCollapse(index: number) {
|
||||
setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const filled = items
|
||||
.map((item, index) => {
|
||||
const imageUrls = normalizeStorePackageImageUrls(item);
|
||||
return {
|
||||
name: item.name.trim(),
|
||||
price: item.price.trim(),
|
||||
dishes: item.dishes.trim(),
|
||||
usableTime: item.usableTime?.trim() || null,
|
||||
otherNotes: item.otherNotes?.trim() || null,
|
||||
imageUrl: imageUrls[0] ?? null,
|
||||
imageUrls: imageUrls.length ? imageUrls : null,
|
||||
sortOrder: index,
|
||||
};
|
||||
})
|
||||
.filter((item) => item.name || item.dishes || item.price || (item.imageUrls?.length ?? 0) > 0);
|
||||
|
||||
for (let i = 0; i < filled.length; i++) {
|
||||
const item = filled[i];
|
||||
if (!item.name) {
|
||||
message.warning(`第 ${i + 1} 条套餐名称不能为空`);
|
||||
return;
|
||||
}
|
||||
if (!item.dishes) {
|
||||
message.warning(`第 ${i + 1} 条套餐菜品不能为空`);
|
||||
return;
|
||||
}
|
||||
const price = Number(item.price);
|
||||
if (!Number.isFinite(price) || price < 0) {
|
||||
message.warning(`第 ${i + 1} 条套餐价格须为非负数字`);
|
||||
return;
|
||||
}
|
||||
if ((item.imageUrls?.length ?? 0) > STORE_PACKAGE_IMAGE_MAX_COUNT) {
|
||||
message.warning(`第 ${i + 1} 条套餐图片最多 ${STORE_PACKAGE_IMAGE_MAX_COUNT} 张`);
|
||||
return;
|
||||
} catch (e) {
|
||||
if (!opts?.quiet) message.error(e instanceof Error ? e.message : '保存失败');
|
||||
throw e;
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
await request(`/admin/stores/${storeId}/packages`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
packages: filled.map((p) => ({ ...p, price: Number(p.price).toFixed(2) })),
|
||||
}),
|
||||
});
|
||||
message.success('套餐已保存并生效');
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
useImperativeHandle(ref, () => ({
|
||||
saveIfLoaded: async (opts) => {
|
||||
if (loadingRef.current) return { skipped: true };
|
||||
await save(opts);
|
||||
return { skipped: false };
|
||||
},
|
||||
}));
|
||||
|
||||
if (loading) {
|
||||
return <Typography.Text type="secondary">加载套餐中…</Typography.Text>;
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <Typography.Text type="secondary">加载套餐中…</Typography.Text>;
|
||||
}
|
||||
if (!items.length) {
|
||||
return (
|
||||
<Form layout="vertical" requiredMark={false}>
|
||||
<Alert type="info" showIcon style={{ marginBottom: 16 }} message="该门店暂无套餐,可添加或保存为空。" />
|
||||
{pendingReminder}
|
||||
<Button onClick={addRow} style={{ marginBottom: 16 }}>
|
||||
添加套餐
|
||||
</Button>
|
||||
<Button type="primary" loading={saving} onClick={() => void save().catch(() => undefined)}>
|
||||
保存套餐
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
if (!items.length) {
|
||||
return (
|
||||
<Form layout="vertical" requiredMark={false}>
|
||||
<Alert type="info" showIcon style={{ marginBottom: 16 }} message="该门店暂无套餐,可添加或保存为空。" />
|
||||
<Button onClick={addRow} style={{ marginBottom: 16 }}>
|
||||
添加套餐
|
||||
</Button>
|
||||
<Button type="primary" loading={saving} onClick={() => void save()}>
|
||||
{pendingReminder}
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={`总部直存立即生效,无需审核。同一门店最多 ${STORE_PACKAGE_MAX_COUNT} 条套餐。`}
|
||||
/>
|
||||
|
||||
{items.map((item, index) => {
|
||||
const isCollapsed = !!collapsed[index];
|
||||
const displayName = item.name.trim() || `套餐 ${index + 1}`;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: 16,
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 8,
|
||||
background: '#fafafa',
|
||||
}}
|
||||
>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: isCollapsed ? 0 : 12 }}>
|
||||
<Button
|
||||
type="text"
|
||||
icon={isCollapsed ? <DownOutlined /> : <UpOutlined />}
|
||||
onClick={() => toggleCollapse(index)}
|
||||
style={{ paddingLeft: 0, height: 'auto' }}
|
||||
>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{displayName}
|
||||
</Typography.Title>
|
||||
</Button>
|
||||
{items.length > 0 ? (
|
||||
<Button type="link" danger onClick={() => removeAt(index)}>
|
||||
删除
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
|
||||
{!isCollapsed ? (
|
||||
<>
|
||||
<Form.Item label="套餐名称" required style={{ marginBottom: 12 }}>
|
||||
<Input
|
||||
placeholder="如:套餐A"
|
||||
value={item.name}
|
||||
onChange={(e) => updateAt(index, { name: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="价格(元)" required style={{ marginBottom: 12 }}>
|
||||
<InputNumber
|
||||
min={0}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="元"
|
||||
placeholder="198"
|
||||
value={item.price === '' ? undefined : Number(item.price)}
|
||||
onChange={(v) => updateAt(index, { price: v != null ? String(v) : '' })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="菜品" required style={{ marginBottom: 12 }}>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="红烧肉、红烧鱼、油焖茄子"
|
||||
value={item.dishes}
|
||||
onChange={(e) => updateAt(index, { dishes: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="使用时间" style={{ marginBottom: 12 }}>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="节假日除外"
|
||||
value={item.usableTime || ''}
|
||||
onChange={(e) => updateAt(index, { usableTime: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="套餐图片" style={{ marginBottom: 12 }}>
|
||||
<PackageImagesUpload
|
||||
value={normalizeStorePackageImageUrls(item)}
|
||||
onChange={(imageUrls) =>
|
||||
updateAt(index, {
|
||||
imageUrls,
|
||||
imageUrl: imageUrls[0] ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="其他说明" style={{ marginBottom: 0 }}>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{items.length < STORE_PACKAGE_MAX_COUNT ? (
|
||||
<Button onClick={addRow} style={{ marginBottom: 16 }}>
|
||||
添加套餐
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
|
||||
上传套餐图后请点右上角「保存修改」(会连同套餐一起保存),或点下方「保存套餐」。仅上传不保存,刷新会丢失。
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Button type="primary" loading={saving} onClick={() => void save().catch(() => undefined)}>
|
||||
保存套餐
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return ( <Form layout="vertical" requiredMark={false}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={`总部直存立即生效,无需审核。同一门店最多 ${STORE_PACKAGE_MAX_COUNT} 条套餐。`}
|
||||
/>
|
||||
|
||||
{items.map((item, index) => {
|
||||
const isCollapsed = !!collapsed[index];
|
||||
const displayName = item.name.trim() || `套餐 ${index + 1}`;
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: 16,
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 8,
|
||||
background: '#fafafa',
|
||||
}}
|
||||
>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: isCollapsed ? 0 : 12 }}>
|
||||
<Button
|
||||
type="text"
|
||||
icon={isCollapsed ? <DownOutlined /> : <UpOutlined />}
|
||||
onClick={() => toggleCollapse(index)}
|
||||
style={{ paddingLeft: 0, height: 'auto' }}
|
||||
>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{displayName}
|
||||
</Typography.Title>
|
||||
</Button>
|
||||
{items.length > 0 ? (
|
||||
<Button type="link" danger onClick={() => removeAt(index)}>
|
||||
删除
|
||||
</Button>
|
||||
) : null} </Space>
|
||||
|
||||
{!isCollapsed ? (
|
||||
<>
|
||||
<Form.Item label="套餐名称" required style={{ marginBottom: 12 }}>
|
||||
<Input
|
||||
placeholder="如:套餐A"
|
||||
value={item.name}
|
||||
onChange={(e) => updateAt(index, { name: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="价格(元)" required style={{ marginBottom: 12 }}>
|
||||
<InputNumber
|
||||
min={0}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
addonAfter="元"
|
||||
placeholder="198"
|
||||
value={item.price === '' ? undefined : Number(item.price)}
|
||||
onChange={(v) => updateAt(index, { price: v != null ? String(v) : '' })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="菜品" required style={{ marginBottom: 12 }}>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="红烧肉、红烧鱼、油焖茄子"
|
||||
value={item.dishes}
|
||||
onChange={(e) => updateAt(index, { dishes: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="使用时间" style={{ marginBottom: 12 }}>
|
||||
<Input
|
||||
placeholder="节假日除外"
|
||||
value={item.usableTime || ''}
|
||||
onChange={(e) => updateAt(index, { usableTime: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="套餐图片" style={{ marginBottom: 12 }}>
|
||||
<PackageImagesUpload
|
||||
value={normalizeStorePackageImageUrls(item)}
|
||||
onChange={(imageUrls) =>
|
||||
updateAt(index, {
|
||||
imageUrls,
|
||||
imageUrl: imageUrls[0] ?? '',
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="其他说明" style={{ marginBottom: 0 }}> <Input
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{items.length < STORE_PACKAGE_MAX_COUNT ? (
|
||||
<Button onClick={addRow} style={{ marginBottom: 16 }}>
|
||||
添加套餐
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
|
||||
修改后点击下方按钮保存,C 端将立即展示生效套餐。
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Button type="primary" loading={saving} onClick={() => void save()}>
|
||||
保存套餐
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
export default AdminStorePackagesSection;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, Image, Space, Typography, Upload, message } from 'antd';
|
||||
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
|
||||
import { UploadOutlined, DeleteOutlined, FilePdfOutlined } from '@ant-design/icons';
|
||||
import type { UploadProps } from 'antd';
|
||||
import { uploadFileToOss, type OssMediaType } from '../lib/upload';
|
||||
|
||||
@@ -13,12 +13,18 @@ type Props = {
|
||||
maxCount?: number;
|
||||
tip?: string;
|
||||
accept?: string;
|
||||
/** 上传按钮文案,默认「批量上传图片」 */
|
||||
buttonText?: string;
|
||||
};
|
||||
|
||||
function normalizeUrls(value?: string[]) {
|
||||
return (value ?? []).map((u) => String(u || '').trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function isPdf(url: string) {
|
||||
return /\.pdf(\?|$)/i.test(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 多图批量上传(一次可选多张),用于套餐图 / 环境照 / 商品详情图等。
|
||||
* Form.Item 直接绑定 string[]。
|
||||
@@ -31,16 +37,36 @@ export default function MultiImageUpload({
|
||||
maxCount,
|
||||
tip,
|
||||
accept = 'image/*',
|
||||
buttonText = '批量上传图片',
|
||||
}: Props) {
|
||||
const urls = normalizeUrls(value);
|
||||
const urlsRef = useRef(urls);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const batchBuf = useRef<File[]>([]);
|
||||
const batchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const uploadChain = useRef(Promise.resolve());
|
||||
|
||||
useEffect(() => {
|
||||
urlsRef.current = urls;
|
||||
}, [urls]);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (batchTimer.current) clearTimeout(batchTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const remaining = maxCount != null ? Math.max(0, maxCount - urls.length) : Number.POSITIVE_INFINITY;
|
||||
const canAdd = remaining > 0;
|
||||
|
||||
async function uploadBatch(files: File[]) {
|
||||
const room = maxCount != null ? Math.max(0, maxCount - urls.length) : files.length;
|
||||
const current = urlsRef.current;
|
||||
const room = maxCount != null ? Math.max(0, maxCount - current.length) : files.length;
|
||||
const picked = files.slice(0, room);
|
||||
if (!picked.length) {
|
||||
message.warning(maxCount != null ? `最多 ${maxCount} 张` : '无法上传');
|
||||
@@ -63,7 +89,10 @@ export default function MultiImageUpload({
|
||||
}
|
||||
}
|
||||
if (appended.length) {
|
||||
onChange?.([...urls, ...appended]);
|
||||
// 始终基于最新列表追加,避免并行上传互相覆盖
|
||||
const next = [...urlsRef.current, ...appended];
|
||||
urlsRef.current = next;
|
||||
onChangeRef.current?.(next);
|
||||
message.success(`成功上传 ${appended.length} 张${fail ? `,失败 ${fail} 张` : ''}`);
|
||||
} else if (fail) {
|
||||
message.error('上传失败');
|
||||
@@ -73,18 +102,37 @@ export default function MultiImageUpload({
|
||||
}
|
||||
}
|
||||
|
||||
const beforeUpload: UploadProps['beforeUpload'] = (file, fileList) => {
|
||||
batchBuf.current.push(file as File);
|
||||
if (batchBuf.current.length >= fileList.length) {
|
||||
const files = [...batchBuf.current];
|
||||
batchBuf.current = [];
|
||||
void uploadBatch(files);
|
||||
function enqueueUploadBatch(files: File[]) {
|
||||
uploadChain.current = uploadChain.current
|
||||
.then(() => uploadBatch(files))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
function flushBatch() {
|
||||
if (batchTimer.current) {
|
||||
clearTimeout(batchTimer.current);
|
||||
batchTimer.current = null;
|
||||
}
|
||||
if (!batchBuf.current.length) return;
|
||||
const files = [...batchBuf.current];
|
||||
batchBuf.current = [];
|
||||
enqueueUploadBatch(files);
|
||||
}
|
||||
|
||||
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
|
||||
batchBuf.current.push(file as File);
|
||||
// 多选时 beforeUpload 可能逐文件触发;短防抖合并成一次批量
|
||||
if (batchTimer.current) clearTimeout(batchTimer.current);
|
||||
batchTimer.current = setTimeout(() => {
|
||||
flushBatch();
|
||||
}, 80);
|
||||
return false;
|
||||
};
|
||||
|
||||
function removeAt(index: number) {
|
||||
onChange?.(urls.filter((_, i) => i !== index));
|
||||
const next = urlsRef.current.filter((_, i) => i !== index);
|
||||
urlsRef.current = next;
|
||||
onChangeRef.current?.(next);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -102,12 +150,36 @@ export default function MultiImageUpload({
|
||||
<Space wrap size={12}>
|
||||
{urls.map((url, index) => (
|
||||
<div key={`${url}-${index}`} style={{ position: 'relative', width: 96 }}>
|
||||
<Image
|
||||
src={url}
|
||||
width={96}
|
||||
height={96}
|
||||
style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #f0f0f0' }}
|
||||
/>
|
||||
{isPdf(url) ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
style={{
|
||||
display: 'flex',
|
||||
width: 96,
|
||||
height: 96,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexDirection: 'column',
|
||||
gap: 4,
|
||||
borderRadius: 6,
|
||||
border: '1px solid #f0f0f0',
|
||||
background: '#fafafa',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<FilePdfOutlined style={{ fontSize: 24, color: '#cf1322' }} />
|
||||
<span>PDF</span>
|
||||
</a>
|
||||
) : (
|
||||
<Image
|
||||
src={url}
|
||||
width={96}
|
||||
height={96}
|
||||
style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #f0f0f0' }}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
@@ -135,7 +207,7 @@ export default function MultiImageUpload({
|
||||
disabled={uploading || !canAdd}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} loading={uploading} disabled={!canAdd}>
|
||||
{canAdd ? '批量上传图片' : '已达上限'}
|
||||
{canAdd ? buttonText : '已达上限'}
|
||||
</Button>
|
||||
</Upload>
|
||||
</Space>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { Button, Image, Input, Space, Upload, message } from 'antd';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import { Button, Image, Input, Modal, Space, Upload, message } from 'antd';
|
||||
import { EyeOutlined, FilePdfOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import type { UploadProps } from 'antd';
|
||||
import { uploadFileToOss, type OssMediaType, type UploadFileResult } from '../lib/upload';
|
||||
|
||||
@@ -15,6 +15,14 @@ type OssUploadProps = {
|
||||
placeholder?: string;
|
||||
};
|
||||
|
||||
function isImageUrl(url: string) {
|
||||
return /\.(png|jpe?g|gif|webp|bmp|svg)(\?|#|$)/i.test(url);
|
||||
}
|
||||
|
||||
function isPdfUrl(url: string) {
|
||||
return /\.pdf(\?|#|$)/i.test(url);
|
||||
}
|
||||
|
||||
export default function OssUpload({
|
||||
value,
|
||||
onChange,
|
||||
@@ -25,6 +33,7 @@ export default function OssUpload({
|
||||
placeholder = '上传后自动填入,或手动粘贴 URL',
|
||||
}: OssUploadProps) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [pdfPreviewOpen, setPdfPreviewOpen] = useState(false);
|
||||
|
||||
const resolvedAccept =
|
||||
accept ?? (mediaType === 'VIDEO' ? 'video/*' : mediaType === 'FILE' ? undefined : 'image/*');
|
||||
@@ -47,6 +56,57 @@ export default function OssUpload({
|
||||
}
|
||||
};
|
||||
|
||||
const filePreview =
|
||||
value && mediaType === 'FILE' ? (
|
||||
isImageUrl(value) ? (
|
||||
<Image src={value} width={120} height={120} style={{ objectFit: 'cover', borderRadius: 4 }} />
|
||||
) : isPdfUrl(value) ? (
|
||||
<Space direction="vertical" size={8}>
|
||||
<div
|
||||
style={{
|
||||
width: 120,
|
||||
height: 120,
|
||||
borderRadius: 4,
|
||||
border: '1px solid #f0f0f0',
|
||||
background: '#fafafa',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
color: '#cf1322',
|
||||
}}
|
||||
>
|
||||
<FilePdfOutlined style={{ fontSize: 36 }} />
|
||||
<span style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>PDF 合同</span>
|
||||
</div>
|
||||
<Space wrap>
|
||||
<Button type="link" size="small" icon={<EyeOutlined />} onClick={() => setPdfPreviewOpen(true)}>
|
||||
预览
|
||||
</Button>
|
||||
<Button type="link" size="small" href={value} target="_blank" rel="noreferrer">
|
||||
新窗口打开
|
||||
</Button>
|
||||
</Space>
|
||||
<Modal
|
||||
title="签约合同预览"
|
||||
open={pdfPreviewOpen}
|
||||
onCancel={() => setPdfPreviewOpen(false)}
|
||||
footer={null}
|
||||
width="90vw"
|
||||
styles={{ body: { height: '75vh', padding: 0 } }}
|
||||
destroyOnClose
|
||||
>
|
||||
<iframe title="合同 PDF 预览" src={value} style={{ width: '100%', height: '100%', border: 0 }} />
|
||||
</Modal>
|
||||
</Space>
|
||||
) : (
|
||||
<Button type="link" href={value} target="_blank" rel="noreferrer" style={{ paddingLeft: 0 }}>
|
||||
打开已上传文件
|
||||
</Button>
|
||||
)
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="small">
|
||||
{value && mediaType === 'IMAGE' && (
|
||||
@@ -55,6 +115,7 @@ export default function OssUpload({
|
||||
{value && mediaType === 'VIDEO' && (
|
||||
<video src={value} controls style={{ maxWidth: '100%', maxHeight: 160, borderRadius: 4 }} />
|
||||
)}
|
||||
{filePreview}
|
||||
<Space wrap>
|
||||
<Upload
|
||||
accept={resolvedAccept}
|
||||
|
||||
@@ -217,6 +217,12 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ payMethod: 'NATIVE' }),
|
||||
});
|
||||
if (pay.mode === 'mock') {
|
||||
message.success(`支付成功:${order.orderNo}`);
|
||||
resetForm();
|
||||
onSuccess({ id: order.id, orderNo: order.orderNo });
|
||||
return;
|
||||
}
|
||||
setCodeUrl(pay.codeUrl ?? null);
|
||||
startPoll(order.id);
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Layout, Menu, Typography, Button, Space } from 'antd';
|
||||
import { Layout, Menu, Typography, Button, Space, Badge } from 'antd';
|
||||
import type { MenuProps } from 'antd';
|
||||
import {
|
||||
RobotOutlined,
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
||||
import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
|
||||
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
|
||||
|
||||
const { Header, Sider, Content } = Layout;
|
||||
|
||||
@@ -60,7 +61,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
label: '门店',
|
||||
children: [
|
||||
{ key: '/stores', label: '门店列表' },
|
||||
{ key: '/store-package-audits', label: '套餐审核' },
|
||||
{ key: '/store-package-audits', label: '审核通知' },
|
||||
{ key: '/store-ratings', label: '门店评价' },
|
||||
{ key: '/store-categories', label: '门店分类' },
|
||||
{ key: '/store-accounts', label: '门店账户' },
|
||||
@@ -243,6 +244,31 @@ function filterMenuItems(items: MenuProps['items'], permissionKeys: string[]): M
|
||||
.filter(Boolean) as MenuProps['items'];
|
||||
}
|
||||
|
||||
function attachAuditBadge(items: MenuProps['items'], pendingCount: number): MenuProps['items'] {
|
||||
if (!items) return items;
|
||||
return items.map((item) => {
|
||||
if (!item || typeof item !== 'object' || !('key' in item)) return item;
|
||||
if ('children' in item && Array.isArray(item.children)) {
|
||||
return {
|
||||
...item,
|
||||
children: attachAuditBadge(item.children as MenuProps['items'], pendingCount),
|
||||
} as MenuItem;
|
||||
}
|
||||
if (String(item.key) === '/store-package-audits') {
|
||||
return {
|
||||
...item,
|
||||
label: (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
审核通知
|
||||
{pendingCount > 0 && <Badge count={pendingCount} size="small" />}
|
||||
</span>
|
||||
),
|
||||
} as MenuItem;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
const IS_STAGING = import.meta.env.VITE_APP_ENV === 'staging';
|
||||
|
||||
export default function AdminLayout() {
|
||||
@@ -250,11 +276,35 @@ export default function AdminLayout() {
|
||||
const location = useLocation();
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [profile, setProfile] = useState<HqProfile | null>(null);
|
||||
const [auditPendingCount, setAuditPendingCount] = useState(0);
|
||||
|
||||
function refreshAuditPendingCount() {
|
||||
Promise.all([
|
||||
request<{ pendingCount: number }>('/admin/store-package-audits/summary').catch(() => ({ pendingCount: 0 })),
|
||||
request<{ pendingCount: number; packagePendingCount?: number }>('/admin/store-info-change-requests/summary').catch(() => ({ pendingCount: 0 })),
|
||||
])
|
||||
.then(([pkg, info]) => setAuditPendingCount((pkg.pendingCount ?? 0) + (info.pendingCount ?? 0)))
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
request<HqProfile>('/admin/auth/me').then(setProfile).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refreshAuditPendingCount();
|
||||
}, [location.pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChanged = () => refreshAuditPendingCount();
|
||||
window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
||||
window.addEventListener(AUDIT_NOTICE_CHANGED_EVENT, onChanged);
|
||||
return () => {
|
||||
window.removeEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
|
||||
window.removeEventListener(AUDIT_NOTICE_CHANGED_EVENT, onChanged);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
contentRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
}, [location.pathname]);
|
||||
@@ -273,10 +323,12 @@ export default function AdminLayout() {
|
||||
: location.pathname;
|
||||
|
||||
const menuItems = useMemo(() => {
|
||||
if (!profile) return MENU_ITEMS;
|
||||
if (profile.adminRole === 'SUPER_ADMIN') return MENU_ITEMS;
|
||||
return filterMenuItems(MENU_ITEMS, profile.permissionKeys ?? []);
|
||||
}, [profile]);
|
||||
const base =
|
||||
!profile || profile.adminRole === 'SUPER_ADMIN'
|
||||
? MENU_ITEMS
|
||||
: filterMenuItems(MENU_ITEMS, profile.permissionKeys ?? []);
|
||||
return attachAuditBadge(base, auditPendingCount);
|
||||
}, [profile, auditPendingCount]);
|
||||
|
||||
return (
|
||||
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export const PACKAGE_AUDIT_CHANGED_EVENT = 'admin:package-audit-changed';
|
||||
export const AUDIT_NOTICE_CHANGED_EVENT = 'dukang:audit-notice-changed';
|
||||
|
||||
export function notifyPackageAuditChanged() {
|
||||
window.dispatchEvent(new Event(PACKAGE_AUDIT_CHANGED_EVENT));
|
||||
window.dispatchEvent(new Event(AUDIT_NOTICE_CHANGED_EVENT));
|
||||
}
|
||||
|
||||
export function notifyAuditNoticeChanged() {
|
||||
notifyPackageAuditChanged();
|
||||
}
|
||||
@@ -168,6 +168,12 @@ export type AdminUserRow = {
|
||||
createdAt: string;
|
||||
orderCount: number;
|
||||
isTest?: boolean;
|
||||
/** 好客权益·累计获得(含已使用,不含退款作废) */
|
||||
benefitTotalAmount?: number;
|
||||
/** 好客权益·已使用(已核销) */
|
||||
benefitUsedAmount?: number;
|
||||
/** 好客权益·剩余未使用 */
|
||||
benefitBalance?: number;
|
||||
};
|
||||
|
||||
export type AdminOrderItem = {
|
||||
|
||||
@@ -140,10 +140,29 @@ export function fmtTime(v?: string | null) {
|
||||
return v ? new Date(v).toLocaleString('zh-CN') : '—';
|
||||
}
|
||||
|
||||
/** 手机号脱敏展示:138****5678;空值返回 — */
|
||||
/** 联系电话脱敏:手机 138****5678;座机 0379-****888;空值返回 — */
|
||||
export function maskPhone(phone?: string | null): string {
|
||||
const raw = String(phone ?? '').trim();
|
||||
const raw = String(phone ?? '').trim().replace(/\s+/g, '');
|
||||
if (!raw) return '—';
|
||||
if (/^1[3-9]\d{9}$/.test(raw)) {
|
||||
const digits = raw.replace(/\D/g, '');
|
||||
return `${digits.slice(0, 3)}****${digits.slice(-4)}`;
|
||||
}
|
||||
if (/^0\d{2,3}-?\d{7,8}(-\d{1,6})?$/.test(raw)) {
|
||||
const extMatch = raw.match(/-(\d{1,6})$/);
|
||||
const hasExt = !!extMatch && raw.indexOf('-') !== raw.lastIndexOf('-');
|
||||
const ext = hasExt ? extMatch![1] : '';
|
||||
const main = hasExt ? raw.slice(0, -(ext.length + 1)) : raw;
|
||||
const digits = main.replace(/\D/g, '');
|
||||
const areaLen = digits.startsWith('01') || digits.startsWith('02') ? 3 : 4;
|
||||
const area = digits.slice(0, areaLen);
|
||||
const local = digits.slice(areaLen);
|
||||
const keepTail = Math.min(4, Math.max(2, local.length - 4));
|
||||
const maskedLocal =
|
||||
local.length <= 4 ? '*'.repeat(local.length) : `${'*'.repeat(local.length - keepTail)}${local.slice(-keepTail)}`;
|
||||
const joiner = main.includes('-') ? '-' : '';
|
||||
return ext ? `${area}${joiner}${maskedLocal}-${ext}` : `${area}${joiner}${maskedLocal}`;
|
||||
}
|
||||
const digits = raw.replace(/\D/g, '');
|
||||
if (digits.length >= 11) {
|
||||
return `${digits.slice(0, 3)}****${digits.slice(-4)}`;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isStoreContactPhone, STORE_CONTACT_PHONE_HINT } from '@dukang/domain';
|
||||
|
||||
export type StoreCreateForm = {
|
||||
partnerAccountId: string;
|
||||
cityId: string;
|
||||
@@ -15,6 +17,8 @@ export type StoreCreateForm = {
|
||||
longitude?: number | null;
|
||||
intro?: string;
|
||||
benefitUsageRule?: string;
|
||||
/** 对外联系电话(店长);可与登录号不同,支持座机 */
|
||||
contactPhone?: string;
|
||||
openTime?: string;
|
||||
closeTime?: string;
|
||||
openTime2?: string;
|
||||
@@ -22,7 +26,8 @@ export type StoreCreateForm = {
|
||||
avgPrice?: number | null;
|
||||
coverUrl?: string;
|
||||
envPhotoUrls?: string[];
|
||||
contractUrl?: string;
|
||||
/** 签约合同,支持多张照片 / PDF */
|
||||
contractUrls?: string[];
|
||||
bankAccountName: string;
|
||||
bankAccountNo: string;
|
||||
bankBranch: string;
|
||||
@@ -58,6 +63,7 @@ export function validateStoreCreateStep1(
|
||||
| 'openTime2'
|
||||
| 'closeTime2'
|
||||
| 'avgPrice'
|
||||
| 'contactPhone'
|
||||
>,
|
||||
): string | null {
|
||||
if (!form.partnerAccountId) return '请选择开城合伙人';
|
||||
@@ -67,6 +73,8 @@ export function validateStoreCreateStep1(
|
||||
if (!form.name?.trim()) return '请填写门店名称';
|
||||
if (!form.phone?.trim()) return '请填写门店手机号';
|
||||
if (!PHONE_RE.test(form.phone.trim())) return '门店手机号须为11位手机号';
|
||||
const contactPhone = form.contactPhone?.trim();
|
||||
if (contactPhone && !isStoreContactPhone(contactPhone)) return STORE_CONTACT_PHONE_HINT;
|
||||
if (!form.address?.trim()) return '请填写详细地址';
|
||||
|
||||
const openTime = String(form.openTime || '').trim();
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import { request } from '../lib/api';
|
||||
import sfxTier1 from '../assets/big-screen/celebrate-t1.mp3';
|
||||
import sfxTier2 from '../assets/big-screen/celebrate-t2.mp3';
|
||||
import sfxTier3 from '../assets/big-screen/celebrate-t3.mp3';
|
||||
|
||||
export type BigScreenOrder = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
payAmount: number;
|
||||
items: string;
|
||||
/** 展示用时间(付款成功时间) */
|
||||
createdAt: string;
|
||||
paidAt?: string;
|
||||
userPhoneMasked: string | null;
|
||||
};
|
||||
|
||||
type AmountTier = 1 | 2 | 3;
|
||||
|
||||
const POLL_MS = 3000;
|
||||
const ROW_MS = 2500;
|
||||
/** 不足此条数时重复填充,保证滚动连贯 */
|
||||
const MIN_SCROLL_ROWS = 10;
|
||||
const FX_DURATION_MS = 10_000;
|
||||
const WEEKDAYS = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
|
||||
|
||||
const CELEBRATE_SFX: Record<AmountTier, string> = {
|
||||
1: sfxTier1,
|
||||
2: sfxTier2,
|
||||
3: sfxTier3,
|
||||
};
|
||||
|
||||
/** 浏览器自动播放策略:需用户手势后才能出声 */
|
||||
let audioUnlocked = false;
|
||||
const sharedAudio = typeof Audio !== 'undefined' ? new Audio() : null;
|
||||
|
||||
function unlockCelebrateAudio() {
|
||||
if (audioUnlocked || !sharedAudio) return;
|
||||
sharedAudio.muted = true;
|
||||
sharedAudio.src = CELEBRATE_SFX[1];
|
||||
void sharedAudio
|
||||
.play()
|
||||
.then(() => {
|
||||
sharedAudio.pause();
|
||||
sharedAudio.currentTime = 0;
|
||||
sharedAudio.muted = false;
|
||||
audioUnlocked = true;
|
||||
})
|
||||
.catch(() => {
|
||||
/* 等待下次手势 */
|
||||
});
|
||||
}
|
||||
|
||||
function playCelebrateSfx(tier: AmountTier): () => void {
|
||||
if (!sharedAudio) return () => undefined;
|
||||
try {
|
||||
sharedAudio.pause();
|
||||
sharedAudio.currentTime = 0;
|
||||
sharedAudio.src = CELEBRATE_SFX[tier];
|
||||
sharedAudio.volume = tier === 3 ? 0.85 : tier === 2 ? 0.75 : 0.65;
|
||||
sharedAudio.muted = false;
|
||||
void sharedAudio.play().catch(() => {
|
||||
/* 未解锁时静默失败 */
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return () => {
|
||||
try {
|
||||
sharedAudio.pause();
|
||||
sharedAudio.currentTime = 0;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0');
|
||||
}
|
||||
|
||||
function formatClock(d: Date) {
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function formatDateLine(d: Date) {
|
||||
return `${d.getFullYear()} / ${pad(d.getMonth() + 1)} / ${pad(d.getDate())} ${WEEKDAYS[d.getDay()]}`;
|
||||
}
|
||||
|
||||
function formatOrderTime(iso: string): string {
|
||||
try {
|
||||
return formatClock(new Date(iso));
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
// function formatAmount(n: number): string {
|
||||
// return Number(n || 0).toLocaleString('zh-CN', {
|
||||
// minimumFractionDigits: 0,
|
||||
// maximumFractionDigits: 0,
|
||||
// });
|
||||
// }
|
||||
|
||||
function formatAmount(n: number): string {
|
||||
const num = Number(n || 0);
|
||||
// 先保留两位小数,再分割处理
|
||||
const fixed = num.toFixed(2);
|
||||
const [intStr, decStr] = fixed.split('.');
|
||||
const intFormatted = Number(intStr).toLocaleString('zh-CN');
|
||||
return decStr === '00' ? intFormatted : `${intFormatted}.${decStr}`;
|
||||
}
|
||||
|
||||
function amountCssClass(payAmount: number, base: string): string {
|
||||
const wide = Math.floor(Math.abs(Number(payAmount || 0))) >= 100_000;
|
||||
return wide ? `${base} ${base}--6d` : base;
|
||||
}
|
||||
|
||||
export function amountTier(payAmount: number): AmountTier {
|
||||
if (payAmount >= 1000) return 3;
|
||||
if (payAmount >= 500) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
function LiveClock() {
|
||||
const [now, setNow] = useState(() => new Date());
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(new Date()), 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
return (
|
||||
<div className="big-screen-hero">
|
||||
<div className="big-screen-clock">{formatClock(now)}</div>
|
||||
<div className="big-screen-date">{formatDateLine(now)}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderRow({
|
||||
order,
|
||||
latest,
|
||||
}: {
|
||||
order: BigScreenOrder;
|
||||
latest?: boolean;
|
||||
}) {
|
||||
const tier = amountTier(order.payAmount);
|
||||
return (
|
||||
<div
|
||||
className={`big-screen-row big-screen-row--t${tier}${latest ? ' is-latest' : ''}`}
|
||||
>
|
||||
{latest ? <span className="big-screen-row-mark" /> : null}
|
||||
<span className={amountCssClass(order.payAmount, 'big-screen-amount')}>
|
||||
¥ {formatAmount(order.payAmount)}
|
||||
</span>
|
||||
<span className="big-screen-items">{order.items || '—'}</span>
|
||||
<span className="big-screen-time">{formatOrderTime(order.paidAt ?? order.createdAt)}</span>
|
||||
<span className="big-screen-phone">{order.userPhoneMasked || '—'}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Particle = {
|
||||
x: number;
|
||||
y: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
rot: number;
|
||||
vr: number;
|
||||
w: number;
|
||||
h: number;
|
||||
color: string;
|
||||
life: number;
|
||||
kind: 'rect' | 'ribbon' | 'spark';
|
||||
rain?: boolean;
|
||||
};
|
||||
|
||||
const TIER_COLORS: Record<AmountTier, string[]> = {
|
||||
1: ['#e6f7ff', '#91d5ff', '#40a9ff', '#ffffff', '#69c0ff'],
|
||||
2: ['#fff1b8', '#ffe58f', '#ffd666', '#fffbe6', '#ffe7ba'],
|
||||
3: ['#ffd666', '#faad14', '#ffec3d', '#fff1b8', '#ff4d4f', '#ff7a45', '#ffffff'],
|
||||
};
|
||||
|
||||
function spawnParticles(tier: AmountTier, w: number, h: number): Particle[] {
|
||||
const colors = TIER_COLORS[tier];
|
||||
const count = tier === 3 ? 180 : tier === 2 ? 110 : 70;
|
||||
const out: Particle[] = [];
|
||||
const cx = w / 2;
|
||||
const cy = h * 0.42;
|
||||
for (let i = 0; i < count; i++) {
|
||||
const angle = Math.random() * Math.PI * 2;
|
||||
const speed = (tier === 3 ? 8 : tier === 2 ? 6 : 4) * (0.4 + Math.random());
|
||||
const kind: Particle['kind'] =
|
||||
tier === 3 && Math.random() < 0.25 ? 'ribbon' : Math.random() < 0.2 ? 'spark' : 'rect';
|
||||
out.push({
|
||||
x: cx + (Math.random() - 0.5) * 80,
|
||||
y: cy + (Math.random() - 0.5) * 40,
|
||||
vx: Math.cos(angle) * speed,
|
||||
vy: Math.sin(angle) * speed - (tier === 3 ? 6 : 3),
|
||||
rot: Math.random() * 360,
|
||||
vr: (Math.random() - 0.5) * 18,
|
||||
w: kind === 'ribbon' ? 10 + Math.random() * 16 : kind === 'spark' ? 2 : 6 + Math.random() * 8,
|
||||
h: kind === 'ribbon' ? 28 + Math.random() * 24 : kind === 'spark' ? 10 + Math.random() * 8 : 4 + Math.random() * 6,
|
||||
color: colors[Math.floor(Math.random() * colors.length)],
|
||||
life: 1,
|
||||
kind,
|
||||
});
|
||||
}
|
||||
if (tier >= 2) {
|
||||
for (let i = 0; i < (tier === 3 ? 80 : 40); i++) {
|
||||
out.push({
|
||||
x: Math.random() * w,
|
||||
y: -20 - Math.random() * 80,
|
||||
vx: (Math.random() - 0.5) * 1.4,
|
||||
vy: 3 + Math.random() * 5,
|
||||
rot: Math.random() * 360,
|
||||
vr: (Math.random() - 0.5) * 10,
|
||||
w: 5 + Math.random() * 8,
|
||||
h: 10 + Math.random() * 14,
|
||||
color: colors[Math.floor(Math.random() * colors.length)],
|
||||
life: 1,
|
||||
kind: 'rect',
|
||||
rain: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function CelebrateFx({ order, onDone }: { order: BigScreenOrder; onDone: () => void }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const onDoneRef = useRef(onDone);
|
||||
onDoneRef.current = onDone;
|
||||
const tier = amountTier(order.payAmount);
|
||||
const [displayAmount, setDisplayAmount] = useState(tier === 3 ? 0 : order.payAmount);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => onDoneRef.current(), FX_DURATION_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [order.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const stop = playCelebrateSfx(tier);
|
||||
return stop;
|
||||
}, [order.id, tier]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tier !== 3) return;
|
||||
const start = performance.now();
|
||||
const dur = 900;
|
||||
let raf = 0;
|
||||
const tick = (now: number) => {
|
||||
const p = Math.min(1, (now - start) / dur);
|
||||
const eased = 1 - (1 - p) ** 3;
|
||||
setDisplayAmount(Math.round(order.payAmount * eased));
|
||||
if (p < 1) raf = requestAnimationFrame(tick);
|
||||
};
|
||||
raf = requestAnimationFrame(tick);
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [order.payAmount, order.id, tier]);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
const resize = () => {
|
||||
canvas.width = canvas.clientWidth * devicePixelRatio;
|
||||
canvas.height = canvas.clientHeight * devicePixelRatio;
|
||||
ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
|
||||
};
|
||||
resize();
|
||||
const particles = spawnParticles(tier, canvas.clientWidth, canvas.clientHeight);
|
||||
let raf = 0;
|
||||
let last = performance.now();
|
||||
const started = performance.now();
|
||||
const gravity = tier === 3 ? 0.18 : 0.14;
|
||||
const loop = (now: number) => {
|
||||
const dt = Math.min(32, now - last) / 16.6;
|
||||
last = now;
|
||||
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
|
||||
for (const p of particles) {
|
||||
p.vy += gravity * dt;
|
||||
p.x += p.vx * dt;
|
||||
p.y += p.vy * dt;
|
||||
p.rot += p.vr * dt;
|
||||
p.life -= (tier === 3 ? 0.002 : 0.003) * dt;
|
||||
if (
|
||||
p.rain &&
|
||||
(p.y > canvas.clientHeight + 30 || p.life <= 0) &&
|
||||
now - started < FX_DURATION_MS - 400
|
||||
) {
|
||||
p.x = Math.random() * canvas.clientWidth;
|
||||
p.y = -16 - Math.random() * 60;
|
||||
p.vx = (Math.random() - 0.5) * 1.4;
|
||||
p.vy = 3 + Math.random() * 5;
|
||||
p.life = 1;
|
||||
}
|
||||
if (p.life <= 0) continue;
|
||||
ctx.save();
|
||||
ctx.translate(p.x, p.y);
|
||||
ctx.rotate((p.rot * Math.PI) / 180);
|
||||
ctx.globalAlpha = Math.max(0, p.life);
|
||||
ctx.fillStyle = p.color;
|
||||
if (p.kind === 'spark') {
|
||||
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
|
||||
} else {
|
||||
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
raf = requestAnimationFrame(loop);
|
||||
};
|
||||
raf = requestAnimationFrame(loop);
|
||||
const onResize = () => resize();
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => {
|
||||
cancelAnimationFrame(raf);
|
||||
window.removeEventListener('resize', onResize);
|
||||
};
|
||||
}, [order.id, tier]);
|
||||
|
||||
return (
|
||||
<div className={`big-screen-fx big-screen-fx--t${tier}`} role="presentation">
|
||||
<canvas ref={canvasRef} className="big-screen-fx-canvas" />
|
||||
{tier === 3 ? <div className="big-screen-fx-shock" /> : null}
|
||||
{tier === 3 ? <div className="big-screen-fx-shock big-screen-fx-shock--late" /> : null}
|
||||
{tier >= 2 ? <div className="big-screen-fx-sweep" /> : null}
|
||||
{tier >= 2 ? <div className="big-screen-fx-sweep big-screen-fx-sweep--alt" /> : null}
|
||||
<div className={`big-screen-fx-card big-screen-fx-card--t${tier}`}>
|
||||
<div className="big-screen-fx-kicker">{tier === 3 ? '高额成交' : tier === 2 ? '大额成交' : '新成交'}</div>
|
||||
<div className={amountCssClass(displayAmount || order.payAmount, 'big-screen-fx-amount')}>
|
||||
¥ {formatAmount(displayAmount)}
|
||||
</div>
|
||||
<div className="big-screen-fx-items">{order.items || '—'}</div>
|
||||
<div className="big-screen-fx-meta">
|
||||
<span>{order.userPhoneMasked || '—'}</span>
|
||||
<span>{formatOrderTime(order.paidAt ?? order.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BigScreenPage() {
|
||||
const [items, setItems] = useState<BigScreenOrder[]>([]);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [celebrate, setCelebrate] = useState<BigScreenOrder | null>(null);
|
||||
const seenIdsRef = useRef<Set<string> | null>(null);
|
||||
const celebratedIdsRef = useRef<Set<string>>(new Set());
|
||||
const queueRef = useRef<BigScreenOrder[]>([]);
|
||||
const celebratingRef = useRef(false);
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
const dayKeyRef = useRef('');
|
||||
const [viewportH, setViewportH] = useState(0);
|
||||
|
||||
const playNext = useCallback(() => {
|
||||
const next = queueRef.current.shift() ?? null;
|
||||
celebratingRef.current = !!next;
|
||||
setCelebrate(next);
|
||||
setPaused(!!next);
|
||||
}, []);
|
||||
|
||||
const enqueueNew = useCallback(
|
||||
(fresh: BigScreenOrder[]) => {
|
||||
const toCelebrate = fresh.filter((o) => !celebratedIdsRef.current.has(o.id));
|
||||
if (!toCelebrate.length) return;
|
||||
for (const o of toCelebrate) celebratedIdsRef.current.add(o.id);
|
||||
const ranked = [...toCelebrate].sort((a, b) => {
|
||||
const td = amountTier(b.payAmount) - amountTier(a.payAmount);
|
||||
if (td !== 0) return td;
|
||||
return +new Date(b.paidAt ?? b.createdAt) - +new Date(a.paidAt ?? a.createdAt);
|
||||
});
|
||||
queueRef.current.push(...ranked);
|
||||
if (!celebratingRef.current) playNext();
|
||||
},
|
||||
[playNext],
|
||||
);
|
||||
|
||||
const fetchData = useCallback(() => {
|
||||
const now = new Date();
|
||||
const todayKey = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
||||
if (dayKeyRef.current && dayKeyRef.current !== todayKey) {
|
||||
seenIdsRef.current = null;
|
||||
celebratedIdsRef.current = new Set();
|
||||
queueRef.current = [];
|
||||
celebratingRef.current = false;
|
||||
setCelebrate(null);
|
||||
setPaused(false);
|
||||
}
|
||||
dayKeyRef.current = todayKey;
|
||||
|
||||
return request<{ items: BigScreenOrder[] }>('/admin/orders/big-screen?limit=2000')
|
||||
.then((d) => {
|
||||
const list = d.items ?? [];
|
||||
setItems(list);
|
||||
setLoadError('');
|
||||
const seen = seenIdsRef.current;
|
||||
if (!seen) {
|
||||
seenIdsRef.current = new Set(list.map((o) => o.id));
|
||||
for (const o of list) celebratedIdsRef.current.add(o.id);
|
||||
return;
|
||||
}
|
||||
const fresh = list.filter((o) => !seen.has(o.id));
|
||||
for (const o of fresh) seen.add(o.id);
|
||||
enqueueNew(fresh);
|
||||
})
|
||||
.catch((e) => {
|
||||
setLoadError(e instanceof Error ? e.message : '加载失败');
|
||||
});
|
||||
}, [enqueueNew]);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchData();
|
||||
const id = setInterval(() => void fetchData(), POLL_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
unlockCelebrateAudio();
|
||||
const unlock = () => unlockCelebrateAudio();
|
||||
window.addEventListener('pointerdown', unlock, { once: true });
|
||||
window.addEventListener('keydown', unlock, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', unlock);
|
||||
window.removeEventListener('keydown', unlock);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const html = document.documentElement;
|
||||
const prevHtml = html.style.overflow;
|
||||
const prevBody = document.body.style.overflow;
|
||||
html.style.overflow = 'hidden';
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
html.style.overflow = prevHtml;
|
||||
document.body.style.overflow = prevBody;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = viewportRef.current;
|
||||
if (!el) return;
|
||||
const measure = () => setViewportH(el.clientHeight);
|
||||
measure();
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const unitItems = useMemo(() => {
|
||||
if (!items.length) return [];
|
||||
const rowH = 80;
|
||||
const visible = Math.max(1, Math.ceil((viewportH || 480) / rowH));
|
||||
const minCount = Math.max(MIN_SCROLL_ROWS, visible + 1);
|
||||
const unit: BigScreenOrder[] = [];
|
||||
while (unit.length < minCount) unit.push(...items);
|
||||
return unit;
|
||||
}, [items, viewportH]);
|
||||
|
||||
const trackItems = useMemo(() => unitItems.concat(unitItems), [unitItems]);
|
||||
const marqueeMs = Math.max(unitItems.length, 1) * ROW_MS;
|
||||
const rolling = items.length > 0 && unitItems.length > 0;
|
||||
const latestId = items[0]?.id;
|
||||
|
||||
return (
|
||||
<div className="big-screen-page">
|
||||
<div className="big-screen-stars" aria-hidden />
|
||||
<div className="big-screen-frame" aria-hidden>
|
||||
<span className="big-screen-corner big-screen-corner--tl" />
|
||||
<span className="big-screen-corner big-screen-corner--tr" />
|
||||
<span className="big-screen-corner big-screen-corner--bl" />
|
||||
<span className="big-screen-corner big-screen-corner--br" />
|
||||
</div>
|
||||
|
||||
<header className="big-screen-header">
|
||||
<div className="big-screen-brand">
|
||||
<h1 className="big-screen-title">杜康好客</h1>
|
||||
<span className="big-screen-subtitle">· 发布会现场</span>
|
||||
</div>
|
||||
<div className="big-screen-live-wrap">
|
||||
<span className="big-screen-live-label">实时成交</span>
|
||||
<span className="big-screen-live">
|
||||
<span className="big-screen-live-dot" />
|
||||
LIVE
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<LiveClock />
|
||||
|
||||
<div className="big-screen-list">
|
||||
<div className="big-screen-list-body" ref={viewportRef}>
|
||||
{items.length === 0 ? null : (
|
||||
<div
|
||||
className={`big-screen-track${rolling ? ' is-rolling' : ''}${paused ? ' is-paused' : ''}`}
|
||||
style={rolling ? ({ ['--marquee-ms']: `${marqueeMs}ms` } as CSSProperties) : undefined}
|
||||
>
|
||||
{trackItems.map((o, idx) => (
|
||||
<OrderRow
|
||||
key={`${o.id}-${idx}`}
|
||||
order={o}
|
||||
latest={idx % items.length === 0 && o.id === latestId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<div className="big-screen-empty">{loadError || '当日暂无订单'}</div>
|
||||
) : null}
|
||||
|
||||
{celebrate ? (
|
||||
<CelebrateFx
|
||||
key={celebrate.id}
|
||||
order={celebrate}
|
||||
onDone={playNext}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -542,6 +542,7 @@ export default function OrdersPage() {
|
||||
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>订单监控</Typography.Title>
|
||||
<Space>
|
||||
<Button onClick={() => window.open('/orders/big-screen', 'dukang-big-screen')}>大屏</Button>
|
||||
{canProxyOrder ? (
|
||||
<Button type="primary" onClick={() => setProxyOpen(true)}>
|
||||
代下单
|
||||
|
||||
@@ -63,10 +63,12 @@ const KIND_COLORS: Record<StoreSettlementKind, string> = {
|
||||
export default function StoreBillsPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : '';
|
||||
const initialStoreId = searchParams.get('storeId') || '';
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({
|
||||
kind: initialKind,
|
||||
status: initialKind === 'WITHDRAW' ? 'PENDING_REVIEW' : '',
|
||||
storeId: initialStoreId,
|
||||
});
|
||||
const [stores, setStores] = useState<StoreOption[]>([]);
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||
@@ -97,8 +99,9 @@ export default function StoreBillsPage() {
|
||||
form.setFieldsValue({
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
storeId: filters.storeId || undefined,
|
||||
});
|
||||
}, [filters.kind, filters.status, form]);
|
||||
}, [filters.kind, filters.status, filters.storeId, form]);
|
||||
|
||||
useEffect(() => {
|
||||
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
|
||||
@@ -359,6 +362,7 @@ export default function StoreBillsPage() {
|
||||
initialValues={{
|
||||
kind: filters.kind || undefined,
|
||||
status: filters.status || undefined,
|
||||
storeId: filters.storeId || undefined,
|
||||
}}
|
||||
onFinish={(v: {
|
||||
kind?: string;
|
||||
|
||||
@@ -1,31 +1,120 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Descriptions,
|
||||
Drawer,
|
||||
Image,
|
||||
Input,
|
||||
Modal,
|
||||
Space,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type {
|
||||
StoreInfoChangeFieldDiff,
|
||||
StoreInfoChangeRequestDto,
|
||||
StoreInfoChangeStatus,
|
||||
StorePackageAuditDetailDto,
|
||||
StorePackageAuditSummaryDto,
|
||||
StorePackageChangeRequestDto,
|
||||
StorePackageChangeStatus,
|
||||
StorePackageItemDto,
|
||||
StorePackageViewDto,
|
||||
} from '@dukang/shared-types';
|
||||
import { STORE_PACKAGE_CHANGE_STATUS_LABELS } from '@dukang/shared-types';
|
||||
import {
|
||||
STORE_INFO_CHANGE_STATUS_LABELS,
|
||||
normalizeStorePackageImageUrls,
|
||||
} from '@dukang/shared-types';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import { notifyPackageAuditChanged } from '../lib/admin-events';
|
||||
import { fmtTime } from '../lib/constants';
|
||||
|
||||
const HQ_PACKAGE_STATUS_LABELS: Record<StorePackageChangeStatus, string> = {
|
||||
PENDING: '待审核',
|
||||
APPROVED: '已通过',
|
||||
REJECTED: '已驳回',
|
||||
};
|
||||
|
||||
function packageKey(pkg: StorePackageItemDto | StorePackageViewDto, index: number) {
|
||||
const name = String(pkg.name ?? '').trim();
|
||||
return name ? `name:${name}` : `idx:${index}`;
|
||||
}
|
||||
|
||||
function imageSignature(pkg: StorePackageItemDto | StorePackageViewDto) {
|
||||
return normalizeStorePackageImageUrls(pkg).join('|');
|
||||
}
|
||||
|
||||
type FieldChange = { label: string; old: string; now: string; kind: 'text' | 'value' };
|
||||
|
||||
/** 文本逐字差异:LCS 比对,产出 equal / delete / insert 段落,用于高亮具体变了哪些字 */
|
||||
function diffText(a: string, b: string): Array<{ type: 'equal' | 'insert' | 'delete'; text: string }> {
|
||||
const m = a.length;
|
||||
const n = b.length;
|
||||
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
||||
for (let i = m - 1; i >= 0; i--) {
|
||||
for (let j = n - 1; j >= 0; j--) {
|
||||
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
||||
}
|
||||
}
|
||||
const raw: Array<{ type: 'equal' | 'insert' | 'delete'; text: string }> = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < m && j < n) {
|
||||
if (a[i] === b[j]) {
|
||||
raw.push({ type: 'equal', text: a[i] });
|
||||
i++;
|
||||
j++;
|
||||
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
||||
raw.push({ type: 'delete', text: a[i] });
|
||||
i++;
|
||||
} else {
|
||||
raw.push({ type: 'insert', text: b[j] });
|
||||
j++;
|
||||
}
|
||||
}
|
||||
while (i < m) raw.push({ type: 'delete', text: a[i++] });
|
||||
while (j < n) raw.push({ type: 'insert', text: b[j++] });
|
||||
const merged: Array<{ type: 'equal' | 'insert' | 'delete'; text: string }> = [];
|
||||
for (const s of raw) {
|
||||
const last = merged[merged.length - 1];
|
||||
if (last && last.type === s.type) last.text += s.text;
|
||||
else merged.push({ ...s });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** 逐字段比较套餐内容,返回发生变化的字段明细(用于“变动的地方详细列出”) */
|
||||
function fieldChanges(
|
||||
live: StorePackageItemDto | StorePackageViewDto,
|
||||
proposed: StorePackageItemDto | StorePackageViewDto,
|
||||
): FieldChange[] {
|
||||
const changes: FieldChange[] = [];
|
||||
const text = (v: string | number | null | undefined) => (v ?? '').toString().trim();
|
||||
const pushText = (label: string, oldV: string, newV: string) => {
|
||||
if (oldV !== newV) changes.push({ label, old: oldV, now: newV, kind: 'text' });
|
||||
};
|
||||
const pushValue = (label: string, oldV: string, newV: string) => {
|
||||
if (oldV !== newV) changes.push({ label, old: oldV || '(空)', now: newV || '(空)', kind: 'value' });
|
||||
};
|
||||
pushValue('价格', `¥${text(live.price)}`, `¥${text(proposed.price)}`);
|
||||
pushText('套餐名称', text(live.name), text(proposed.name));
|
||||
pushText('菜品内容', text(live.dishes), text(proposed.dishes));
|
||||
pushText('可用时间', text(live.usableTime), text(proposed.usableTime));
|
||||
pushText('其他说明', text(live.otherNotes), text(proposed.otherNotes));
|
||||
const liveImgs = normalizeStorePackageImageUrls(live);
|
||||
const proposedImgs = normalizeStorePackageImageUrls(proposed);
|
||||
if (imageSignature(live) !== imageSignature(proposed)) {
|
||||
changes.push({ label: '图片', old: `${liveImgs.length} 张`, now: `${proposedImgs.length} 张`, kind: 'value' });
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
function diffPackages(live: StorePackageViewDto[], proposed: StorePackageItemDto[]) {
|
||||
const liveMap = new Map(live.map((p, i) => [packageKey(p, i), p]));
|
||||
const proposedMap = new Map(proposed.map((p, i) => [packageKey(p, i), p]));
|
||||
@@ -35,6 +124,7 @@ function diffPackages(live: StorePackageViewDto[], proposed: StorePackageItemDto
|
||||
change: 'added' | 'removed' | 'changed' | 'unchanged';
|
||||
live?: StorePackageViewDto;
|
||||
proposed?: StorePackageItemDto;
|
||||
changes?: FieldChange[];
|
||||
}> = [];
|
||||
|
||||
for (const key of keys) {
|
||||
@@ -49,8 +139,15 @@ function diffPackages(live: StorePackageViewDto[], proposed: StorePackageItemDto
|
||||
l.price !== p.price ||
|
||||
l.dishes !== p.dishes ||
|
||||
(l.usableTime ?? '') !== (p.usableTime ?? '') ||
|
||||
(l.otherNotes ?? '') !== (p.otherNotes ?? '');
|
||||
rows.push({ key, change: changed ? 'changed' : 'unchanged', live: l, proposed: p });
|
||||
(l.otherNotes ?? '') !== (p.otherNotes ?? '') ||
|
||||
imageSignature(l) !== imageSignature(p);
|
||||
rows.push({
|
||||
key,
|
||||
change: changed ? 'changed' : 'unchanged',
|
||||
live: l,
|
||||
proposed: p,
|
||||
changes: changed ? fieldChanges(l, p) : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
@@ -63,12 +160,441 @@ const CHANGE_LABELS = {
|
||||
unchanged: { text: '未变', color: 'default' },
|
||||
} as const;
|
||||
|
||||
/** 文本逐字差异渲染:原行红色删除线标出被删的字,新行绿色标出新增的字 */
|
||||
function TextDiff({ oldText, newText }: { oldText: string; newText: string }) {
|
||||
const segs = diffText(oldText, newText);
|
||||
return (
|
||||
<div style={{ marginTop: 2 }}>
|
||||
<div style={{ lineHeight: 1.6 }}>
|
||||
<Typography.Text type="secondary">原:</Typography.Text>
|
||||
{segs
|
||||
.filter((s) => s.type !== 'insert')
|
||||
.map((s, idx) =>
|
||||
s.type === 'delete' ? (
|
||||
<Typography.Text key={idx} delete style={{ color: '#cf1322' }}>
|
||||
{s.text || '(空)'}
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text key={idx}>{s.text}</Typography.Text>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<div style={{ lineHeight: 1.6 }}>
|
||||
<Typography.Text type="secondary">新:</Typography.Text>
|
||||
{segs
|
||||
.filter((s) => s.type !== 'delete')
|
||||
.map((s, idx) =>
|
||||
s.type === 'insert' ? (
|
||||
<Typography.Text key={idx} style={{ color: '#389e0d' }}>
|
||||
{s.text || '(空)'}
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text key={idx}>{s.text}</Typography.Text>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PackageDetailCard({
|
||||
title,
|
||||
pkg,
|
||||
change,
|
||||
changes,
|
||||
}: {
|
||||
title?: string;
|
||||
pkg: StorePackageItemDto | StorePackageViewDto;
|
||||
change?: keyof typeof CHANGE_LABELS;
|
||||
changes?: FieldChange[];
|
||||
}) {
|
||||
const images = normalizeStorePackageImageUrls(pkg);
|
||||
const meta = change ? CHANGE_LABELS[change] : null;
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 12,
|
||||
padding: 12,
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 8,
|
||||
background: '#fafafa',
|
||||
}}
|
||||
>
|
||||
<Space style={{ marginBottom: 8 }} wrap>
|
||||
{title ? (
|
||||
<Typography.Text type="secondary">{title}</Typography.Text>
|
||||
) : null}
|
||||
{meta ? <Tag color={meta.color}>{meta.text}</Tag> : null}
|
||||
</Space>
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<strong>{pkg.name}</strong>
|
||||
<span style={{ marginLeft: 8 }}>¥{pkg.price}</span>
|
||||
</div>
|
||||
<Typography.Paragraph className="admin-package-audit-text" style={{ marginBottom: 8 }}>
|
||||
{pkg.dishes || '—'}
|
||||
</Typography.Paragraph>
|
||||
{pkg.usableTime ? (
|
||||
<Typography.Paragraph
|
||||
type="secondary"
|
||||
className="admin-package-audit-text"
|
||||
style={{ marginBottom: 4 }}
|
||||
>
|
||||
可用时间:{pkg.usableTime}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
{pkg.otherNotes ? (
|
||||
<Typography.Paragraph
|
||||
type="secondary"
|
||||
className="admin-package-audit-text"
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
其他说明:{pkg.otherNotes}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
{images.length ? (
|
||||
<Image.PreviewGroup>
|
||||
<Space wrap size={8}>
|
||||
{images.map((url) => (
|
||||
<Image
|
||||
key={url}
|
||||
src={url}
|
||||
width={72}
|
||||
height={72}
|
||||
style={{ objectFit: 'cover', borderRadius: 4 }}
|
||||
/>
|
||||
))}
|
||||
</Space>
|
||||
</Image.PreviewGroup>
|
||||
) : (
|
||||
<Typography.Text type="secondary">无套餐图片</Typography.Text>
|
||||
)}
|
||||
{changes && changes.length ? (
|
||||
<div
|
||||
style={{
|
||||
marginTop: 8,
|
||||
padding: 8,
|
||||
background: '#fff7e6',
|
||||
border: '1px solid #ffe7ba',
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
<Typography.Text strong style={{ fontSize: 12 }}>
|
||||
变更明细
|
||||
</Typography.Text>
|
||||
<ul style={{ margin: '6px 0 0', paddingLeft: 18 }}>
|
||||
{changes.map((c) => (
|
||||
<li key={c.label} style={{ marginBottom: 6 }}>
|
||||
<Typography.Text type="secondary">{c.label}:</Typography.Text>
|
||||
{c.kind === 'text' ? (
|
||||
<TextDiff oldText={c.old} newText={c.now} />
|
||||
) : (
|
||||
<>
|
||||
<Typography.Text delete type="secondary">
|
||||
{c.old}
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary"> → </Typography.Text>
|
||||
<Typography.Text strong>{c.now}</Typography.Text>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const INFO_CHANGE_FIELD_LABELS: Record<string, string> = {
|
||||
name: '门店名称',
|
||||
contactPhone: '联系电话',
|
||||
address: '详细地址',
|
||||
intro: '门店简介',
|
||||
benefitUsageRule: '权益券使用规则',
|
||||
latitude: '纬度',
|
||||
longitude: '经度',
|
||||
openTime: '营业开始',
|
||||
closeTime: '营业结束',
|
||||
openTime2: '第二段开始',
|
||||
closeTime2: '第二段结束',
|
||||
avgPrice: '人均费用',
|
||||
};
|
||||
|
||||
function fmtFieldValue(field: string, v: unknown): string {
|
||||
if (v == null || String(v).trim() === '') return '(空)';
|
||||
if (field === 'avgPrice' || field === 'latitude' || field === 'longitude') {
|
||||
return String(v);
|
||||
}
|
||||
return String(v);
|
||||
}
|
||||
|
||||
function InfoChangeAuditPanel({
|
||||
initialRequestId,
|
||||
}: {
|
||||
initialRequestId?: string | null;
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [items, setItems] = useState<StoreInfoChangeRequestDto[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState<string>('PENDING');
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [detail, setDetail] = useState<(StoreInfoChangeRequestDto & { diffs?: StoreInfoChangeFieldDiff[] }) | null>(null);
|
||||
const [rejectOpen, setRejectOpen] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
|
||||
async function reload(nextPage = page, nextStatus = status) {
|
||||
setLoading(true);
|
||||
try {
|
||||
const qs = new URLSearchParams({ page: String(nextPage), pageSize: '20' });
|
||||
if (nextStatus) qs.set('status', nextStatus);
|
||||
const [data, summary] = await Promise.all([
|
||||
request<{ items: StoreInfoChangeRequestDto[]; total: number; page?: number }>(
|
||||
`/admin/store-info-change-requests?${qs}`,
|
||||
),
|
||||
request<{ pendingCount: number }>('/admin/store-info-change-requests/summary'),
|
||||
]);
|
||||
setItems(data.items);
|
||||
setTotal(data.total);
|
||||
setPage(data.page ?? nextPage);
|
||||
setPendingCount(summary.pendingCount ?? 0);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void reload(1, status);
|
||||
}, [status]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialRequestId) void openDetail(initialRequestId);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function openDetail(id: string) {
|
||||
setDetailOpen(true);
|
||||
setDetailLoading(true);
|
||||
setDetail(null);
|
||||
try {
|
||||
const data = await request<StoreInfoChangeRequestDto & { diffs?: StoreInfoChangeFieldDiff[] }>(
|
||||
`/admin/store-info-change-requests/${id}`,
|
||||
);
|
||||
setDetail(data);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '加载详情失败');
|
||||
setDetailOpen(false);
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function audit(id: string, action: 'APPROVE' | 'REJECT', reason?: string) {
|
||||
try {
|
||||
await request(`/admin/store-info-change-requests/${id}/audit`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(
|
||||
action === 'REJECT' ? { action, rejectReason: reason } : { action },
|
||||
),
|
||||
});
|
||||
message.success(action === 'APPROVE' ? '已通过' : '已驳回');
|
||||
setDetailOpen(false);
|
||||
notifyPackageAuditChanged();
|
||||
void reload(page, status);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '操作失败');
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<StoreInfoChangeRequestDto> = [
|
||||
{ title: '门店', dataIndex: 'storeName', render: (_, row) => row.storeName || row.storeId },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: StoreInfoChangeStatus) => (
|
||||
<Tag>{STORE_INFO_CHANGE_STATUS_LABELS[v] ?? v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '变更字段',
|
||||
render: (_, row) =>
|
||||
row.changedFields?.length
|
||||
? row.changedFields.map((f) => (
|
||||
<Tag key={f}>{INFO_CHANGE_FIELD_LABELS[f] ?? f}</Tag>
|
||||
))
|
||||
: '—',
|
||||
},
|
||||
{
|
||||
title: '提交方',
|
||||
render: (_, row) =>
|
||||
row.submitterType === 'PARTNER' ? '合伙人' : row.submitterType === 'SHOP' ? '门店' : '总部',
|
||||
},
|
||||
{ title: '提交时间', dataIndex: 'createdAt', render: (v) => fmtTime(String(v)) },
|
||||
{
|
||||
title: '操作',
|
||||
render: (_, row) => (
|
||||
<Space>
|
||||
<Button type="link" onClick={() => void openDetail(row.id)}>
|
||||
查看
|
||||
</Button>
|
||||
{row.status === 'PENDING' ? (
|
||||
<>
|
||||
<Button type="link" onClick={() => void audit(row.id, 'APPROVE')}>
|
||||
通过
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
danger
|
||||
onClick={() => {
|
||||
setActiveId(row.id);
|
||||
setRejectReason('');
|
||||
setRejectOpen(true);
|
||||
}}
|
||||
>
|
||||
驳回
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
row.rejectReason || null
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
{(['PENDING', 'APPROVED', 'REJECTED', ''] as const).map((s) => (
|
||||
<Button
|
||||
key={s || 'all'}
|
||||
type={status === s ? 'primary' : 'default'}
|
||||
onClick={() => setStatus(s)}
|
||||
>
|
||||
{s === 'PENDING' ? (
|
||||
<Badge count={pendingCount} size="small" offset={[8, -2]}>
|
||||
{STORE_INFO_CHANGE_STATUS_LABELS.PENDING}
|
||||
</Badge>
|
||||
) : s ? (
|
||||
STORE_INFO_CHANGE_STATUS_LABELS[s]
|
||||
) : (
|
||||
'全部'
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
pagination={{
|
||||
current: page,
|
||||
total,
|
||||
pageSize: 20,
|
||||
onChange: (p) => void reload(p, status),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Drawer
|
||||
title={detail ? `${detail.storeName || detail.storeId} · 信息变更` : '信息变更详情'}
|
||||
width={680}
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
extra={
|
||||
detail?.status === 'PENDING' ? (
|
||||
<Space>
|
||||
<Button onClick={() => void audit(detail.id, 'APPROVE')}>通过</Button>
|
||||
<Button
|
||||
danger
|
||||
onClick={() => {
|
||||
setActiveId(detail.id);
|
||||
setRejectReason('');
|
||||
setRejectOpen(true);
|
||||
}}
|
||||
>
|
||||
驳回
|
||||
</Button>
|
||||
</Space>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detailLoading ? (
|
||||
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||
) : detail ? (
|
||||
<>
|
||||
<Space style={{ marginBottom: 16 }} wrap>
|
||||
<Tag>{STORE_INFO_CHANGE_STATUS_LABELS[detail.status]}</Tag>
|
||||
<Typography.Text type="secondary">
|
||||
提交方:{detail.submitterType === 'PARTNER' ? '合伙人' : detail.submitterType === 'SHOP' ? '门店' : '总部'} · {fmtTime(detail.createdAt)}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{detail.rejectReason ? (
|
||||
<Typography.Paragraph type="danger">驳回原因:{detail.rejectReason}</Typography.Paragraph>
|
||||
) : null}
|
||||
{detail.diffs && detail.diffs.length ? (
|
||||
<Descriptions column={1} bordered size="small">
|
||||
{detail.diffs.map((d) => (
|
||||
<Descriptions.Item
|
||||
key={d.field}
|
||||
label={INFO_CHANGE_FIELD_LABELS[d.field] ?? d.field}
|
||||
>
|
||||
<span>
|
||||
<Typography.Text delete type="secondary">
|
||||
{fmtFieldValue(d.field, d.live)}
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary"> → </Typography.Text>
|
||||
<Typography.Text strong>
|
||||
{fmtFieldValue(d.field, d.proposed)}
|
||||
</Typography.Text>
|
||||
</span>
|
||||
</Descriptions.Item>
|
||||
))}
|
||||
</Descriptions>
|
||||
) : (
|
||||
<Typography.Text type="secondary">无变更字段明细</Typography.Text>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</Drawer>
|
||||
|
||||
<Modal
|
||||
title="驳回信息变更"
|
||||
open={rejectOpen}
|
||||
onCancel={() => setRejectOpen(false)}
|
||||
onOk={() => {
|
||||
if (!activeId) return;
|
||||
if (!rejectReason.trim()) {
|
||||
message.warning('请填写驳回原因');
|
||||
return;
|
||||
}
|
||||
void audit(activeId, 'REJECT', rejectReason.trim());
|
||||
setRejectOpen(false);
|
||||
}}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
value={rejectReason}
|
||||
placeholder="驳回原因"
|
||||
onChange={(e) => setRejectReason(e.target.value)}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function StorePackageAuditsPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [items, setItems] = useState<StorePackageChangeRequestDto[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState<string>('PENDING');
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const [rejectOpen, setRejectOpen] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
@@ -84,12 +610,14 @@ export default function StorePackageAuditsPage() {
|
||||
pageSize: '20',
|
||||
});
|
||||
if (nextStatus) qs.set('status', nextStatus);
|
||||
const data = await request<Paginated<StorePackageChangeRequestDto>>(
|
||||
`/admin/store-package-audits?${qs}`,
|
||||
);
|
||||
const [data, summary] = await Promise.all([
|
||||
request<Paginated<StorePackageChangeRequestDto>>(`/admin/store-package-audits?${qs}`),
|
||||
request<StorePackageAuditSummaryDto>('/admin/store-package-audits/summary'),
|
||||
]);
|
||||
setItems(data.items);
|
||||
setTotal(data.total);
|
||||
setPage(data.page);
|
||||
setPendingCount(summary.pendingCount ?? 0);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '加载失败');
|
||||
} finally {
|
||||
@@ -101,6 +629,17 @@ export default function StorePackageAuditsPage() {
|
||||
void reload(1, status);
|
||||
}, [status]);
|
||||
|
||||
// 从门店详情 / 门店列表跳转过来时,带 requestId 自动打开审核(对比)抽屉
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialTab = searchParams.get('tab') === 'info' ? 'info' : 'package';
|
||||
const [activeTab, setActiveTab] = useState<string>(initialTab);
|
||||
const infoRequestId = searchParams.get('infoRequestId');
|
||||
useEffect(() => {
|
||||
const rid = searchParams.get('requestId');
|
||||
if (rid) void openDetail(rid);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function openDetail(id: string) {
|
||||
setDetailOpen(true);
|
||||
setDetailLoading(true);
|
||||
@@ -126,6 +665,7 @@ export default function StorePackageAuditsPage() {
|
||||
});
|
||||
message.success(action === 'APPROVE' ? '已通过' : '已驳回');
|
||||
setDetailOpen(false);
|
||||
notifyPackageAuditChanged();
|
||||
void reload(page, status);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '操作失败');
|
||||
@@ -133,54 +673,12 @@ export default function StorePackageAuditsPage() {
|
||||
}
|
||||
|
||||
const diffRows = detail ? diffPackages(detail.livePackages ?? [], detail.packages ?? []) : [];
|
||||
|
||||
const diffColumns: ColumnsType<(typeof diffRows)[number]> = [
|
||||
{
|
||||
title: '变更',
|
||||
dataIndex: 'change',
|
||||
width: 72,
|
||||
render: (v: keyof typeof CHANGE_LABELS) => {
|
||||
const meta = CHANGE_LABELS[v];
|
||||
return <Tag color={meta.color}>{meta.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '当前线上',
|
||||
render: (_, row) =>
|
||||
row.live ? (
|
||||
<div>
|
||||
<div><strong>{row.live.name}</strong> · ¥{row.live.price}</div>
|
||||
<Typography.Text type="secondary">{row.live.dishes}</Typography.Text>
|
||||
{row.live.usableTime ? (
|
||||
<div><Typography.Text type="secondary">可用:{row.live.usableTime}</Typography.Text></div>
|
||||
) : null}
|
||||
{row.live.otherNotes ? (
|
||||
<div><Typography.Text type="secondary">备注:{row.live.otherNotes}</Typography.Text></div>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '申请变更',
|
||||
render: (_, row) =>
|
||||
row.proposed ? (
|
||||
<div>
|
||||
<div><strong>{row.proposed.name}</strong> · ¥{row.proposed.price}</div>
|
||||
<Typography.Text type="secondary">{row.proposed.dishes}</Typography.Text>
|
||||
{row.proposed.usableTime ? (
|
||||
<div><Typography.Text type="secondary">可用:{row.proposed.usableTime}</Typography.Text></div>
|
||||
) : null}
|
||||
{row.proposed.otherNotes ? (
|
||||
<div><Typography.Text type="secondary">备注:{row.proposed.otherNotes}</Typography.Text></div>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
];
|
||||
const changeByKey = new Map(diffRows.map((row) => [row.key, row.change]));
|
||||
const changesByKey = new Map(diffRows.map((row) => [row.key, row.changes]));
|
||||
const addedCount = diffRows.filter((r) => r.change === 'added').length;
|
||||
const removedCount = diffRows.filter((r) => r.change === 'removed').length;
|
||||
const changedCount = diffRows.filter((r) => r.change === 'changed').length;
|
||||
const unchangedCount = diffRows.filter((r) => r.change === 'unchanged').length;
|
||||
|
||||
const columns: ColumnsType<StorePackageChangeRequestDto> = [
|
||||
{ title: '门店', dataIndex: 'storeName', render: (_, row) => row.storeName || row.storeId },
|
||||
@@ -188,7 +686,7 @@ export default function StorePackageAuditsPage() {
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: StorePackageChangeRequestDto['status']) => (
|
||||
<Tag>{STORE_PACKAGE_CHANGE_STATUS_LABELS[v] ?? v}</Tag>
|
||||
<Tag>{HQ_PACKAGE_STATUS_LABELS[v] ?? v}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -234,30 +732,57 @@ export default function StorePackageAuditsPage() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Typography.Title level={4}>套餐变更审核</Typography.Title>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
{(['PENDING', 'APPROVED', 'REJECTED', ''] as const).map((s) => (
|
||||
<Button key={s || 'all'} type={status === s ? 'primary' : 'default'} onClick={() => setStatus(s)}>
|
||||
{s ? STORE_PACKAGE_CHANGE_STATUS_LABELS[s as keyof typeof STORE_PACKAGE_CHANGE_STATUS_LABELS] : '全部'}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
pagination={{
|
||||
current: page,
|
||||
total,
|
||||
pageSize: 20,
|
||||
onChange: (p) => void reload(p, status),
|
||||
}}
|
||||
<Typography.Title level={4}>审核通知</Typography.Title>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
{
|
||||
key: 'package',
|
||||
label: '套餐审核',
|
||||
children: (
|
||||
<>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
{(['PENDING', 'APPROVED', 'REJECTED', ''] as const).map((s) => (
|
||||
<Button key={s || 'all'} type={status === s ? 'primary' : 'default'} onClick={() => setStatus(s)}>
|
||||
{s === 'PENDING' ? (
|
||||
<Badge count={pendingCount} size="small" offset={[8, -2]}>
|
||||
{HQ_PACKAGE_STATUS_LABELS.PENDING}
|
||||
</Badge>
|
||||
) : s ? (
|
||||
HQ_PACKAGE_STATUS_LABELS[s]
|
||||
) : (
|
||||
'全部'
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
pagination={{
|
||||
current: page,
|
||||
total,
|
||||
pageSize: 20,
|
||||
onChange: (p) => void reload(p, status),
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'info',
|
||||
label: '信息变更',
|
||||
children: <InfoChangeAuditPanel initialRequestId={infoRequestId} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<Drawer
|
||||
title={detail ? `${detail.storeName || detail.storeId} · 套餐变更` : '套餐变更详情'}
|
||||
width={720}
|
||||
width={880}
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
extra={
|
||||
@@ -282,8 +807,8 @@ export default function StorePackageAuditsPage() {
|
||||
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||
) : detail ? (
|
||||
<>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Tag>{STORE_PACKAGE_CHANGE_STATUS_LABELS[detail.status]}</Tag>
|
||||
<Space style={{ marginBottom: 16 }} wrap>
|
||||
<Tag>{HQ_PACKAGE_STATUS_LABELS[detail.status]}</Tag>
|
||||
<Typography.Text type="secondary">
|
||||
提交方:{detail.submitterType === 'PARTNER' ? '合伙人' : '门店'} · {fmtTime(detail.createdAt)}
|
||||
</Typography.Text>
|
||||
@@ -291,16 +816,54 @@ export default function StorePackageAuditsPage() {
|
||||
{detail.rejectReason ? (
|
||||
<Typography.Paragraph type="danger">驳回原因:{detail.rejectReason}</Typography.Paragraph>
|
||||
) : null}
|
||||
<Typography.Paragraph type="secondary">
|
||||
线上 {detail.livePackages?.length ?? 0} 条 → 申请 {detail.packages?.length ?? 0} 条
|
||||
</Typography.Paragraph>
|
||||
<Table
|
||||
size="small"
|
||||
rowKey="key"
|
||||
columns={diffColumns}
|
||||
dataSource={diffRows}
|
||||
pagination={false}
|
||||
/>
|
||||
<Space direction="vertical" size={4} style={{ marginBottom: 12 }}>
|
||||
<Typography.Text type="secondary">
|
||||
线上已审核 {detail.livePackages?.length ?? 0} 条 · 待审核 {detail.packages?.length ?? 0} 条
|
||||
</Typography.Text>
|
||||
<Space wrap>
|
||||
<Tag color="green">新增 {addedCount}</Tag>
|
||||
<Tag color="red">删除 {removedCount}</Tag>
|
||||
<Tag color="orange">变更 {changedCount}</Tag>
|
||||
{unchangedCount ? <Tag>未变 {unchangedCount}</Tag> : null}
|
||||
</Space>
|
||||
</Space>
|
||||
<div className="admin-package-audit-cols">
|
||||
<div className="admin-package-audit-col">
|
||||
<Typography.Title level={5} style={{ marginTop: 0 }}>
|
||||
线上已审核套餐
|
||||
</Typography.Title>
|
||||
{(detail.livePackages ?? []).length ? (
|
||||
(detail.livePackages ?? []).map((pkg, index) => (
|
||||
<PackageDetailCard
|
||||
key={`live-${packageKey(pkg, index)}`}
|
||||
title={`套餐 ${index + 1}`}
|
||||
pkg={pkg}
|
||||
change={changeByKey.get(packageKey(pkg, index))}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<Typography.Text type="secondary">暂无线上套餐</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
<div className="admin-package-audit-col">
|
||||
<Typography.Title level={5} style={{ marginTop: 0 }}>
|
||||
待审核套餐
|
||||
</Typography.Title>
|
||||
{(detail.packages ?? []).length ? (
|
||||
(detail.packages ?? []).map((pkg, index) => (
|
||||
<PackageDetailCard
|
||||
key={`pending-${packageKey(pkg, index)}`}
|
||||
title={`套餐 ${index + 1}`}
|
||||
pkg={pkg}
|
||||
change={changeByKey.get(packageKey(pkg, index))}
|
||||
changes={changesByKey.get(packageKey(pkg, index))}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<Typography.Text type="secondary">暂无待审核套餐</Typography.Text>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</Drawer>
|
||||
|
||||
@@ -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,
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { FormInstance } from 'antd/es/form';
|
||||
import { EnvironmentOutlined } from '@ant-design/icons';
|
||||
import { isStoreContactPhone, STORE_CONTACT_PHONE_HINT } from '@dukang/domain';
|
||||
import { request, type Paginated } from '../lib/api';
|
||||
import {
|
||||
ADMIN_OPTIONS_PAGE_SIZE,
|
||||
@@ -42,7 +43,9 @@ import ChinaRegionCascader from '../components/ChinaRegionCascader';
|
||||
import OssUpload from '../components/OssUpload';
|
||||
import MultiImageUpload from '../components/MultiImageUpload';
|
||||
import TencentLocPickerModal from '../components/TencentLocPickerModal';
|
||||
import AdminStorePackagesSection from '../components/AdminStorePackagesSection';
|
||||
import AdminStorePackagesSection, {
|
||||
type AdminStorePackagesHandle,
|
||||
} from '../components/AdminStorePackagesSection';
|
||||
|
||||
const CREATE_STEPS = [
|
||||
{ title: '基本信息' },
|
||||
@@ -114,7 +117,7 @@ function StoreAuditMediaEditor() {
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message="可替换或删除门头照 / 环境照 / 签约合同,点击右上角「保存修改」后生效。环境照最多 20 张。"
|
||||
message="可替换或删除门头照 / 环境照 / 签约合同,点击右上角「保存修改」后生效。环境照、签约合同均最多 20 张。套餐请在「套餐」页签编辑,同样由「保存修改」一并提交。"
|
||||
/>
|
||||
<Form.Item name="coverUrl" label="门头照">
|
||||
<OssUpload bizType="STORE_TITLE" mediaType="IMAGE" />
|
||||
@@ -131,8 +134,20 @@ function StoreAuditMediaEditor() {
|
||||
tip="环境照支持一次选择多张批量上传"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="contractUrl" label="签约合同" style={{ marginTop: 16 }}>
|
||||
<OssUpload bizType="STORE_CONTRACT" mediaType="FILE" accept="image/*,.pdf" />
|
||||
<Form.Item
|
||||
name="contractUrls"
|
||||
label="签约合同"
|
||||
style={{ marginTop: 16 }}
|
||||
extra="支持多张合同照片(如首页、盖章页),也可上传 PDF,最多 20 个。"
|
||||
>
|
||||
<MultiImageUpload
|
||||
bizType="STORE_CONTRACT"
|
||||
mediaType="FILE"
|
||||
accept="image/*,.pdf"
|
||||
maxCount={20}
|
||||
buttonText="批量上传合同"
|
||||
tip="合同支持一次选择多张照片批量上传,最多 20 个"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
);
|
||||
@@ -175,6 +190,10 @@ type StoreRow = {
|
||||
createdAt: string;
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
visibilityPhones?: string[];
|
||||
/** 该门店当前待审核套餐变更的 requestId(无则为空) */
|
||||
pendingPackageAuditId?: string | null;
|
||||
/** 该门店当前待审核信息变更的 requestId(无则为空) */
|
||||
pendingInfoChangeId?: string | null;
|
||||
isTest?: boolean;
|
||||
cityRef?: { name: string; code: string };
|
||||
partner?: { id?: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||
@@ -251,6 +270,7 @@ export default function StoresPage() {
|
||||
const [filterPartners, setFilterPartners] = useState<PartnerOption[]>([]);
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const packagesRef = useRef<AdminStorePackagesHandle>(null);
|
||||
const [rejectOpen, setRejectOpen] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [auditing, setAuditing] = useState(false);
|
||||
@@ -365,12 +385,18 @@ export default function StoresPage() {
|
||||
account?.phone ||
|
||||
(typeof d.phone === 'string' ? d.phone : undefined);
|
||||
const storePhone = typeof d.phone === 'string' ? d.phone : undefined;
|
||||
const contactPhone =
|
||||
(typeof d.contactPhone === 'string' && d.contactPhone.trim()) ||
|
||||
storePhone ||
|
||||
loginPhone ||
|
||||
'';
|
||||
const phoneMismatchNow = !!(loginPhone && storePhone && loginPhone !== storePhone);
|
||||
setPhoneMismatch(phoneMismatchNow ? String(loginPhone) : null);
|
||||
editForm.setFieldsValue({
|
||||
name: d.name,
|
||||
// 以门店手机号为准保存;若与账号登录号不一致,保存时会强制同步到登录账号
|
||||
phone: storePhone || loginPhone,
|
||||
// 登录手机号(老板);与 StoreAccount 同步
|
||||
phone: loginPhone || storePhone,
|
||||
contactPhone,
|
||||
intro: d.intro,
|
||||
benefitUsageRule:
|
||||
d.benefitUsageRule != null &&
|
||||
@@ -384,9 +410,9 @@ export default function StoresPage() {
|
||||
const urls = envs.map((item) => item.url).filter(Boolean);
|
||||
return urls;
|
||||
})(),
|
||||
contractUrl: (() => {
|
||||
contractUrls: (() => {
|
||||
const { contracts } = collectMediaUrls(d);
|
||||
return contracts[0]?.url || '';
|
||||
return contracts.map((item) => item.url).filter(Boolean);
|
||||
})(),
|
||||
province: d.province,
|
||||
city: d.cityName,
|
||||
@@ -428,11 +454,14 @@ export default function StoresPage() {
|
||||
const payload = {
|
||||
name: v.name,
|
||||
phone: v.phone,
|
||||
contactPhone: String(v.contactPhone || '').trim() || v.phone,
|
||||
coverUrl: v.coverUrl ?? '',
|
||||
envPhotoUrls: Array.isArray(v.envPhotoUrls)
|
||||
? v.envPhotoUrls.map((u: string) => String(u || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
contractUrl: v.contractUrl ?? '',
|
||||
contractUrls: Array.isArray(v.contractUrls)
|
||||
? v.contractUrls.map((u: string) => String(u || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
intro: v.intro,
|
||||
benefitUsageRule:
|
||||
typeof v.benefitUsageRule === 'string' &&
|
||||
@@ -465,7 +494,10 @@ export default function StoresPage() {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
message.success('门店信息已保存');
|
||||
const packagesResult = await packagesRef.current?.saveIfLoaded({ quiet: true });
|
||||
message.success(
|
||||
packagesResult?.skipped === false ? '门店信息与套餐已保存' : '门店信息已保存',
|
||||
);
|
||||
setDetail(updated);
|
||||
setPhoneMismatch(null);
|
||||
void reload();
|
||||
@@ -592,6 +624,7 @@ export default function StoresPage() {
|
||||
}
|
||||
|
||||
const envPhotoUrls = (values.envPhotoUrls ?? []).map((u: string) => u?.trim()).filter(Boolean) as string[];
|
||||
const contractUrls = (values.contractUrls ?? []).map((u: string) => u?.trim()).filter(Boolean) as string[];
|
||||
await request('/admin/stores', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
@@ -602,6 +635,7 @@ export default function StoresPage() {
|
||||
city: values.city,
|
||||
name: values.name.trim(),
|
||||
phone: values.phone.trim(),
|
||||
contactPhone: String(values.contactPhone || values.phone || '').trim(),
|
||||
district: values.district.trim(),
|
||||
address: values.address.trim(),
|
||||
...(values.latitude != null &&
|
||||
@@ -625,7 +659,7 @@ export default function StoresPage() {
|
||||
: {}),
|
||||
coverUrl: values.coverUrl?.trim() || undefined,
|
||||
envPhotoUrls: envPhotoUrls.length ? envPhotoUrls : undefined,
|
||||
contractUrl: values.contractUrl?.trim() || undefined,
|
||||
contractUrls: contractUrls.length ? contractUrls : undefined,
|
||||
bankAccountName: values.bankAccountName.trim(),
|
||||
bankAccountNo: values.bankAccountNo.replace(/\s/g, ''),
|
||||
bankBranch: values.bankBranch.trim(),
|
||||
@@ -655,19 +689,37 @@ export default function StoresPage() {
|
||||
title: '封面', dataIndex: 'coverUrl', width: 72,
|
||||
render: (url) => url ? <Image src={url} width={48} height={48} style={{ objectFit: 'cover', borderRadius: 4 }} /> : '—',
|
||||
},
|
||||
{ title: '门店名', dataIndex: 'name', width: 160, render: (v, row) => (
|
||||
<Space size={4}>
|
||||
<span>{v}</span>
|
||||
{row.isTest ? <Tag color="orange">测试</Tag> : null}
|
||||
</Space>
|
||||
) },
|
||||
{
|
||||
title: '门店名',
|
||||
dataIndex: 'name',
|
||||
width: 180,
|
||||
ellipsis: { showTitle: false },
|
||||
render: (v: string, row) => {
|
||||
const name = v || '—';
|
||||
return (
|
||||
<Space size={4} style={{ maxWidth: '100%' }} wrap={false}>
|
||||
<Typography.Text ellipsis={{ tooltip: name }} style={{ maxWidth: row.isTest ? 110 : 160 }}>
|
||||
{name}
|
||||
</Typography.Text>
|
||||
{row.isTest ? <Tag color="orange">测试</Tag> : null}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '分类',
|
||||
width: 100,
|
||||
ellipsis: true,
|
||||
render: (_, row) => row.category?.name || '—',
|
||||
},
|
||||
{ title: '城市', dataIndex: 'cityName', width: 80 },
|
||||
{ title: '电话', dataIndex: 'phone', width: 120 },
|
||||
{ title: '城市', dataIndex: 'cityName', width: 80, ellipsis: true },
|
||||
{ title: '登录号', dataIndex: 'phone', width: 120 },
|
||||
{
|
||||
title: '联系电话',
|
||||
dataIndex: 'contactPhone',
|
||||
width: 120,
|
||||
render: (v: string | null | undefined, row) => v || row.phone,
|
||||
},
|
||||
{
|
||||
title: '营业状态', dataIndex: 'status', width: 90,
|
||||
render: (s) => <Tag>{STORE_STATUS_LABELS[s] || s}</Tag>,
|
||||
@@ -678,10 +730,10 @@ export default function StoresPage() {
|
||||
const status = s || 'APPROVED';
|
||||
const color = status === 'PENDING' ? 'orange' : status === 'REJECTED' ? 'red' : 'green';
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Space direction="vertical" size={0} style={{ maxWidth: '100%' }}>
|
||||
<Tag color={color}>{STORE_AUDIT_STATUS_LABELS[status] || status}</Tag>
|
||||
{status === 'REJECTED' && row.rejectReason ? (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }} ellipsis>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12, maxWidth: 88 }} ellipsis={{ tooltip: row.rejectReason }}>
|
||||
{row.rejectReason}
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
@@ -693,8 +745,16 @@ export default function StoresPage() {
|
||||
title: '开城合伙人',
|
||||
dataIndex: 'partner',
|
||||
width: 140,
|
||||
render: (partner: StoreRow['partner']) =>
|
||||
partner ? partnerOptionLabel({ id: partner.id ?? '', ...partner }) : '—',
|
||||
ellipsis: { showTitle: false },
|
||||
render: (partner: StoreRow['partner']) => {
|
||||
if (!partner) return '—';
|
||||
const label = partnerOptionLabel({ id: partner.id ?? '', ...partner });
|
||||
return (
|
||||
<Typography.Text ellipsis={{ tooltip: label }} style={{ maxWidth: 124 }}>
|
||||
{label}
|
||||
</Typography.Text>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '可见',
|
||||
@@ -705,14 +765,59 @@ export default function StoresPage() {
|
||||
},
|
||||
{ title: '介绍', dataIndex: 'intro', width: 160, ellipsis: true, render: (v) => v || '—' },
|
||||
{ title: '排序', dataIndex: 'sortOrder', width: 70 },
|
||||
{ title: '店长', dataIndex: ['account', 'name'], width: 90, render: (v) => v || '—' },
|
||||
{ title: '店长', dataIndex: ['account', 'name'], width: 90, ellipsis: true, render: (v) => v || '—' },
|
||||
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||
{
|
||||
title: '操作', width: 140,
|
||||
title: '操作',
|
||||
width: 280,
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space size={0}>
|
||||
<Space size={0} wrap>
|
||||
<Button type="link" size="small" onClick={() => void openStoreDetail(row)}>详情</Button>
|
||||
<Button type="link" size="small" onClick={() => navigate(`/store-ratings?storeId=${row.id}`)}>评价</Button>
|
||||
{row.pendingPackageAuditId ? (
|
||||
<>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => navigate(`/store-package-audits?requestId=${row.pendingPackageAuditId}`)}
|
||||
>
|
||||
审核套餐
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => navigate(`/store-package-audits?requestId=${row.pendingPackageAuditId}`)}
|
||||
>
|
||||
对比
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{row.pendingInfoChangeId ? (
|
||||
<>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => navigate(`/store-package-audits?tab=info&infoRequestId=${row.pendingInfoChangeId}`)}
|
||||
>
|
||||
审核信息
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => navigate(`/store-package-audits?tab=info&infoRequestId=${row.pendingInfoChangeId}`)}
|
||||
>
|
||||
对比
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => navigate(`/finance/store-bills?storeId=${row.id}`)}
|
||||
>
|
||||
提现
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -780,8 +885,24 @@ export default function StoresPage() {
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1200 }}
|
||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||
<Table
|
||||
rowKey="id"
|
||||
className="admin-table-nowrap"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1720 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: true,
|
||||
onChange: (p, ps) => {
|
||||
setPage(p);
|
||||
setPageSize(ps);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<Drawer title="门店详情" width={760} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||
extra={detail && (
|
||||
<Space wrap>
|
||||
@@ -878,18 +999,34 @@ export default function StoresPage() {
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: 16 }}
|
||||
message={`登录账号手机号仍为 ${phoneMismatch},与门店手机号不一致。请点击右上角「保存修改」同步,否则门店端无法用新号登录。`}
|
||||
message={`主账号登录号为 ${phoneMismatch},与门店登录字段不一致。保存「登录手机号」将同步到门店端登录账号。`}
|
||||
/>
|
||||
) : null}
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}><Input /></Form.Item>
|
||||
<Form.Item
|
||||
name="phone"
|
||||
label="登录手机号"
|
||||
label="登录手机号(老板)"
|
||||
rules={[{ required: true }]}
|
||||
extra="门店端短信登录使用此号码;修改后需用新号重新登录"
|
||||
extra="门店端主账号短信登录;修改后需用新号重新登录"
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="contactPhone"
|
||||
label="联系电话(店长/对外)"
|
||||
rules={[
|
||||
{ required: true, message: '请填写对外联系电话' },
|
||||
{
|
||||
validator: (_, value) =>
|
||||
isStoreContactPhone(String(value || ''))
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error(STORE_CONTACT_PHONE_HINT)),
|
||||
},
|
||||
]}
|
||||
extra="用户端门店详情展示与拨号使用此号码,可与登录号不同,支持座机"
|
||||
>
|
||||
<Input placeholder="手机号或座机,如 0379-8888888" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="categoryParentId"
|
||||
label="门店分类(大类)"
|
||||
@@ -1066,7 +1203,8 @@ export default function StoresPage() {
|
||||
{
|
||||
key: 'packages',
|
||||
label: '套餐',
|
||||
children: <AdminStorePackagesSection storeId={String(detail.id)} />,
|
||||
forceRender: true,
|
||||
children: <AdminStorePackagesSection ref={packagesRef} storeId={String(detail.id)} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -1164,8 +1302,24 @@ export default function StoresPage() {
|
||||
<Form.Item name="name" label="门店名称" rules={[{ required: true, message: '请填写门店名称' }]}>
|
||||
<Input placeholder="请输入门店名称" />
|
||||
</Form.Item>
|
||||
<Form.Item name="phone" label="门店手机号(登录账号)" rules={[{ required: true, message: '请填写门店手机号' }]}>
|
||||
<Input placeholder="11位手机号" />
|
||||
<Form.Item name="phone" label="登录手机号(老板)" rules={[{ required: true, message: '请填写登录手机号' }]}>
|
||||
<Input placeholder="门店端主账号登录" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="contactPhone"
|
||||
label="联系电话(店长/对外)"
|
||||
extra="用户端拨号展示;留空则与登录号相同。支持座机"
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value) => {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw || isStoreContactPhone(raw)) return Promise.resolve();
|
||||
return Promise.reject(new Error(STORE_CONTACT_PHONE_HINT));
|
||||
},
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Input placeholder="手机号或座机,如 0379-8888888" />
|
||||
</Form.Item>
|
||||
<Form.Item name="sortOrder" label="排序" extra="数值越小越靠前">
|
||||
<InputNumber min={0} precision={0} style={{ width: '100%' }} placeholder="0" />
|
||||
@@ -1266,8 +1420,19 @@ export default function StoresPage() {
|
||||
tip="环境照支持一次选择多张批量上传"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="contractUrl" label="签约合同">
|
||||
<OssUpload bizType="STORE_CONTRACT" mediaType="FILE" accept="image/*,.pdf" />
|
||||
<Form.Item
|
||||
name="contractUrls"
|
||||
label="签约合同"
|
||||
extra="选填;支持多张合同照片或 PDF,最多 20 个"
|
||||
>
|
||||
<MultiImageUpload
|
||||
bizType="STORE_CONTRACT"
|
||||
mediaType="FILE"
|
||||
accept="image/*,.pdf"
|
||||
maxCount={20}
|
||||
buttonText="批量上传合同"
|
||||
tip="合同支持一次选择多张照片批量上传,最多 20 个"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<div style={{ display: createStep === 2 ? 'block' : 'none' }}>
|
||||
|
||||
@@ -30,6 +30,13 @@ type UserOrderRow = {
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
/** 好客权益金额展示:0 与空值统一显示占位,避免整列都是 ¥0.00 干扰 */
|
||||
function fmtBenefit(v: number | null | undefined) {
|
||||
const n = Number(v ?? 0);
|
||||
if (!Number.isFinite(n) || n <= 0) return '—';
|
||||
return `¥${n.toFixed(2)}`;
|
||||
}
|
||||
|
||||
type UserBehaviorLog = {
|
||||
id: string;
|
||||
eventName: string;
|
||||
@@ -315,6 +322,39 @@ export default function UsersPage() {
|
||||
render: (v) => (v ? <Tag color="blue">已合并</Tag> : '—'),
|
||||
},
|
||||
{ title: '订单数', dataIndex: 'orderCount', width: 80 },
|
||||
{
|
||||
title: '剩余权益',
|
||||
dataIndex: 'benefitBalance',
|
||||
width: 110,
|
||||
align: 'right',
|
||||
sorter: (a, b) => Number(a.benefitBalance ?? 0) - Number(b.benefitBalance ?? 0),
|
||||
render: (v: number | undefined) =>
|
||||
Number(v ?? 0) > 0 ? (
|
||||
<Typography.Text strong style={{ color: '#cf1322' }}>
|
||||
{fmtBenefit(v)}
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<Typography.Text type="secondary">—</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '已用权益',
|
||||
dataIndex: 'benefitUsedAmount',
|
||||
width: 110,
|
||||
align: 'right',
|
||||
sorter: (a, b) => Number(a.benefitUsedAmount ?? 0) - Number(b.benefitUsedAmount ?? 0),
|
||||
render: (v: number | undefined) => (
|
||||
<Typography.Text type="secondary">{fmtBenefit(v)}</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '累计权益',
|
||||
dataIndex: 'benefitTotalAmount',
|
||||
width: 110,
|
||||
align: 'right',
|
||||
sorter: (a, b) => Number(a.benefitTotalAmount ?? 0) - Number(b.benefitTotalAmount ?? 0),
|
||||
render: (v: number | undefined) => fmtBenefit(v),
|
||||
},
|
||||
{
|
||||
title: '注册时间',
|
||||
dataIndex: 'createdAt',
|
||||
@@ -389,7 +429,7 @@ export default function UsersPage() {
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1500 }}
|
||||
scroll={{ x: 1830 }}
|
||||
rowSelection={canDeleteUsers ? {
|
||||
selectedRowKeys,
|
||||
preserveSelectedRowKeys: true,
|
||||
@@ -461,6 +501,18 @@ export default function UsersPage() {
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="被合并访客数">{detail.mergedFromCount ?? 0}</Descriptions.Item>
|
||||
<Descriptions.Item label="订单/地址">{detail.orderCount} / {detail.addressCount}</Descriptions.Item>
|
||||
<Descriptions.Item label="好客权益">
|
||||
<Space size={16} wrap>
|
||||
<span>
|
||||
剩余{' '}
|
||||
<Typography.Text strong style={{ color: '#cf1322' }}>
|
||||
{fmtBenefit(detail.benefitBalance)}
|
||||
</Typography.Text>
|
||||
</span>
|
||||
<span>已用 {fmtBenefit(detail.benefitUsedAmount)}</span>
|
||||
<span>累计 {fmtBenefit(detail.benefitTotalAmount)}</span>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="注册时间">
|
||||
{new Date(detail.createdAt).toLocaleString('zh-CN')}
|
||||
</Descriptions.Item>
|
||||
|
||||
@@ -51,13 +51,35 @@ type BillItem = {
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
UNPAID: '未打款',
|
||||
PAID: '已打款',
|
||||
NO_PAYMENT_NEEDED: '无需打款',
|
||||
};
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
UNPAID: 'red',
|
||||
PAID: 'green',
|
||||
NO_PAYMENT_NEEDED: 'default',
|
||||
};
|
||||
|
||||
function isZeroPayable(amount: number | string | null | undefined) {
|
||||
return Number(amount ?? 0) === 0;
|
||||
}
|
||||
|
||||
/** 应付为 0 时展示「无需打款」(灰),否则按 DB 打款状态 */
|
||||
function displayWineryStatus(status: string, wineryAmount: number | string) {
|
||||
if (isZeroPayable(wineryAmount)) {
|
||||
return { key: 'NO_PAYMENT_NEEDED', label: STATUS_LABELS.NO_PAYMENT_NEEDED, color: STATUS_COLORS.NO_PAYMENT_NEEDED };
|
||||
}
|
||||
return {
|
||||
key: status,
|
||||
label: STATUS_LABELS[status] || status,
|
||||
color: STATUS_COLORS[status] || 'default',
|
||||
};
|
||||
}
|
||||
|
||||
function canConfirmWineryPay(row: { status: string; wineryAmount: number | string }) {
|
||||
return row.status === 'UNPAID' && !isZeroPayable(row.wineryAmount);
|
||||
}
|
||||
|
||||
const DELIVERY_LABELS: Record<string, string> = {
|
||||
LOCAL: '同城',
|
||||
CROSS_CITY: '跨城',
|
||||
@@ -212,7 +234,7 @@ export default function WineryBillsPage() {
|
||||
render: (v) => `${Math.round(Number(v) * 100)}%`,
|
||||
},
|
||||
{
|
||||
title: '酒厂应付',
|
||||
title: '应付',
|
||||
dataIndex: 'wineryAmount',
|
||||
width: 110,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
@@ -220,8 +242,11 @@ export default function WineryBillsPage() {
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s) => <Tag color={STATUS_COLORS[s] || 'default'}>{STATUS_LABELS[s] || s}</Tag>,
|
||||
width: 100,
|
||||
render: (s, row) => {
|
||||
const d = displayWineryStatus(s, row.wineryAmount);
|
||||
return <Tag color={d.color}>{d.label}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
@@ -232,7 +257,7 @@ export default function WineryBillsPage() {
|
||||
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
||||
明细
|
||||
</Button>
|
||||
{row.status === 'UNPAID' && (
|
||||
{canConfirmWineryPay(row) && (
|
||||
<Button type="link" size="small" onClick={() => confirmPay([row.id], Number(row.wineryAmount))}>
|
||||
确认打款
|
||||
</Button>
|
||||
@@ -258,7 +283,8 @@ export default function WineryBillsPage() {
|
||||
酒厂对账单
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
||||
T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × {ratePct}%);未打款红色、已打款绿色、应付为 0
|
||||
无需打款(灰),可展开订单明细
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{canEditWineryBank ? (
|
||||
@@ -273,7 +299,7 @@ export default function WineryBillsPage() {
|
||||
<Space size="large" wrap>
|
||||
<Statistic title="账单数" value={summary.count} />
|
||||
<Statistic title="酒单实付合计" value={summary.orderAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="酒厂应付合计" value={summary.wineryAmount ?? 0} prefix="¥" precision={2} />
|
||||
<Statistic title="应付合计" value={summary.wineryAmount ?? 0} prefix="¥" precision={2} />
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
@@ -296,7 +322,7 @@ export default function WineryBillsPage() {
|
||||
<Form.Item name="status" label="状态">
|
||||
<Select
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
style={{ width: 130 }}
|
||||
options={Object.entries(STATUS_LABELS).map(([value, label]) => ({ value, label }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -347,7 +373,7 @@ export default function WineryBillsPage() {
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedKeys,
|
||||
onChange: setSelectedKeys,
|
||||
getCheckboxProps: (r) => ({ disabled: r.status !== 'UNPAID' }),
|
||||
getCheckboxProps: (r) => ({ disabled: !canConfirmWineryPay(r) }),
|
||||
}}
|
||||
scroll={{ x: 1100 }}
|
||||
pagination={{
|
||||
@@ -368,8 +394,10 @@ export default function WineryBillsPage() {
|
||||
<Descriptions column={1} size="small" bordered>
|
||||
<Descriptions.Item label="账单号">{detail.billNo}</Descriptions.Item>
|
||||
<Descriptions.Item label="账单日">{String(detail.billDate).slice(0, 10)}</Descriptions.Item>
|
||||
<Descriptions.Item label="酒厂应付">¥{Number(detail.wineryAmount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">{STATUS_LABELS[detail.status] || detail.status}</Descriptions.Item>
|
||||
<Descriptions.Item label="应付">¥{Number(detail.wineryAmount).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
{displayWineryStatus(detail.status, detail.wineryAmount).label}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="打款时间">{detail.paidAt ? fmtTime(detail.paidAt) : '—'}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Typography.Title level={5} style={{ marginTop: 16 }}>
|
||||
@@ -395,7 +423,7 @@ export default function WineryBillsPage() {
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '酒厂应付',
|
||||
title: '应付',
|
||||
dataIndex: 'wineryAmount',
|
||||
width: 90,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.mp3' {
|
||||
const src: string;
|
||||
export default src;
|
||||
}
|
||||
@@ -11,7 +11,10 @@
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@dukang/domain": ["../../packages/domain/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import path from 'path';
|
||||
|
||||
const apiTarget = process.env.VITE_API_TARGET ?? 'http://localhost:3010';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@dukang/domain': path.resolve(__dirname, '../../packages/domain/src/index.ts'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
port: 5175,
|
||||
proxy: { '/api': apiTarget },
|
||||
},
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@dukang/client-logging": "workspace:*",
|
||||
"@dukang/domain": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/weixin-sdk": "workspace:*",
|
||||
|
||||
@@ -13,12 +13,20 @@ type Props = {
|
||||
maxCount?: number;
|
||||
disabled?: boolean;
|
||||
label?: string;
|
||||
/** 系统文件选择器的 accept,默认仅图片 */
|
||||
accept?: string;
|
||||
/** 计量单位文案,如「张」「个」 */
|
||||
unit?: string;
|
||||
};
|
||||
|
||||
function isCancelError(msg: string): boolean {
|
||||
return /cancel|取消/i.test(msg);
|
||||
}
|
||||
|
||||
function isPdf(url: string): boolean {
|
||||
return /\.pdf(\?|$)/i.test(url);
|
||||
}
|
||||
|
||||
function normalizeUrls(value?: string[]) {
|
||||
return (value ?? []).map((u) => String(u || '').trim()).filter(Boolean);
|
||||
}
|
||||
@@ -32,6 +40,8 @@ export default function MultiOssUploadField({
|
||||
maxCount = 20,
|
||||
disabled,
|
||||
label,
|
||||
accept = 'image/*',
|
||||
unit = '张',
|
||||
}: Props) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const pickingRef = useRef(false);
|
||||
@@ -39,9 +49,19 @@ export default function MultiOssUploadField({
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const urls = normalizeUrls(value);
|
||||
const urlsRef = useRef(urls);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const remaining = Math.max(0, maxCount - urls.length);
|
||||
const inWechat = isWechatEnv();
|
||||
|
||||
useEffect(() => {
|
||||
urlsRef.current = urls;
|
||||
}, [urls]);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!inWechat) return;
|
||||
void weixinSdk.init().catch(() => {});
|
||||
@@ -53,9 +73,11 @@ export default function MultiOssUploadField({
|
||||
}
|
||||
|
||||
async function uploadFiles(files: File[]) {
|
||||
const picked = files.slice(0, remaining);
|
||||
const current = urlsRef.current;
|
||||
const room = Math.max(0, maxCount - current.length);
|
||||
const picked = files.slice(0, room);
|
||||
if (!picked.length) {
|
||||
showUploadError(`最多 ${maxCount} 张`);
|
||||
showUploadError(`最多 ${maxCount} ${unit}`);
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
@@ -68,8 +90,10 @@ export default function MultiOssUploadField({
|
||||
appended.push(result.url);
|
||||
}
|
||||
if (appended.length) {
|
||||
onChange?.([...urls, ...appended]);
|
||||
toastSuccess(`已上传 ${appended.length} 张`);
|
||||
const next = [...urlsRef.current, ...appended];
|
||||
urlsRef.current = next;
|
||||
onChangeRef.current?.(next);
|
||||
toastSuccess(`已上传 ${appended.length} ${unit}`);
|
||||
}
|
||||
} catch (e) {
|
||||
showUploadError(e instanceof Error ? e.message : '上传失败');
|
||||
@@ -112,7 +136,7 @@ export default function MultiOssUploadField({
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept={accept}
|
||||
multiple
|
||||
className="partner-oss-upload-input"
|
||||
disabled={disabled || uploading || remaining <= 0}
|
||||
@@ -126,11 +150,37 @@ export default function MultiOssUploadField({
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
|
||||
{urls.map((url, index) => (
|
||||
<div key={`${url}-${index}`} style={{ position: 'relative', width: 88, height: 88 }}>
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
style={{ width: 88, height: 88, objectFit: 'cover', borderRadius: 8 }}
|
||||
/>
|
||||
{isPdf(url) ? (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
style={{
|
||||
display: 'flex',
|
||||
width: 88,
|
||||
height: 88,
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 2,
|
||||
borderRadius: 8,
|
||||
border: '1px solid rgba(0,0,0,0.08)',
|
||||
background: '#f7f7f7',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<span className="material-symbols-outlined text-primary" style={{ fontSize: 26 }}>
|
||||
description
|
||||
</span>
|
||||
<span className="text-muted">PDF</span>
|
||||
</a>
|
||||
) : (
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
style={{ width: 88, height: 88, objectFit: 'cover', borderRadius: 8 }}
|
||||
/>
|
||||
)}
|
||||
{!disabled ? (
|
||||
<button
|
||||
type="button"
|
||||
@@ -172,7 +222,7 @@ export default function MultiOssUploadField({
|
||||
{uploading
|
||||
? '上传中…'
|
||||
: remaining <= 0
|
||||
? `已达上限 ${maxCount}`
|
||||
? `已达上限 ${maxCount}${unit}`
|
||||
: label ?? `批量上传(${urls.length}/${maxCount})`}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -119,15 +119,13 @@ export default function StorePackagesForm({ items, onChange, disabled, embedded
|
||||
|
||||
<div className="partner-field">
|
||||
<label>使用时间</label>
|
||||
<div className="partner-field-input">
|
||||
<span className="material-symbols-outlined">schedule</span>
|
||||
<input
|
||||
placeholder="节假日除外"
|
||||
value={item.usableTime || ''}
|
||||
disabled={disabled}
|
||||
onChange={(e) => updateAt(index, { usableTime: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="节假日除外"
|
||||
value={item.usableTime || ''}
|
||||
disabled={disabled}
|
||||
onChange={(e) => updateAt(index, { usableTime: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="partner-field">
|
||||
@@ -154,15 +152,13 @@ export default function StorePackagesForm({ items, onChange, disabled, embedded
|
||||
|
||||
<div className="partner-field">
|
||||
<label>其他说明</label>
|
||||
<div className="partner-field-input">
|
||||
<span className="material-symbols-outlined">info</span>
|
||||
<input
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
disabled={disabled}
|
||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
disabled={disabled}
|
||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from '../lib/api';
|
||||
import { fetchClientConfig, processPartnerWechatOAuthCallback } from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { toastError } from '../lib/toast';
|
||||
|
||||
export type PartnerAccount = PartnerMe & {
|
||||
staffRole?: PartnerStaffRole;
|
||||
@@ -115,7 +116,10 @@ export function PartnerSessionProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
} catch {
|
||||
} catch (e) {
|
||||
// 微信 OAuth 回跳后后端可能因账号暂停(DISABLED)等拒绝登录,
|
||||
// 必须把错误显式提示出来,否则用户无任何反馈(与短信路径一致)。
|
||||
toastError(e instanceof Error ? e.message : '微信登录失败');
|
||||
stripOAuthParamsFromLocation();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,10 +156,19 @@ async function rawRequest<T>(
|
||||
if (authToken) headers.Authorization = `Bearer ${authToken}`;
|
||||
|
||||
const res = await fetch(`${apiBase}${path}`, { ...options, headers });
|
||||
const json = await res.json().catch(() => ({ code: res.status, message: '网络异常' }));
|
||||
const json = await res.json().catch(() => ({ code: res.status, message: '网络异常' })) as {
|
||||
code: number;
|
||||
message?: string;
|
||||
data?: T;
|
||||
reason?: string;
|
||||
};
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
const err = new Error(json.message || '请求失败') as Error & {
|
||||
status?: number;
|
||||
reason?: string;
|
||||
};
|
||||
err.status = json.code === 401 ? 401 : json.code;
|
||||
err.reason = json.reason;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
@@ -224,8 +233,19 @@ export async function request<T>(
|
||||
try {
|
||||
return await requestWithAuthRetry<T>(path, fetchOptions);
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const err = e as Error & { status?: number; reason?: string };
|
||||
const message = err.message || '请求失败';
|
||||
// 账号停用 / 合伙人绑定失效:强制退出登录
|
||||
if (err.reason === 'ACCOUNT_DISABLED') {
|
||||
if (localStorage.getItem(ACCESS_TOKEN)) {
|
||||
clearAuth({ keepProfile: true });
|
||||
if (!silent) showPartnerToast(message, 'error');
|
||||
if (typeof window !== 'undefined' && !isOnAppPath('/login')) {
|
||||
window.location.href = toAppPath('/login?disabled=1');
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (err.status === 401) {
|
||||
if (localStorage.getItem(ACCESS_TOKEN)) {
|
||||
clearAuth({ keepProfile: true });
|
||||
@@ -260,7 +280,14 @@ export async function ensureSession(): Promise<{ authenticated: boolean; partner
|
||||
touchPartnerSession();
|
||||
return { authenticated: true, partner };
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const err = e as Error & { status?: number; reason?: string };
|
||||
if (err.reason === 'ACCOUNT_DISABLED') {
|
||||
clearAuth({ keepProfile: true });
|
||||
if (typeof window !== 'undefined' && !isOnAppPath('/login')) {
|
||||
window.location.href = toAppPath('/login?disabled=1');
|
||||
}
|
||||
return { authenticated: false, partner: getPartnerProfile() };
|
||||
}
|
||||
if (err.status === 401) {
|
||||
const refreshed = await refreshSession();
|
||||
if (refreshed?.partner) {
|
||||
@@ -277,3 +304,17 @@ export async function ensureSession(): Promise<{ authenticated: boolean; partner
|
||||
|
||||
/** @deprecated 使用 PartnerSessionPayload */
|
||||
export type PartnerAuthPayload = PartnerSessionPayload;
|
||||
|
||||
export function submitStoreInfoChangeRequest(storeId: string, fields: Record<string, unknown>) {
|
||||
return request('PARTNER_H5', `/partner/stores/${storeId}/info-change-request`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(fields),
|
||||
});
|
||||
}
|
||||
|
||||
export function listStoreInfoChangeRequests(storeId: string) {
|
||||
return request<Array<{ status?: string }>>(
|
||||
'PARTNER_H5',
|
||||
`/partner/stores/${storeId}/info-change-requests`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { getDefaultPartnerRegionForm } from './china-region';
|
||||
import { isStoreContactPhone, STORE_CONTACT_PHONE_HINT } from '@dukang/domain';
|
||||
|
||||
export type StoreDraftForm = {
|
||||
regionCodes: string[];
|
||||
cityId: string;
|
||||
@@ -5,7 +8,10 @@ export type StoreDraftForm = {
|
||||
city: string;
|
||||
district: string;
|
||||
name: string;
|
||||
/** 门店登录手机号(老板主账号) */
|
||||
phone: string;
|
||||
/** 对外联系电话(店长);可与登录号不同 */
|
||||
contactPhone: string;
|
||||
address: string;
|
||||
/** 门店坐标(定位或地理编码) */
|
||||
latitude: string;
|
||||
@@ -25,7 +31,8 @@ export type StoreDraftForm = {
|
||||
benefitUsageRule: string;
|
||||
coverUrl: string;
|
||||
envPhotoUrls: string[];
|
||||
contractUrl: string;
|
||||
/** 签约合同,支持多张照片 / PDF */
|
||||
contractUrls: string[];
|
||||
bankAccountName: string;
|
||||
bankAccountNo: string;
|
||||
bankBranch: string;
|
||||
@@ -44,13 +51,12 @@ export function storeDraftKey(accountId?: string): string {
|
||||
return accountId ? `${STORE_DRAFT_KEY}_${accountId}` : STORE_DRAFT_KEY;
|
||||
}
|
||||
|
||||
import { getDefaultPartnerRegionForm } from './china-region';
|
||||
|
||||
export const defaultStoreForm = (): StoreDraftForm => ({
|
||||
...getDefaultPartnerRegionForm(),
|
||||
cityId: '',
|
||||
name: '',
|
||||
phone: '',
|
||||
contactPhone: '',
|
||||
address: '',
|
||||
latitude: '',
|
||||
longitude: '',
|
||||
@@ -66,7 +72,7 @@ export const defaultStoreForm = (): StoreDraftForm => ({
|
||||
benefitUsageRule: '',
|
||||
coverUrl: '',
|
||||
envPhotoUrls: ['', '', ''],
|
||||
contractUrl: '',
|
||||
contractUrls: [],
|
||||
bankAccountName: '',
|
||||
bankAccountNo: '',
|
||||
bankBranch: '',
|
||||
@@ -84,6 +90,9 @@ function timeToMinutes(hhmm: string): number {
|
||||
|
||||
export const MIN_ENV_PHOTO_COUNT = 3;
|
||||
|
||||
/** 签约合同最多可上传的照片 / PDF 数量 */
|
||||
export const MAX_CONTRACT_COUNT = 20;
|
||||
|
||||
export function normalizeStringArray(urls: unknown, minLen: number): string[] {
|
||||
const arr = Array.isArray(urls) ? urls.map((u) => String(u ?? '')) : [];
|
||||
while (arr.length < minLen) arr.push('');
|
||||
@@ -102,6 +111,9 @@ export function normalizeStoreDraftForm(raw: Partial<StoreDraftForm> | null | un
|
||||
...raw,
|
||||
regionCodes: Array.isArray(raw.regionCodes) ? raw.regionCodes.map(String) : base.regionCodes,
|
||||
cityId: String(raw.cityId ?? base.cityId),
|
||||
phone: String(raw.phone ?? base.phone),
|
||||
contactPhone:
|
||||
String(raw.contactPhone ?? '').trim() || String(raw.phone ?? '').trim() || base.contactPhone,
|
||||
latitude: raw.latitude != null && raw.latitude !== '' ? String(raw.latitude) : base.latitude,
|
||||
longitude: raw.longitude != null && raw.longitude !== '' ? String(raw.longitude) : base.longitude,
|
||||
openTime: String(raw.openTime ?? base.openTime),
|
||||
@@ -111,6 +123,22 @@ export function normalizeStoreDraftForm(raw: Partial<StoreDraftForm> | null | un
|
||||
closeTime2: String(raw.closeTime2 ?? base.closeTime2),
|
||||
avgPrice: String(raw.avgPrice ?? base.avgPrice),
|
||||
envPhotoUrls: normalizeStringArray(raw.envPhotoUrls, MIN_ENV_PHOTO_COUNT),
|
||||
// 兼容旧草稿:单个 contractUrl 迁移为数组
|
||||
contractUrls: (() => {
|
||||
const list = Array.isArray(raw.contractUrls)
|
||||
? raw.contractUrls
|
||||
: [(raw as { contractUrl?: unknown }).contractUrl];
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const item of list) {
|
||||
const url = String(item ?? '').trim();
|
||||
if (!url || seen.has(url)) continue;
|
||||
seen.add(url);
|
||||
out.push(url);
|
||||
if (out.length >= MAX_CONTRACT_COUNT) break;
|
||||
}
|
||||
return out;
|
||||
})(),
|
||||
packages: Array.isArray(raw.packages)
|
||||
? raw.packages.map((p, i) => ({
|
||||
name: String((p as { name?: string }).name ?? ''),
|
||||
@@ -217,12 +245,13 @@ export function validateStoreStep1(
|
||||
}
|
||||
|
||||
export function validateStoreStep2(
|
||||
form: Pick<StoreDraftForm, 'coverUrl' | 'envPhotoUrls' | 'contractUrl'>,
|
||||
form: Pick<StoreDraftForm, 'coverUrl' | 'envPhotoUrls' | 'contractUrls'>,
|
||||
): string | null {
|
||||
if (!form.coverUrl.trim()) return '请上传门头照';
|
||||
const envCount = form.envPhotoUrls.filter((u) => u.trim()).length;
|
||||
if (envCount < MIN_ENV_PHOTO_COUNT) return `请上传至少 ${MIN_ENV_PHOTO_COUNT} 张环境照片`;
|
||||
if (!form.contractUrl.trim()) return '请上传签约合同';
|
||||
const contractCount = (form.contractUrls ?? []).filter((u) => u.trim()).length;
|
||||
if (contractCount < 1) return '请上传签约合同';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -236,14 +265,16 @@ export function patchEnvPhotoAt(urls: string[], index: number, url: string): str
|
||||
export function validateStoreStep3(
|
||||
form: Pick<
|
||||
StoreDraftForm,
|
||||
'bankAccountName' | 'bankAccountNo' | 'bankBranch' | 'phone'
|
||||
'bankAccountName' | 'bankAccountNo' | 'bankBranch' | 'phone' | 'contactPhone'
|
||||
>,
|
||||
): string | null {
|
||||
if (!form.bankAccountName.trim()) return '请填写户主姓名';
|
||||
if (!form.bankAccountNo.trim()) return '请填写银行卡号';
|
||||
if (!BANK_RE.test(form.bankAccountNo.replace(/\s/g, ''))) return '银行卡号须为 16~19 位数字';
|
||||
if (!form.bankBranch.trim()) return '请填写开户支行';
|
||||
if (!form.phone.trim()) return '请填写联系电话';
|
||||
if (!PHONE_RE.test(form.phone.trim())) return '联系电话须为11位手机号';
|
||||
if (!form.phone.trim()) return '请填写门店登录手机号';
|
||||
if (!PHONE_RE.test(form.phone.trim())) return '门店登录手机号须为11位手机号';
|
||||
if (!form.contactPhone.trim()) return '请填写联系电话';
|
||||
if (!isStoreContactPhone(form.contactPhone.trim())) return STORE_CONTACT_PHONE_HINT;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ export type PartnerStoreAuditStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | stri
|
||||
|
||||
export function storeAuditLabel(auditStatus?: string | null): string {
|
||||
const s = String(auditStatus || 'APPROVED').toUpperCase();
|
||||
if (s === 'PENDING') return '待总部审核';
|
||||
if (s === 'PENDING') return '待审核';
|
||||
if (s === 'REJECTED') return '审核驳回';
|
||||
if (s === 'APPROVED') return '审核通过';
|
||||
return auditStatus || '—';
|
||||
@@ -21,10 +21,26 @@ export function storeStatusLabel(status: string): string {
|
||||
const s = String(status).toUpperCase();
|
||||
if (s === 'OPEN') return '营业中';
|
||||
if (s === 'PAUSED') return '临时闭店';
|
||||
if (s === 'CLOSED') return '永久关闭';
|
||||
if (s === 'CLOSED') return '永久闭店';
|
||||
return status;
|
||||
}
|
||||
|
||||
/** 列表右上角统一状态:审核未通过优先于营业状态 */
|
||||
export function storeListBadge(store: {
|
||||
status?: unknown;
|
||||
auditStatus?: unknown;
|
||||
}): { label: string; pillClass: string } {
|
||||
const audit = String(store.auditStatus || 'APPROVED').toUpperCase();
|
||||
if (audit === 'PENDING') {
|
||||
return { label: '待审核', pillClass: storeAuditPillClass('PENDING') };
|
||||
}
|
||||
if (audit === 'REJECTED') {
|
||||
return { label: '审核驳回', pillClass: storeAuditPillClass('REJECTED') };
|
||||
}
|
||||
const status = String(store.status || '').toUpperCase();
|
||||
return { label: storeStatusLabel(status), pillClass: storeStatusPillClass(status) };
|
||||
}
|
||||
|
||||
export function storeStatusPillClass(status: string): string {
|
||||
const s = String(status).toUpperCase();
|
||||
if (s === 'OPEN') return 'partner-status-pill--open';
|
||||
|
||||
@@ -71,16 +71,24 @@ function formatPartnerError(e: unknown): string {
|
||||
if (text.includes('合伙人账号不存在') || text.includes('未找到合伙人账号')) {
|
||||
return '未找到合伙人账号';
|
||||
}
|
||||
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||
return '合伙人账号已暂停,无法登录';
|
||||
if (
|
||||
text.includes('合伙人账号已停用') ||
|
||||
text.includes('账号已停用') ||
|
||||
text.includes('暂停使用')
|
||||
) {
|
||||
return '该账号已暂停使用,请联系客服人员';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function formatWechatError(e: unknown): string {
|
||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||
return '合伙人账号已暂停,无法登录';
|
||||
if (
|
||||
text.includes('合伙人账号已停用') ||
|
||||
text.includes('账号已停用') ||
|
||||
text.includes('暂停使用')
|
||||
) {
|
||||
return '该账号已暂停使用,请联系客服人员';
|
||||
}
|
||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||
@@ -91,7 +99,7 @@ function formatWechatError(e: unknown): string {
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { applySession, refresh, account } = usePartnerSession();
|
||||
const [params] = useSearchParams();
|
||||
const [params, setSearchParams] = useSearchParams();
|
||||
const quick = params.get('quick') === '1';
|
||||
const savedProfile = getPartnerProfile();
|
||||
const remembered = loadRememberedPhone();
|
||||
@@ -112,6 +120,18 @@ export default function LoginPage() {
|
||||
.catch(() => setWxAuthorize(false));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (params.get('disabled') === '1') {
|
||||
const tip = '账号已停用或解绑,请重新登录';
|
||||
setMsg(tip);
|
||||
toastError(tip);
|
||||
const next = new URLSearchParams(params);
|
||||
next.delete('disabled');
|
||||
setSearchParams(next, { replace: true });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const quickName = savedProfile?.name ?? '城市合伙人';
|
||||
const quickCompany = savedProfile?.companyName ?? '';
|
||||
const quickPhone = savedProfile?.phone || phone;
|
||||
|
||||
@@ -8,6 +8,7 @@ import OssUploadField from '../components/OssUploadField';
|
||||
import MultiOssUploadField from '../components/MultiOssUploadField';
|
||||
|
||||
import { request } from '../lib/api';
|
||||
import { fetchClientConfig } from '../lib/wechat-auth';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
|
||||
import { resolveRegionBinding } from '../lib/china-region';
|
||||
@@ -42,12 +43,17 @@ import {
|
||||
validateStoreStep3,
|
||||
|
||||
MIN_ENV_PHOTO_COUNT,
|
||||
|
||||
MAX_CONTRACT_COUNT,
|
||||
} from '../lib/storeDraft';
|
||||
import StorePackagesForm from '../components/StorePackagesForm';
|
||||
import { normalizePackageFormItems, validatePackageFormItems } from '../lib/storePackages';
|
||||
|
||||
const STEPS = ['基本信息', '照片上传', '结算资质', '门店套餐'] as const;
|
||||
|
||||
const DEFAULT_PARTNER_ONBOARD_CS_HINT =
|
||||
'使用问题、提现问题等随时可联系【杜康好客】客服';
|
||||
|
||||
type StoreCategoryNode = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -56,6 +62,7 @@ type StoreCategoryNode = {
|
||||
|
||||
type FieldErrors = {
|
||||
phone?: string;
|
||||
contactPhone?: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -97,6 +104,10 @@ export default function StoreCreatePage() {
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [csAdded, setCsAdded] = useState(false);
|
||||
const [csQrUrl, setCsQrUrl] = useState<string | null>(null);
|
||||
const [csHint, setCsHint] = useState(DEFAULT_PARTNER_ONBOARD_CS_HINT);
|
||||
const [csConfigLoading, setCsConfigLoading] = useState(false);
|
||||
|
||||
const [cities, setCities] = useState<OpenCityOption[]>([]);
|
||||
|
||||
@@ -148,6 +159,29 @@ export default function StoreCreatePage() {
|
||||
});
|
||||
}, [step]);
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== 4) return;
|
||||
let cancelled = false;
|
||||
setCsConfigLoading(true);
|
||||
void fetchClientConfig()
|
||||
.then((cfg) => {
|
||||
if (cancelled) return;
|
||||
setCsQrUrl((cfg.partnerOnboardCsQrUrl ?? '').trim() || null);
|
||||
setCsHint((cfg.partnerOnboardCsHint ?? '').trim() || DEFAULT_PARTNER_ONBOARD_CS_HINT);
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) return;
|
||||
setCsQrUrl(null);
|
||||
setCsHint(DEFAULT_PARTNER_ONBOARD_CS_HINT);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setCsConfigLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [step]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
void fetchPartnerCities()
|
||||
@@ -237,9 +271,17 @@ export default function StoreCreatePage() {
|
||||
|
||||
setSubmitError('');
|
||||
|
||||
if ('phone' in patch) {
|
||||
if ('phone' in patch || 'contactPhone' in patch) {
|
||||
|
||||
setFieldErrors((prev) => ({ ...prev, phone: undefined }));
|
||||
setFieldErrors((prev) => ({
|
||||
|
||||
...prev,
|
||||
|
||||
...('phone' in patch ? { phone: undefined } : {}),
|
||||
|
||||
...('contactPhone' in patch ? { contactPhone: undefined } : {}),
|
||||
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
@@ -315,7 +357,9 @@ export default function StoreCreatePage() {
|
||||
const msg = validateStoreStep3(form);
|
||||
if (msg) {
|
||||
if (isPhoneValidationMessage(msg)) {
|
||||
setFieldErrors({ phone: msg });
|
||||
setFieldErrors(
|
||||
msg.includes('联系电话') ? { contactPhone: msg } : { phone: msg },
|
||||
);
|
||||
reportStepError(msg);
|
||||
return;
|
||||
}
|
||||
@@ -331,12 +375,23 @@ export default function StoreCreatePage() {
|
||||
|
||||
|
||||
async function submit(skipPackages = false) {
|
||||
const qr = (csQrUrl ?? '').trim();
|
||||
if (!qr) {
|
||||
reportFormError('客服二维码暂未配置,请联系总部');
|
||||
return;
|
||||
}
|
||||
if (!csAdded) {
|
||||
reportFormError('请先勾选「我已添加【杜康好客】客服」');
|
||||
return;
|
||||
}
|
||||
|
||||
const msg = validateStoreStep3(form);
|
||||
|
||||
if (msg) {
|
||||
if (isPhoneValidationMessage(msg)) {
|
||||
setFieldErrors({ phone: msg });
|
||||
setFieldErrors(
|
||||
msg.includes('联系电话') ? { contactPhone: msg } : { phone: msg },
|
||||
);
|
||||
return;
|
||||
}
|
||||
reportFormError(msg);
|
||||
@@ -423,7 +478,11 @@ export default function StoreCreatePage() {
|
||||
|
||||
const envPhotoUrls = Array.from(
|
||||
new Set(form.envPhotoUrls.map((u) => u.trim()).filter(Boolean)),
|
||||
).slice(0, 3);
|
||||
).slice(0, 20);
|
||||
|
||||
const contractUrls = Array.from(
|
||||
new Set((form.contractUrls ?? []).map((u) => u.trim()).filter(Boolean)),
|
||||
).slice(0, MAX_CONTRACT_COUNT);
|
||||
|
||||
const result = await request<{ store: { id: string } }>('PARTNER_H5', '/partner/stores', {
|
||||
|
||||
@@ -441,6 +500,8 @@ export default function StoreCreatePage() {
|
||||
|
||||
phone: form.phone.trim(),
|
||||
|
||||
contactPhone: form.contactPhone.trim() || form.phone.trim(),
|
||||
|
||||
district: form.district.trim(),
|
||||
|
||||
address: form.address.trim(),
|
||||
@@ -471,7 +532,7 @@ export default function StoreCreatePage() {
|
||||
|
||||
envPhotoUrls: envPhotoUrls.length ? envPhotoUrls : undefined,
|
||||
|
||||
contractUrl: form.contractUrl.trim() || undefined,
|
||||
contractUrls: contractUrls.length ? contractUrls : undefined,
|
||||
|
||||
bankAccountName: form.bankAccountName.trim(),
|
||||
|
||||
@@ -522,6 +583,7 @@ export default function StoreCreatePage() {
|
||||
|
||||
const progress = step === 1 ? 0 : step === 2 ? 33 : step === 3 ? 66 : 100;
|
||||
|
||||
const canSubmitOnboard = !!csQrUrl?.trim() && csAdded && !submitting && !csConfigLoading;
|
||||
const nextDisabled = submitting;
|
||||
|
||||
|
||||
@@ -957,9 +1019,11 @@ 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' }}>
|
||||
拍照上传签约协议首页与盖章页,支持多张,最多 {MAX_CONTRACT_COUNT} 个
|
||||
</p>
|
||||
|
||||
<OssUploadField
|
||||
<MultiOssUploadField
|
||||
|
||||
bizType="STORE_CONTRACT"
|
||||
|
||||
@@ -967,11 +1031,15 @@ export default function StoreCreatePage() {
|
||||
|
||||
accept="image/*,.pdf"
|
||||
|
||||
value={form.contractUrl}
|
||||
unit="个"
|
||||
|
||||
onChange={(contractUrl) => patchForm({ contractUrl })}
|
||||
maxCount={MAX_CONTRACT_COUNT}
|
||||
|
||||
label="上传合同副本"
|
||||
value={form.contractUrls ?? []}
|
||||
|
||||
onChange={(urls) => patchForm({ contractUrls: urls })}
|
||||
|
||||
label={`批量上传合同(${(form.contractUrls ?? []).length}/${MAX_CONTRACT_COUNT})`}
|
||||
|
||||
/>
|
||||
|
||||
@@ -1089,7 +1157,43 @@ export default function StoreCreatePage() {
|
||||
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
|
||||
该手机号将作为门店端登录账号。
|
||||
老板手机号,作为门店端主账号登录凭证。
|
||||
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="partner-field">
|
||||
|
||||
<label>联系电话 <span className="text-primary">*</span></label>
|
||||
|
||||
<div className="partner-field-input">
|
||||
|
||||
<span className="material-symbols-outlined">phone_in_talk</span>
|
||||
|
||||
<input
|
||||
|
||||
type="tel"
|
||||
|
||||
placeholder="手机号或座机,如 0379-8888888"
|
||||
|
||||
value={form.contactPhone}
|
||||
|
||||
onChange={(e) => patchForm({ contactPhone: e.target.value })}
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{fieldErrors.contactPhone && (
|
||||
|
||||
<p className="partner-field-error" role="alert">{fieldErrors.contactPhone}</p>
|
||||
|
||||
)}
|
||||
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
|
||||
用户端门店详情展示与拨号使用此号码,可与登录号不同,支持座机(如 0379-8888888)。
|
||||
|
||||
</p>
|
||||
|
||||
@@ -1102,6 +1206,37 @@ export default function StoreCreatePage() {
|
||||
|
||||
{step === 4 && (
|
||||
<>
|
||||
<section className="partner-form-card partner-onboard-cs-card">
|
||||
<div className="partner-section-title">
|
||||
<div className="partner-section-bar" />
|
||||
<h2 className="headline-md">添加客服</h2>
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginBottom: 16, lineHeight: 1.5 }}>
|
||||
{csHint}
|
||||
</p>
|
||||
{csConfigLoading ? (
|
||||
<p className="body-md text-muted">加载客服二维码…</p>
|
||||
) : csQrUrl ? (
|
||||
<img
|
||||
className="partner-onboard-cs-qr"
|
||||
src={csQrUrl}
|
||||
alt="杜康好客企微客服二维码"
|
||||
/>
|
||||
) : (
|
||||
<p className="partner-form-error" role="alert">
|
||||
客服二维码暂未配置,请联系总部
|
||||
</p>
|
||||
)}
|
||||
<label className="partner-onboard-cs-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={csAdded}
|
||||
disabled={!csQrUrl || submitting}
|
||||
onChange={(e) => setCsAdded(e.target.checked)}
|
||||
/>
|
||||
<span>我已添加【杜康好客】客服</span>
|
||||
</label>
|
||||
</section>
|
||||
<section className="partner-form-card">
|
||||
<div className="partner-section-title">
|
||||
<div className="partner-section-bar" />
|
||||
@@ -1147,13 +1282,21 @@ export default function StoreCreatePage() {
|
||||
) : (
|
||||
|
||||
<>
|
||||
<button type="button" className="partner-btn-outline" onClick={() => void submit(true)} disabled={submitting}>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-outline"
|
||||
onClick={() => void submit(true)}
|
||||
disabled={!canSubmitOnboard}
|
||||
>
|
||||
跳过
|
||||
</button>
|
||||
<button type="button" className="partner-btn-primary" onClick={() => void submit(false)} disabled={submitting}>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="partner-btn-primary"
|
||||
onClick={() => void submit(false)}
|
||||
disabled={!canSubmitOnboard}
|
||||
>
|
||||
{submitting ? '提交中…' : '提交'}
|
||||
|
||||
</button>
|
||||
</>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import AppImage from '@dukang/shared-ui/AppImage';
|
||||
import { request } from '../lib/api';
|
||||
import { request, submitStoreInfoChangeRequest, listStoreInfoChangeRequests } from '../lib/api';
|
||||
import { toastError, toastSuccess } from '../lib/toast';
|
||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||
import { canManagePartnerStore } from '../lib/partnerAccess';
|
||||
@@ -43,7 +43,8 @@ export default function StoreDetailPage() {
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [form, setForm] = useState({
|
||||
name: '',
|
||||
phone: '',
|
||||
loginPhone: '',
|
||||
contactPhone: '',
|
||||
address: '',
|
||||
intro: '',
|
||||
benefitUsageRule: '',
|
||||
@@ -59,12 +60,14 @@ export default function StoreDetailPage() {
|
||||
const [mapPickerOpen, setMapPickerOpen] = useState(false);
|
||||
const [actionError, setActionError] = useState('');
|
||||
const [closeConfirmOpen, setCloseConfirmOpen] = useState(false);
|
||||
const [pendingInfoChange, setPendingInfoChange] = useState(false);
|
||||
|
||||
function applyStore(data: Record<string, unknown>) {
|
||||
setStore(data);
|
||||
setForm({
|
||||
name: String(data.name || ''),
|
||||
phone: String(data.phone || ''),
|
||||
loginPhone: String(data.phone || ''),
|
||||
contactPhone: String(data.contactPhone || data.phone || ''),
|
||||
address: String(data.address || ''),
|
||||
intro: String(data.intro || ''),
|
||||
benefitUsageRule: (() => {
|
||||
@@ -95,6 +98,12 @@ export default function StoreDetailPage() {
|
||||
setStore(null);
|
||||
setLoadError(e instanceof Error ? e.message : '加载失败');
|
||||
});
|
||||
// 拉取该门店的信息变更审核记录,若有 PENDING 则展示「审核中」横幅
|
||||
listStoreInfoChangeRequests(id)
|
||||
.then((reqs) =>
|
||||
setPendingInfoChange(Array.isArray(reqs) && reqs.some((r) => r.status === 'PENDING')),
|
||||
)
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
async function changeStatus(next: StoreStatusValue) {
|
||||
@@ -160,26 +169,24 @@ export default function StoreDetailPage() {
|
||||
setSaving(true);
|
||||
setActionError('');
|
||||
try {
|
||||
const data = await request<Record<string, unknown>>('PARTNER_H5', `/partner/stores/${id}/basic`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
name: form.name.trim(),
|
||||
phone: form.phone.trim(),
|
||||
address: form.address.trim(),
|
||||
intro: form.intro.trim(),
|
||||
benefitUsageRule: form.benefitUsageRule.trim() || null,
|
||||
...(form.latitude.trim() && form.longitude.trim()
|
||||
? {
|
||||
latitude: Number(form.latitude),
|
||||
longitude: Number(form.longitude),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
// v3.5.1 #5:基本信息变更走「提交变更」审核流,由总部审核通过后覆盖门店
|
||||
await submitStoreInfoChangeRequest(id, {
|
||||
name: form.name.trim(),
|
||||
contactPhone: form.contactPhone.trim(),
|
||||
address: form.address.trim(),
|
||||
intro: form.intro.trim(),
|
||||
benefitUsageRule: form.benefitUsageRule.trim() || null,
|
||||
...(form.latitude.trim() && form.longitude.trim()
|
||||
? {
|
||||
latitude: Number(form.latitude),
|
||||
longitude: Number(form.longitude),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
applyStore(data);
|
||||
toastSuccess(auditStatus === 'REJECTED' ? '已保存并重新提交审核' : '已保存');
|
||||
setPendingInfoChange(true);
|
||||
toastSuccess('变更已提交,等待总部审核');
|
||||
} catch (e) {
|
||||
setActionError(e instanceof Error ? e.message : '保存失败');
|
||||
setActionError(e instanceof Error ? e.message : '提交失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -277,13 +284,23 @@ export default function StoreDetailPage() {
|
||||
{auditStatus === 'APPROVED' && (
|
||||
<p className="label-md text-muted">总部审核已通过,可将门店设为营业中。</p>
|
||||
)}
|
||||
{pendingInfoChange && (
|
||||
<div style={{ marginTop: 12, background: 'rgba(245,166,35,0.08)', border: '1px solid rgba(245,166,35,0.3)', borderRadius: 8, padding: 12 }}>
|
||||
<p className="body-md" style={{ fontWeight: 600, marginBottom: 4 }}>
|
||||
基础信息变更审核中
|
||||
</p>
|
||||
<p className="label-md text-muted" style={{ margin: 0 }}>
|
||||
已提交的资料变更正在等待总部审核,审核通过后才会覆盖门店线上信息。审核期间可继续修改并重新提交。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{canMutate && !auditPending && status !== 'CLOSED' && (
|
||||
<section className="partner-form-card" style={{ margin: '0 0 16px' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<h3 className="label-md text-muted" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>门店套餐</h3>
|
||||
<button type="button" className="partner-btn-outline" onClick={() => navigate(`/stores/${id}/packages`)}>
|
||||
<button type="button" className="partner-btn-outline partner-btn-outline--compact" onClick={() => navigate(`/stores/${id}/packages`)}>
|
||||
编辑套餐
|
||||
</button>
|
||||
</div>
|
||||
@@ -346,12 +363,31 @@ export default function StoreDetailPage() {
|
||||
<label>门店名称</label>
|
||||
<input disabled={readOnly} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} style={{ width: '100%', padding: '12px 16px', border: '1px solid rgba(226,190,188,0.5)', borderRadius: 8, fontSize: 16, fontWeight: 500 }} />
|
||||
</div>
|
||||
<div className="partner-field">
|
||||
<label>门店登录手机号</label>
|
||||
<div className="partner-field-input">
|
||||
<span className="material-symbols-outlined">lock</span>
|
||||
<input disabled type="tel" value={form.loginPhone} readOnly />
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
老板主账号,用于门店端登录;如需变更请联系总部。
|
||||
</p>
|
||||
</div>
|
||||
<div className="partner-field">
|
||||
<label>联系电话</label>
|
||||
<div className="partner-field-input">
|
||||
<span className="material-symbols-outlined">call</span>
|
||||
<input disabled={readOnly} type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
|
||||
<span className="material-symbols-outlined">phone_in_talk</span>
|
||||
<input
|
||||
disabled={readOnly}
|
||||
type="tel"
|
||||
placeholder="手机号或座机,如 0379-8888888"
|
||||
value={form.contactPhone}
|
||||
onChange={(e) => setForm({ ...form, contactPhone: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<p className="label-md text-muted" style={{ marginTop: 8 }}>
|
||||
店长或对外展示号码,用户端拨号使用此号码,支持座机。
|
||||
</p>
|
||||
</div>
|
||||
<div className="partner-field">
|
||||
<label>门店地址</label>
|
||||
@@ -460,8 +496,8 @@ export default function StoreDetailPage() {
|
||||
<button type="button" className="partner-save-cancel" onClick={() => navigate('/stores')}>返回</button>
|
||||
{canMutate && (
|
||||
<button type="button" className="partner-save-submit" onClick={() => void saveBasic()} disabled={readOnly || saving}>
|
||||
<span className="material-symbols-outlined">save</span>
|
||||
{saving ? '保存中…' : auditRejected ? '保存并重新提交' : '保存修改'}
|
||||
<span className="material-symbols-outlined">send</span>
|
||||
{saving ? '提交中…' : '提交变更'}
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
|
||||
@@ -8,9 +8,7 @@ import { canCreatePartnerStore, canManagePartnerStore } from '../lib/partnerAcce
|
||||
import {
|
||||
canPartnerOpenStore,
|
||||
storeAuditLabel,
|
||||
storeAuditPillClass,
|
||||
storeStatusLabel,
|
||||
storeStatusPillClass,
|
||||
storeListBadge,
|
||||
type StoreStatusValue,
|
||||
} from '../lib/storeStatus';
|
||||
import { usePartnerPageView } from '../lib/usePageView';
|
||||
@@ -20,10 +18,10 @@ type StatusFilter = 'ALL' | StoreStatusValue | 'PENDING_AUDIT' | 'REJECTED';
|
||||
const FILTERS: { key: StatusFilter; label: string }[] = [
|
||||
{ key: 'ALL', label: '全部' },
|
||||
{ key: 'OPEN', label: '营业中' },
|
||||
{ key: 'PAUSED', label: '暂时闭店' },
|
||||
{ key: 'PAUSED', label: '临时闭店' },
|
||||
{ key: 'PENDING_AUDIT', label: '待审核' },
|
||||
{ key: 'REJECTED', label: '已驳回' },
|
||||
{ key: 'CLOSED', label: '关闭' },
|
||||
{ key: 'CLOSED', label: '永久闭店' },
|
||||
];
|
||||
|
||||
export default function StoreListPage() {
|
||||
@@ -46,7 +44,10 @@ export default function StoreListPage() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoggedIn()) { navigate('/login'); return; }
|
||||
if (!isLoggedIn()) {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
void loadStores();
|
||||
}, [navigate, loadStores]);
|
||||
|
||||
@@ -54,20 +55,28 @@ export default function StoreListPage() {
|
||||
document.title = canMutate ? '门店管理' : '我的门店';
|
||||
}, [canMutate]);
|
||||
|
||||
const filtered = useMemo(() => stores.filter((s) => {
|
||||
const matchQ = !q || String(s.name).includes(q) || String(s.address).includes(q);
|
||||
const audit = String(s.auditStatus || 'APPROVED').toUpperCase();
|
||||
const status = String(s.status).toUpperCase();
|
||||
let matchStatus = true;
|
||||
if (filter === 'PENDING_AUDIT') matchStatus = audit === 'PENDING';
|
||||
else if (filter === 'REJECTED') matchStatus = audit === 'REJECTED';
|
||||
else if (filter !== 'ALL') matchStatus = status === filter;
|
||||
return matchQ && matchStatus;
|
||||
}), [stores, q, filter]);
|
||||
const filtered = useMemo(
|
||||
() =>
|
||||
stores.filter((s) => {
|
||||
const matchQ = !q || String(s.name).includes(q) || String(s.address).includes(q);
|
||||
const audit = String(s.auditStatus || 'APPROVED').toUpperCase();
|
||||
const status = String(s.status).toUpperCase();
|
||||
let matchStatus = true;
|
||||
if (filter === 'PENDING_AUDIT') matchStatus = audit === 'PENDING';
|
||||
else if (filter === 'REJECTED') matchStatus = audit === 'REJECTED';
|
||||
else if (filter !== 'ALL') matchStatus = status === filter;
|
||||
return matchQ && matchStatus;
|
||||
}),
|
||||
[stores, q, filter],
|
||||
);
|
||||
|
||||
async function updateStatus(storeId: string, next: StoreStatusValue, auditStatus?: string) {
|
||||
if (next === 'OPEN' && !canPartnerOpenStore(auditStatus)) {
|
||||
setError(auditStatus === 'REJECTED' ? '门店审核未通过,请查看驳回原因并修改后重新提交' : '门店尚在总部审核中,通过后方可开门');
|
||||
setError(
|
||||
auditStatus === 'REJECTED'
|
||||
? '门店审核未通过,请查看驳回原因并修改后重新提交'
|
||||
: '门店尚在总部审核中,通过后方可开门',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (next === 'CLOSED') {
|
||||
@@ -82,7 +91,8 @@ export default function StoreListPage() {
|
||||
body: JSON.stringify({ status: next }),
|
||||
});
|
||||
await loadStores();
|
||||
if (next === 'OPEN') toastSuccess('开店成功');
|
||||
if (next === 'OPEN') toastSuccess('已营业');
|
||||
if (next === 'PAUSED') toastSuccess('已临时闭店');
|
||||
} catch {
|
||||
/* request 已 toast */
|
||||
} finally {
|
||||
@@ -102,6 +112,7 @@ export default function StoreListPage() {
|
||||
body: JSON.stringify({ status: 'CLOSED' }),
|
||||
});
|
||||
await loadStores();
|
||||
toastSuccess('已永久闭店');
|
||||
} catch {
|
||||
/* request 已 toast */
|
||||
} finally {
|
||||
@@ -111,29 +122,43 @@ export default function StoreListPage() {
|
||||
|
||||
return (
|
||||
<PullToRefresh onRefresh={loadStores} className="page partner-store-page partner-home--flush-top">
|
||||
{error && <p className="partner-form-error" role="alert" style={{ margin: '0 20px 12px' }}>{error}</p>}
|
||||
{error && (
|
||||
<p className="partner-form-error" role="alert" style={{ margin: '0 20px 12px' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="partner-sticky-filter">
|
||||
<div className="partner-search">
|
||||
<span className="material-symbols-outlined">search</span>
|
||||
<input placeholder="搜索门店名称/地址" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</div>
|
||||
<div className="partner-chips">
|
||||
{FILTERS.map((f) => (
|
||||
<button key={f.key} type="button" className={`partner-chip${filter === f.key ? ' active' : ''}`} onClick={() => setFilter(f.key)}>
|
||||
{f.label}
|
||||
</button>
|
||||
))}
|
||||
<div className="partner-store-filter-row">
|
||||
<label className="partner-store-filter-label" htmlFor="partner-store-status-filter">
|
||||
状态
|
||||
</label>
|
||||
<select
|
||||
id="partner-store-status-filter"
|
||||
className="partner-store-filter-select"
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value as StatusFilter)}
|
||||
>
|
||||
{FILTERS.map((f) => (
|
||||
<option key={f.key} value={f.key}>
|
||||
{f.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canCreate && (
|
||||
<Link to="/stores/new" className="partner-fab-link">
|
||||
<button type="button" className="partner-btn-primary">
|
||||
<span className="material-symbols-outlined">add_business</span>
|
||||
录入新门店
|
||||
</button>
|
||||
</Link>
|
||||
<Link to="/stores/new" className="partner-fab-link">
|
||||
<button type="button" className="partner-btn-primary">
|
||||
<span className="material-symbols-outlined">add_business</span>
|
||||
录入新门店
|
||||
</button>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{filtered.length === 0 && <div className="empty">暂无门店</div>}
|
||||
@@ -145,87 +170,114 @@ export default function StoreListPage() {
|
||||
const dim = currentStatus === 'CLOSED';
|
||||
const storeName = String(s.name || '未命名门店');
|
||||
const busy = updatingId === storeId;
|
||||
const canOpen = canPartnerOpenStore(auditStatus);
|
||||
const badge = storeListBadge(s);
|
||||
const switchOn = currentStatus === 'OPEN';
|
||||
const switchDisabled =
|
||||
busy ||
|
||||
currentStatus === 'CLOSED' ||
|
||||
auditStatus === 'PENDING' ||
|
||||
auditStatus === 'REJECTED';
|
||||
return (
|
||||
<div key={storeId} className={`partner-store-card${dim ? ' partner-store-card--dim' : ''}`}>
|
||||
<Link to={`/stores/${storeId}`} className="partner-store-card-hit" style={{ color: 'inherit', textDecoration: 'none' }}>
|
||||
<Link
|
||||
to={`/stores/${storeId}`}
|
||||
className="partner-store-card-hit"
|
||||
style={{ color: 'inherit', textDecoration: 'none' }}
|
||||
>
|
||||
<div className="partner-store-card-header">
|
||||
<div>
|
||||
<p className="label-md text-muted" style={{ marginBottom: 2 }}>门店名称</p>
|
||||
<div className="partner-store-card-main">
|
||||
<p className="label-md text-muted" style={{ marginBottom: 2 }}>
|
||||
门店名称
|
||||
</p>
|
||||
<h3 className="headline-md">{storeName}</h3>
|
||||
<p className="label-md text-muted" style={{ marginTop: 4 }}>{String(s.address || s.district || '')}</p>
|
||||
{auditStatus !== 'APPROVED' && (
|
||||
<p className="label-md" style={{ marginTop: 8, color: auditStatus === 'REJECTED' ? 'var(--color-heritage-red)' : 'var(--color-secondary)' }}>
|
||||
{storeAuditLabel(auditStatus)}
|
||||
{auditStatus === 'REJECTED' && s.rejectReason ? `:${String(s.rejectReason)}` : ''}
|
||||
<p className="label-md text-muted" style={{ marginTop: 4 }}>
|
||||
{String(s.address || s.district || '')}
|
||||
</p>
|
||||
{auditStatus === 'REJECTED' && s.rejectReason ? (
|
||||
<p
|
||||
className="label-md"
|
||||
style={{ marginTop: 8, color: 'var(--color-heritage-red)' }}
|
||||
>
|
||||
{storeAuditLabel(auditStatus)}:{String(s.rejectReason)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
|
||||
{auditStatus !== 'APPROVED' ? (
|
||||
<span className={`partner-status-pill ${storeAuditPillClass(auditStatus)}`}>
|
||||
{storeAuditLabel(auditStatus)}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`partner-status-pill ${storeStatusPillClass(currentStatus)}`}>
|
||||
{storeStatusLabel(currentStatus)}
|
||||
</span>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
<span className={`partner-status-pill partner-store-card-badge ${badge.pillClass}`}>
|
||||
{badge.label}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
{canMutate && (
|
||||
<div className="partner-store-card-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-outline"
|
||||
style={{ fontSize: 12, padding: '8px 12px' }}
|
||||
disabled={busy || currentStatus === 'CLOSED' || currentStatus === 'PAUSED' || auditStatus === 'PENDING'}
|
||||
onClick={() => void updateStatus(storeId, 'PAUSED', auditStatus)}
|
||||
>
|
||||
暂时闭店
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-outline"
|
||||
style={{ fontSize: 12, padding: '8px 12px', borderColor: 'var(--color-subtle-gray)', color: 'var(--color-subtle-gray)' }}
|
||||
disabled={busy || currentStatus === 'CLOSED'}
|
||||
onClick={() => void updateStatus(storeId, 'CLOSED', auditStatus)}
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
{currentStatus === 'PAUSED' && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-outline"
|
||||
style={{ fontSize: 12, padding: '8px 12px' }}
|
||||
disabled={busy || !canOpen}
|
||||
onClick={() => void updateStatus(storeId, 'OPEN', auditStatus)}
|
||||
{canMutate ? (
|
||||
<div className="partner-store-card-actions partner-store-card-actions--v3416">
|
||||
{currentStatus !== 'CLOSED' ? (
|
||||
<>
|
||||
<label
|
||||
className={`partner-store-switch${switchDisabled ? ' partner-store-switch--disabled' : ''}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={switchOn}
|
||||
disabled={switchDisabled}
|
||||
aria-label={switchOn ? '营业中,点击临时闭店' : '临时闭店,点击营业'}
|
||||
onChange={() => {
|
||||
const next: StoreStatusValue = switchOn ? 'PAUSED' : 'OPEN';
|
||||
void updateStatus(storeId, next, auditStatus);
|
||||
}}
|
||||
/>
|
||||
<span className="partner-store-switch-track" aria-hidden />
|
||||
<span className="partner-store-switch-text">
|
||||
{switchOn ? '开启(营业中)' : '关闭(临时闭店)'}
|
||||
</span>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="partner-store-close-btn"
|
||||
disabled={busy}
|
||||
onClick={() => void updateStatus(storeId, 'CLOSED', auditStatus)}
|
||||
>
|
||||
永久闭店
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<Link
|
||||
to={`/stores/${storeId}`}
|
||||
className="partner-menu-icon"
|
||||
style={{ width: 40, height: 40, borderRadius: 8, textDecoration: 'none' }}
|
||||
>
|
||||
{canOpen ? '开门营业' : '待审核通过'}
|
||||
</button>
|
||||
)}
|
||||
<Link to={`/stores/${storeId}`} className="partner-menu-icon" style={{ width: 40, height: 40, borderRadius: 8, textDecoration: 'none' }}>
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>edit</span>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
<span className="material-symbols-outlined" style={{ fontSize: 20 }}>
|
||||
edit
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{closeTarget && (
|
||||
<div className="partner-ship-modal-backdrop" role="presentation" onClick={() => setCloseTarget(null)}>
|
||||
<div className="partner-ship-modal" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
|
||||
<h3 className="headline-md" style={{ marginBottom: 8 }}>确认关闭门店?</h3>
|
||||
<div
|
||||
className="partner-ship-modal-backdrop"
|
||||
role="presentation"
|
||||
onClick={() => setCloseTarget(null)}
|
||||
>
|
||||
<div
|
||||
className="partner-ship-modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h3 className="headline-md" style={{ marginBottom: 8 }}>
|
||||
确认永久闭店?
|
||||
</h3>
|
||||
<p className="body-md text-muted" style={{ lineHeight: 1.5 }}>
|
||||
关闭后不可恢复营业,确认关闭该门店?
|
||||
永久闭店后不可再开门营业,确认关闭该门店?
|
||||
</p>
|
||||
<div className="partner-ship-actions">
|
||||
<button type="button" className="partner-btn-secondary" onClick={() => setCloseTarget(null)}>
|
||||
取消
|
||||
</button>
|
||||
<button type="button" className="partner-btn-primary" onClick={() => void confirmCloseStore()}>
|
||||
确认关闭
|
||||
确认永久闭店
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -304,6 +304,30 @@ html {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 卡片标题旁的紧凑型描边按钮:不拉伸、缩小尺寸、贴右对齐 */
|
||||
.partner-btn-outline--compact {
|
||||
flex: none;
|
||||
height: 30px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid var(--color-outline);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
font-family: var(--font-label);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
}
|
||||
.partner-btn-outline--compact:hover {
|
||||
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
.partner-btn-outline--compact:active {
|
||||
transform: scale(0.97);
|
||||
}
|
||||
|
||||
.partner-btn-wechat {
|
||||
width: 100%;
|
||||
padding: 16px;
|
||||
@@ -1960,6 +1984,134 @@ nav.app-tabbar .app-tabbar-label {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.partner-store-filter-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.partner-store-filter-label {
|
||||
flex-shrink: 0;
|
||||
font-family: var(--font-label);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.partner-store-filter-select {
|
||||
flex: 1;
|
||||
height: 40px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--color-outline-variant);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-container-low);
|
||||
font-size: 14px;
|
||||
color: var(--color-ink-black);
|
||||
}
|
||||
|
||||
.partner-store-filter-select:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px rgba(166, 29, 36, 0.2);
|
||||
}
|
||||
|
||||
.partner-store-card-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.partner-store-card-badge {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.partner-store-card-actions--v3416 {
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.partner-store-card-actions--v3416 > .partner-store-switch {
|
||||
flex: 1 1 auto;
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.partner-store-card-actions--v3416 > .partner-store-close-btn {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.partner-store-card-actions--v3416 > .partner-menu-icon {
|
||||
flex: 0 0 auto;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.partner-store-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
font-family: var(--font-label);
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.partner-store-switch input {
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.partner-store-switch-track {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
height: 24px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-surface-container-highest);
|
||||
transition: background 0.2s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.partner-store-switch-track::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.partner-store-switch input:checked + .partner-store-switch-track {
|
||||
background: var(--color-success-green);
|
||||
}
|
||||
|
||||
.partner-store-switch input:checked + .partner-store-switch-track::after {
|
||||
transform: translateX(20px);
|
||||
}
|
||||
|
||||
.partner-store-switch--disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.partner-store-close-btn {
|
||||
flex: 0 0 auto !important;
|
||||
padding: 8px 12px !important;
|
||||
border: 1px solid rgba(166, 29, 36, 0.35);
|
||||
background: transparent;
|
||||
color: var(--color-heritage-red);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.partner-store-close-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.partner-store-card {
|
||||
background: var(--color-card);
|
||||
border-radius: var(--radius-md);
|
||||
@@ -2061,6 +2213,39 @@ nav.app-tabbar .app-tabbar-label {
|
||||
margin: 0 var(--space-page) var(--space-md);
|
||||
}
|
||||
|
||||
.partner-onboard-cs-card {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.partner-onboard-cs-qr {
|
||||
display: block;
|
||||
width: min(220px, 70vw);
|
||||
height: auto;
|
||||
margin: 0 auto 16px;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--color-surface-container);
|
||||
}
|
||||
|
||||
.partner-onboard-cs-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
font-family: var(--font-label);
|
||||
font-size: 14px;
|
||||
color: var(--color-ink-black);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.partner-onboard-cs-check input {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ── Store detail ── */
|
||||
.partner-detail-page {
|
||||
padding-bottom: 96px;
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@dukang/shared-ui/*": ["../../packages/shared-ui/src/*"]
|
||||
"@dukang/shared-ui/*": ["../../packages/shared-ui/src/*"],
|
||||
"@dukang/domain": ["../../packages/domain/src/index.ts"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
|
||||
@@ -9,9 +9,11 @@ export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@dukang/shared-ui': path.resolve(__dirname, '../../packages/shared-ui/src'),
|
||||
'@dukang/domain': path.resolve(__dirname, '../../packages/domain/src/index.ts'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
port: 5175,
|
||||
proxy: {
|
||||
'/api': process.env.VITE_API_TARGET ?? 'http://localhost:3010',
|
||||
|
||||
@@ -148,8 +148,9 @@ export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
||||
|
||||
<label className="shop-packages-field">
|
||||
<span className="shop-packages-label">使用时间</span>
|
||||
<input
|
||||
<textarea
|
||||
className="shop-packages-input"
|
||||
rows={2}
|
||||
placeholder="节假日除外"
|
||||
value={item.usableTime || ''}
|
||||
disabled={disabled}
|
||||
@@ -213,8 +214,9 @@ export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
||||
|
||||
<label className="shop-packages-field">
|
||||
<span className="shop-packages-label">其他说明</span>
|
||||
<input
|
||||
<textarea
|
||||
className="shop-packages-input"
|
||||
rows={2}
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -202,7 +202,7 @@ async function rawRequest<T>(
|
||||
if (authToken) headers.Authorization = `Bearer ${authToken}`;
|
||||
|
||||
const res = await fetch(`${apiBase}${path}`, { ...options, headers });
|
||||
let json: { code: number; message?: string; data?: T };
|
||||
let json: { code: number; message?: string; data?: T; reason?: string };
|
||||
try {
|
||||
json = await res.json();
|
||||
} catch {
|
||||
@@ -213,8 +213,12 @@ async function rawRequest<T>(
|
||||
throw err;
|
||||
}
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
const err = new Error(json.message || '请求失败') as Error & {
|
||||
status?: number;
|
||||
reason?: string;
|
||||
};
|
||||
err.status = res.status >= 500 ? res.status : json.code;
|
||||
err.reason = json.reason;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
@@ -254,7 +258,15 @@ async function requestWithAuthRetry<T>(
|
||||
try {
|
||||
return await rawRequest<T>(path, options);
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const err = e as Error & { status?: number; reason?: string };
|
||||
// 账号停用 / 门店关闭 / 合伙人绑定失效:强制退出登录
|
||||
if (err.reason === 'ACCOUNT_DISABLED') {
|
||||
clearAuth();
|
||||
if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
|
||||
window.location.replace('/login?disabled=1');
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const canRecover =
|
||||
err.status === 401 &&
|
||||
!retried &&
|
||||
@@ -303,7 +315,14 @@ export async function ensureSession(): Promise<{
|
||||
needsSelectStore: needsStoreSelection({ store, stores: me.stores }),
|
||||
};
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const err = e as Error & { status?: number; reason?: string };
|
||||
if (err.reason === 'ACCOUNT_DISABLED') {
|
||||
clearAuth();
|
||||
if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
|
||||
window.location.replace('/login?disabled=1');
|
||||
}
|
||||
return { authenticated: false, store: null, needsSelectStore: false };
|
||||
}
|
||||
if (err.status === 401) {
|
||||
const refreshed = await refreshSession();
|
||||
if (refreshed) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
/**
|
||||
* v3.5.1 #2:门店端核销即时刷新。
|
||||
* 核销成功后,通过浏览器自定义事件通知「门店信息页 / 提现页」即时刷新余额与提现按钮状态,
|
||||
* 避免用户手动下拉刷新。
|
||||
*/
|
||||
|
||||
const REDEEM_SUCCESS_EVENT = 'shop:redeem-success';
|
||||
|
||||
export type RedeemSuccessPayload = {
|
||||
redeemNo?: string;
|
||||
amount?: number;
|
||||
storeId?: string;
|
||||
};
|
||||
|
||||
/** 核销成功页 mount 时调用,广播核销成功事件 */
|
||||
export function notifyRedeemSuccess(payload: RedeemSuccessPayload = {}) {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.dispatchEvent(new CustomEvent(REDEEM_SUCCESS_EVENT, { detail: payload }));
|
||||
}
|
||||
|
||||
/** 订阅核销成功事件,回调在事件触发时执行(通常用于刷新余额/提现状态) */
|
||||
export function useRedeemSuccessListener(
|
||||
callback: (payload: RedeemSuccessPayload) => void,
|
||||
deps: React.DependencyList = [],
|
||||
) {
|
||||
const savedCallback = useRef(callback);
|
||||
useEffect(() => {
|
||||
savedCallback.current = callback;
|
||||
}, [callback]);
|
||||
|
||||
useEffect(() => {
|
||||
function handler(e: Event) {
|
||||
const payload = (e as CustomEvent<RedeemSuccessPayload>).detail ?? {};
|
||||
savedCallback.current(payload);
|
||||
}
|
||||
window.addEventListener(REDEEM_SUCCESS_EVENT, handler);
|
||||
return () => window.removeEventListener(REDEEM_SUCCESS_EVENT, handler);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
}
|
||||
@@ -112,6 +112,10 @@ export default function HomePage() {
|
||||
|
||||
const [authError, setAuthError] = useState('');
|
||||
|
||||
const [showOpenModal, setShowOpenModal] = useState(false);
|
||||
|
||||
const [opening, setOpening] = useState(false);
|
||||
|
||||
const pendingScanStartedRef = useRef(false);
|
||||
|
||||
|
||||
@@ -309,6 +313,12 @@ export default function HomePage() {
|
||||
|
||||
setScanMsg('');
|
||||
|
||||
// 门店临时闭店/休息中(非营业状态)时,点击扫码直接提示,不进入扫码流程
|
||||
if (status !== 'OPEN') {
|
||||
setShowOpenModal(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isWechatEnv()) {
|
||||
|
||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||
@@ -349,6 +359,25 @@ export default function HomePage() {
|
||||
|
||||
|
||||
|
||||
async function openStoreAndContinue() {
|
||||
if (opening) return;
|
||||
setOpening(true);
|
||||
try {
|
||||
await request('SHOP_H5', '/shop/store/status', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ status: 'OPEN' }),
|
||||
});
|
||||
setShowOpenModal(false);
|
||||
setScanMsg('');
|
||||
void loadDashboard(); // 刷新门店状态为营业中,扫码按钮可再次使用
|
||||
} catch (e) {
|
||||
setShowOpenModal(false);
|
||||
setScanMsg(e instanceof Error ? e.message : '开启营业失败');
|
||||
} finally {
|
||||
setOpening(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function startWechatAuth() {
|
||||
|
||||
setAuthLoading(true);
|
||||
@@ -615,6 +644,33 @@ export default function HomePage() {
|
||||
|
||||
/>
|
||||
|
||||
{showOpenModal && (
|
||||
<div className="shop-redeem-modal" role="dialog" aria-modal="true">
|
||||
<div className="shop-redeem-modal-card">
|
||||
<h4 className="shop-redeem-modal-title">门店休息中</h4>
|
||||
<p className="shop-redeem-modal-desc">门店目前休息中无法核销,是否开启营业?</p>
|
||||
<div className="shop-redeem-modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-cancel"
|
||||
disabled={opening}
|
||||
onClick={() => setShowOpenModal(false)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-confirm"
|
||||
disabled={opening}
|
||||
onClick={() => void openStoreAndContinue()}
|
||||
>
|
||||
{opening ? '开启中…' : '确认开启'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</PullToRefresh>
|
||||
|
||||
);
|
||||
|
||||
@@ -86,6 +86,16 @@ export default function LoginPage() {
|
||||
if (hint) setMsg(hint);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (params.get('disabled') === '1') {
|
||||
setMsg('账号已被停用或门店已关闭,请重新登录');
|
||||
const next = new URLSearchParams(params);
|
||||
next.delete('disabled');
|
||||
setSearchParams(next, { replace: true });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||
void handleShopWechatCallbackOnce()
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../lib/wechat-auth';
|
||||
import { isWechatEnv } from '../lib/weixin';
|
||||
import { useStorePageView } from '../lib/usePageView';
|
||||
import { useRedeemSuccessListener } from '../lib/useRedeemSuccessBus';
|
||||
|
||||
export default function MinePage() {
|
||||
useStorePageView('store_mine_view');
|
||||
@@ -43,6 +44,11 @@ export default function MinePage() {
|
||||
void loadMine();
|
||||
}, [loadMine]);
|
||||
|
||||
// v3.5.1 #2:核销成功后即时刷新门店信息(余额等)
|
||||
useRedeemSuccessListener(() => {
|
||||
void loadMine();
|
||||
}, [loadMine]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWechatEnv() || !wxAuthorize || !searchParams.get('code')) return;
|
||||
void handleShopWechatCallbackOnce()
|
||||
|
||||
@@ -20,6 +20,8 @@ export default function PhoneRedeemPage() {
|
||||
const [msg, setMsg] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [confirmCooldown, setConfirmCooldown] = useState(0);
|
||||
const [showOpenModal, setShowOpenModal] = useState(false);
|
||||
const [opening, setOpening] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
||||
@@ -36,15 +38,7 @@ export default function PhoneRedeemPage() {
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [confirmCooldown]);
|
||||
|
||||
async function sendConfirmSms() {
|
||||
if (!/^1\d{10}$/.test(phone.trim())) {
|
||||
setMsg('请输入正确的手机号');
|
||||
return;
|
||||
}
|
||||
if (storeClosed) {
|
||||
setMsg('门店未营业,无法核销');
|
||||
return;
|
||||
}
|
||||
async function prepareDirectRedeem() {
|
||||
const value = Number(amount);
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
setMsg('请输入有效核销金额');
|
||||
@@ -69,6 +63,37 @@ export default function PhoneRedeemPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function sendConfirmSms() {
|
||||
if (!/^1\d{10}$/.test(phone.trim())) {
|
||||
setMsg('请输入正确的手机号');
|
||||
return;
|
||||
}
|
||||
if (storeClosed) {
|
||||
setShowOpenModal(true);
|
||||
return;
|
||||
}
|
||||
await prepareDirectRedeem();
|
||||
}
|
||||
|
||||
async function openStoreAndContinue() {
|
||||
if (opening) return;
|
||||
setOpening(true);
|
||||
try {
|
||||
await request('SHOP_H5', '/shop/store/status', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ status: 'OPEN' }),
|
||||
});
|
||||
setStoreClosed(false);
|
||||
setShowOpenModal(false);
|
||||
await prepareDirectRedeem();
|
||||
} catch (e) {
|
||||
setShowOpenModal(false);
|
||||
setMsg(e instanceof Error ? e.message : '开启营业失败');
|
||||
} finally {
|
||||
setOpening(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmRedeem() {
|
||||
if (!prepared) {
|
||||
setMsg('请先发送核销验证码');
|
||||
@@ -114,7 +139,7 @@ export default function PhoneRedeemPage() {
|
||||
|
||||
<main className="shop-redeem-main">
|
||||
{storeClosed && (
|
||||
<p className="shop-redeem-error" style={{ marginBottom: 12 }}>门店当前未营业,无法核销</p>
|
||||
<p className="shop-redeem-error" style={{ marginBottom: 12 }}>门店目前休息中无法核销,开启营业后可继续</p>
|
||||
)}
|
||||
|
||||
<section className="shop-redeem-card">
|
||||
@@ -181,7 +206,7 @@ export default function PhoneRedeemPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="shop-phone-code-btn"
|
||||
disabled={loading || confirmCooldown > 0 || storeClosed || !canSendCode}
|
||||
disabled={loading || confirmCooldown > 0 || !canSendCode}
|
||||
onClick={() => void sendConfirmSms()}
|
||||
>
|
||||
{confirmCooldown > 0 ? `${confirmCooldown}s` : '发送验证码'}
|
||||
@@ -205,6 +230,33 @@ export default function PhoneRedeemPage() {
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
{showOpenModal && (
|
||||
<div className="shop-redeem-modal" role="dialog" aria-modal="true">
|
||||
<div className="shop-redeem-modal-card">
|
||||
<h4 className="shop-redeem-modal-title">门店休息中</h4>
|
||||
<p className="shop-redeem-modal-desc">门店目前休息中无法核销,是否开启营业?</p>
|
||||
<div className="shop-redeem-modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-cancel"
|
||||
disabled={opening}
|
||||
onClick={() => setShowOpenModal(false)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-confirm"
|
||||
disabled={opening}
|
||||
onClick={() => void openStoreAndContinue()}
|
||||
>
|
||||
{opening ? '开启中…' : '确认开启'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ export default function RedeemConfirmPage() {
|
||||
const [storeClosed, setStoreClosed] = useState(false);
|
||||
const [failCount, setFailCount] = useState(0);
|
||||
const [showWeakNet, setShowWeakNet] = useState(false);
|
||||
const [showOpenModal, setShowOpenModal] = useState(false);
|
||||
const [opening, setOpening] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
request<Record<string, unknown>>('SHOP_H5', '/shop/store')
|
||||
@@ -48,34 +50,37 @@ export default function RedeemConfirmPage() {
|
||||
setToken(scanned);
|
||||
}, [searchParams, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadPreview() {
|
||||
if (!token.trim()) {
|
||||
setPreview(null);
|
||||
return;
|
||||
}
|
||||
request<Preview>('SHOP_H5', '/shop/redeem/preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
})
|
||||
.then(setPreview)
|
||||
.catch(async (e) => {
|
||||
setPreview(null);
|
||||
setMsg(e instanceof Error ? e.message : '无法预览核销码');
|
||||
const report = await reportRedeemFailure(token, 'preview', e);
|
||||
if (report?.thresholdReached) {
|
||||
setFailCount(report.failCount);
|
||||
setShowWeakNet(true);
|
||||
} else if (report) {
|
||||
setFailCount(report.failCount);
|
||||
}
|
||||
try {
|
||||
const p = await request<Preview>('SHOP_H5', '/shop/redeem/preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
setPreview(p);
|
||||
setMsg('');
|
||||
} catch (e) {
|
||||
setPreview(null);
|
||||
setMsg(e instanceof Error ? e.message : '无法预览核销码');
|
||||
const report = await reportRedeemFailure(token, 'preview', e);
|
||||
if (report?.thresholdReached) {
|
||||
setFailCount(report.failCount);
|
||||
setShowWeakNet(true);
|
||||
} else if (report) {
|
||||
setFailCount(report.failCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void loadPreview();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token]);
|
||||
|
||||
async function confirm() {
|
||||
if (storeClosed) {
|
||||
setMsg('门店未营业,无法核销');
|
||||
return;
|
||||
}
|
||||
async function doConfirm() {
|
||||
if (!token.trim()) {
|
||||
setMsg('请先扫码获取核销码');
|
||||
return;
|
||||
@@ -103,6 +108,36 @@ export default function RedeemConfirmPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (storeClosed) {
|
||||
setShowOpenModal(true);
|
||||
return;
|
||||
}
|
||||
await doConfirm();
|
||||
}
|
||||
|
||||
async function openStoreAndContinue() {
|
||||
if (opening) return;
|
||||
setOpening(true);
|
||||
try {
|
||||
await request('SHOP_H5', '/shop/store/status', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ status: 'OPEN' }),
|
||||
});
|
||||
setStoreClosed(false);
|
||||
setShowOpenModal(false);
|
||||
setMsg('');
|
||||
// 开张后重新拉取预览(门店已 OPEN,后端不再拦截),再继续核销
|
||||
await loadPreview();
|
||||
await doConfirm();
|
||||
} catch (e) {
|
||||
setShowOpenModal(false);
|
||||
setMsg(e instanceof Error ? e.message : '开启营业失败');
|
||||
} finally {
|
||||
setOpening(false);
|
||||
}
|
||||
}
|
||||
|
||||
const previewAmount = preview?.amount ?? 0;
|
||||
const userLabel = preview?.user?.nickname || preview?.user?.phone || '—';
|
||||
|
||||
@@ -117,7 +152,7 @@ export default function RedeemConfirmPage() {
|
||||
|
||||
<main className="shop-redeem-main">
|
||||
{storeClosed && (
|
||||
<p className="shop-redeem-error" style={{ marginBottom: 12 }}>门店当前未营业,无法核销</p>
|
||||
<p className="shop-redeem-error" style={{ marginBottom: 12 }}>门店目前休息中无法核销,开启营业后可继续</p>
|
||||
)}
|
||||
<section className="shop-redeem-card">
|
||||
<div className="shop-redeem-banner">
|
||||
@@ -189,13 +224,13 @@ export default function RedeemConfirmPage() {
|
||||
<button
|
||||
type="button"
|
||||
className={`shop-redeem-confirm-btn${loading ? ' success' : ''}`}
|
||||
disabled={loading || storeClosed || !preview}
|
||||
disabled={loading || (!preview && !storeClosed)}
|
||||
onClick={() => void confirm()}
|
||||
>
|
||||
<span className="material-symbols-outlined shop-fill-icon">
|
||||
{loading ? 'sync' : 'check_circle'}
|
||||
</span>
|
||||
<span>{loading ? '正在核销...' : preview ? `确认核销 ¥${formatAmount(previewAmount)}` : '加载中…'}</span>
|
||||
<span>{loading ? '正在核销...' : preview ? `确认核销 ¥${formatAmount(previewAmount)}` : storeClosed ? '确认核销' : '加载中…'}</span>
|
||||
</button>
|
||||
<p className="shop-redeem-hint">请核对金额后点击确认</p>
|
||||
</>
|
||||
@@ -213,6 +248,33 @@ export default function RedeemConfirmPage() {
|
||||
</span>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{showOpenModal && (
|
||||
<div className="shop-redeem-modal" role="dialog" aria-modal="true">
|
||||
<div className="shop-redeem-modal-card">
|
||||
<h4 className="shop-redeem-modal-title">门店休息中</h4>
|
||||
<p className="shop-redeem-modal-desc">门店目前休息中无法核销,是否开启营业?</p>
|
||||
<div className="shop-redeem-modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-cancel"
|
||||
disabled={opening}
|
||||
onClick={() => setShowOpenModal(false)}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-redeem-modal-confirm"
|
||||
disabled={opening}
|
||||
onClick={() => void openStoreAndContinue()}
|
||||
>
|
||||
{opening ? '开启中…' : '确认开启'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { notifyRedeemSuccess } from '../lib/useRedeemSuccessBus';
|
||||
|
||||
function formatAmount(n: number) {
|
||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
@@ -29,6 +30,14 @@ export default function RedeemSuccessPage() {
|
||||
? new Date(String(result.createdAt)).toLocaleString('zh-CN')
|
||||
: new Date().toLocaleString('zh-CN');
|
||||
|
||||
// v3.5.1 #2:核销成功后广播事件,通知门店信息页 / 提现页即时刷新
|
||||
useEffect(() => {
|
||||
notifyRedeemSuccess({
|
||||
redeemNo: redeemNo !== '—' ? redeemNo : undefined,
|
||||
amount,
|
||||
});
|
||||
}, [redeemNo, amount]);
|
||||
|
||||
return (
|
||||
<div className="shop-success-page">
|
||||
<header className="shop-success-header">
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||
import { request } from '../lib/api';
|
||||
import { useStorePageView } from '../lib/usePageView';
|
||||
import { useRedeemSuccessListener } from '../lib/useRedeemSuccessBus';
|
||||
|
||||
type StatusFilter = 'all' | StoreWithdrawStatus;
|
||||
|
||||
@@ -42,6 +43,11 @@ export default function WithdrawPage() {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// v3.5.1 #2:核销成功后即时刷新可提余额与提现按钮状态
|
||||
useRedeemSuccessListener(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (statusFilter === 'all') return items;
|
||||
return items.filter((r) => r.status === statusFilter);
|
||||
|
||||
@@ -1519,6 +1519,7 @@
|
||||
z-index: 40;
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-surface-container-highest);
|
||||
padding: 0 var(--space-page);
|
||||
}
|
||||
|
||||
.shop-records-range-tabs {
|
||||
@@ -1566,7 +1567,7 @@
|
||||
.shop-records-status-chips {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 0;
|
||||
padding-bottom: 10px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
flex: 1;
|
||||
@@ -1897,8 +1898,8 @@
|
||||
}
|
||||
|
||||
.shop-withdraw-btn {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
width: calc(100% - 2 * var(--space-page));
|
||||
margin: 12px var(--space-page) 0;
|
||||
height: 44px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
@@ -1916,11 +1917,80 @@
|
||||
|
||||
.shop-withdraw-msg {
|
||||
margin-top: 10px;
|
||||
padding: 0 var(--space-page);
|
||||
font-size: 13px;
|
||||
color: var(--color-aged-amber);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ─── 休息中核销·开张确认弹窗 ─── */
|
||||
.shop-redeem-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.shop-redeem-modal-card {
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
background: var(--color-surface);
|
||||
border-radius: var(--radius-lg, 16px);
|
||||
padding: 24px;
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.shop-redeem-modal-title {
|
||||
margin: 0 0 8px;
|
||||
font-family: var(--font-headline);
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
color: var(--color-on-surface);
|
||||
}
|
||||
|
||||
.shop-redeem-modal-desc {
|
||||
margin: 0 0 20px;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.shop-redeem-modal-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.shop-redeem-modal-cancel,
|
||||
.shop-redeem-modal-confirm {
|
||||
flex: 1;
|
||||
padding: 11px 0;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-redeem-modal-cancel {
|
||||
background: var(--color-surface-container, #ececec);
|
||||
color: var(--color-on-surface-variant);
|
||||
}
|
||||
|
||||
.shop-redeem-modal-confirm {
|
||||
background: var(--color-primary, #8b1a1a);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.shop-redeem-modal-cancel:disabled,
|
||||
.shop-redeem-modal-confirm:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ─── 门店套餐 ─── */
|
||||
.shop-packages-page .shop-records-main {
|
||||
padding-bottom: 24px;
|
||||
|
||||
@@ -12,6 +12,7 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
port: 5174,
|
||||
proxy: { '/api': process.env.VITE_API_TARGET ?? 'http://localhost:3010' },
|
||||
},
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
# 企业微信客服链接(覆盖 shared-types 默认值)
|
||||
# VITE_CS_WECOM_URL=https://work.weixin.qq.com/kfid/kfc8b88659a1dffa8cd
|
||||
@@ -1,15 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<title>杜康好客</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@400;500;600&family=Inter:wght@500&family=Manrope:wght@600;700&family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "@dukang/h5-user",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --port 5173",
|
||||
"build": "vite build",
|
||||
"lint": "echo ok"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dukang/client-logging": "workspace:*",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"@dukang/weixin-sdk": "workspace:*",
|
||||
"element-china-area-data": "^6.1.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"typescript": "^5.4.5",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
ayPJ4CQqbUcec3jX
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 329 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 301 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 332 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 356 KiB |
@@ -1,75 +0,0 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { useEffect } from 'react';
|
||||
import TabLayout from './layouts/TabLayout';
|
||||
import LoginPage from './pages/LoginPage';
|
||||
import LegalPage from './pages/LegalPage';
|
||||
import HomePage from './pages/HomePage';
|
||||
import ProductDetailPage from './pages/ProductDetailPage';
|
||||
import OrderConfirmPage from './pages/OrderConfirmPage';
|
||||
import AddressListPage from './pages/AddressListPage';
|
||||
import AddressEditPage from './pages/AddressEditPage';
|
||||
import OrderListPage from './pages/OrderListPage';
|
||||
import OrderDetailPage from './pages/OrderDetailPage';
|
||||
import StoreListPage from './pages/StoreListPage';
|
||||
import StoreDetailPage from './pages/StoreDetailPage';
|
||||
import BenefitPage from './pages/BenefitPage';
|
||||
import BenefitDetailPage from './pages/BenefitDetailPage';
|
||||
import MinePage from './pages/MinePage';
|
||||
import RedeemPage from './pages/RedeemPage';
|
||||
import RedeemCodePage from './pages/RedeemCodePage';
|
||||
import RedeemSuccessPage from './pages/RedeemSuccessPage';
|
||||
import PayPage from './pages/PayPage';
|
||||
import CustomerServicePage from './pages/CustomerServicePage';
|
||||
import AfterSalePage from './pages/AfterSalePage';
|
||||
import AfterSaleListPage from './pages/AfterSaleListPage';
|
||||
import InvoiceApplyPage from './pages/InvoiceApplyPage';
|
||||
import InvoiceListPage from './pages/InvoiceListPage';
|
||||
import { UserSessionProvider } from './contexts/UserSessionContext';
|
||||
import { capturePromoFromUrl } from './lib/promo';
|
||||
import WechatShareBootstrap from './components/WechatShareBootstrap';
|
||||
|
||||
function PromoBootstrap() {
|
||||
useEffect(() => {
|
||||
capturePromoFromUrl();
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<UserSessionProvider>
|
||||
<PromoBootstrap />
|
||||
<WechatShareBootstrap />
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/legal/user-agreement" element={<LegalPage docId="user-agreement" />} />
|
||||
<Route path="/legal/privacy-policy" element={<LegalPage docId="privacy-policy" />} />
|
||||
<Route element={<TabLayout />}>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/stores" element={<StoreListPage />} />
|
||||
<Route path="/benefit" element={<BenefitPage />} />
|
||||
<Route path="/mine" element={<MinePage />} />
|
||||
</Route>
|
||||
<Route path="/product/:id" element={<ProductDetailPage />} />
|
||||
<Route path="/stores/:id" element={<StoreDetailPage />} />
|
||||
<Route path="/order/confirm" element={<OrderConfirmPage />} />
|
||||
<Route path="/pay" element={<PayPage />} />
|
||||
<Route path="/customer-service" element={<CustomerServicePage />} />
|
||||
<Route path="/after-sale" element={<AfterSalePage />} />
|
||||
<Route path="/after-sale/list" element={<AfterSaleListPage />} />
|
||||
<Route path="/invoices" element={<InvoiceListPage />} />
|
||||
<Route path="/invoices/apply" element={<InvoiceApplyPage />} />
|
||||
<Route path="/addresses" element={<AddressListPage />} />
|
||||
<Route path="/addresses/new" element={<AddressEditPage />} />
|
||||
<Route path="/addresses/:id/edit" element={<AddressEditPage />} />
|
||||
<Route path="/orders" element={<OrderListPage />} />
|
||||
<Route path="/orders/:id" element={<OrderDetailPage />} />
|
||||
<Route path="/benefit/:id" element={<BenefitDetailPage />} />
|
||||
<Route path="/redeem" element={<RedeemPage />} />
|
||||
<Route path="/redeem/code" element={<RedeemCodePage />} />
|
||||
<Route path="/redeem/success" element={<RedeemSuccessPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</UserSessionProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
type AppToastProps = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export default function AppToast({ message }: AppToastProps) {
|
||||
if (!message) return null;
|
||||
return <div className="app-toast">{message}</div>;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { track } from '../lib/analytics';
|
||||
import {
|
||||
getCustomerServicePhone,
|
||||
loadCustomerServicePhone,
|
||||
openWecomCustomerService,
|
||||
} from '../lib/customer-service';
|
||||
|
||||
type ContactCustomerSheetProps = {
|
||||
orderId?: string;
|
||||
orderNo?: string;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export default function ContactCustomerSheet({ orderId, onClose }: ContactCustomerSheetProps) {
|
||||
const [phone, setPhone] = useState(getCustomerServicePhone);
|
||||
|
||||
useEffect(() => {
|
||||
void loadCustomerServicePhone().then(setPhone);
|
||||
}, []);
|
||||
|
||||
const tel = phone.replace(/-/g, '');
|
||||
|
||||
function openPhone() {
|
||||
track('cs_contact', { type: 'phone', orderId });
|
||||
window.location.href = `tel:${tel}`;
|
||||
onClose();
|
||||
}
|
||||
|
||||
function openOnline() {
|
||||
track('cs_contact', { type: 'wecom_kf', orderId });
|
||||
if (openWecomCustomerService()) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="contact-customer-overlay" onClick={onClose}>
|
||||
<div className="contact-customer-sheet" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="contact-customer-head">
|
||||
<h3>联系客服</h3>
|
||||
<button type="button" className="contact-customer-close" aria-label="关闭" onClick={onClose}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="contact-customer-options">
|
||||
<button type="button" className="contact-customer-option" onClick={openPhone}>
|
||||
<div className="contact-customer-option-icon">
|
||||
<span className="material-symbols-outlined">call</span>
|
||||
</div>
|
||||
<div className="contact-customer-option-body">
|
||||
<p className="contact-customer-option-title">拨打总部客服电话</p>
|
||||
<p className="contact-customer-option-sub">{phone}</p>
|
||||
</div>
|
||||
<span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
|
||||
</button>
|
||||
|
||||
<button type="button" className="contact-customer-option" onClick={openOnline}>
|
||||
<div className="contact-customer-option-icon">
|
||||
<span className="material-symbols-outlined">chat</span>
|
||||
</div>
|
||||
<div className="contact-customer-option-body">
|
||||
<p className="contact-customer-option-title">在线客服</p>
|
||||
<p className="contact-customer-option-sub">专业客服实时解答</p>
|
||||
</div>
|
||||
<span className="material-symbols-outlined contact-customer-chevron">chevron_right</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" className="contact-customer-cancel" onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { WechatLoginResult } from '@dukang/shared-types';
|
||||
import { SmsScene } from '@dukang/shared-types';
|
||||
import { bindPhone, request, type SessionPayload } from '../lib/api';
|
||||
import { normalizePhoneInput, validateMobilePhone } from '../lib/phone';
|
||||
import { useSmsCode } from '../lib/use-sms-code';
|
||||
import { useUserSession } from '../contexts/UserSessionContext';
|
||||
|
||||
type PhoneVerifySheetProps = {
|
||||
open: boolean;
|
||||
/** 打开时预填手机号(如收货地址中的手机号) */
|
||||
defaultPhone?: string;
|
||||
mode?: 'bind_phone' | 'wechat_bind_phone';
|
||||
wxSessionKey?: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
};
|
||||
|
||||
export default function PhoneVerifySheet({
|
||||
open,
|
||||
defaultPhone,
|
||||
mode = 'bind_phone',
|
||||
wxSessionKey,
|
||||
title,
|
||||
description,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: PhoneVerifySheetProps) {
|
||||
const { applySession } = useUserSession();
|
||||
const [phone, setPhone] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { sendCode, sending, codeCooldown, sentHint, error, setError, clearMessages } = useSmsCode();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setPhone('');
|
||||
setCode('');
|
||||
setError('');
|
||||
clearMessages();
|
||||
return;
|
||||
}
|
||||
if (defaultPhone) {
|
||||
const normalized = normalizePhoneInput(defaultPhone);
|
||||
if (validateMobilePhone(normalized).ok) {
|
||||
setPhone(normalized);
|
||||
}
|
||||
}
|
||||
}, [open, defaultPhone, clearMessages, setError]);
|
||||
|
||||
async function onSendCode() {
|
||||
clearMessages();
|
||||
await sendCode(phone, SmsScene.BIND_PHONE);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const phoneCheck = validateMobilePhone(phone);
|
||||
if (!phoneCheck.ok) {
|
||||
setError(phoneCheck.message ?? '请输入正确的手机号码');
|
||||
return;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
setError('请输入验证码');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
if (mode === 'wechat_bind_phone') {
|
||||
if (!wxSessionKey) {
|
||||
setError('微信会话已过期,请重新授权');
|
||||
return;
|
||||
}
|
||||
const data = await request<WechatLoginResult>('USER_H5', '/auth/wechat/bind-phone', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ wxSessionKey, phone, code }),
|
||||
});
|
||||
if (data.accessToken) {
|
||||
applySession({
|
||||
accessToken: data.accessToken,
|
||||
refreshToken: data.refreshToken ?? '',
|
||||
deviceKey: data.deviceKey,
|
||||
phoneVerified: !!data.phoneVerified,
|
||||
user: data.user as SessionPayload['user'],
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const session = await bindPhone(phone, code);
|
||||
applySession(session as SessionPayload);
|
||||
}
|
||||
onSuccess();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '验证失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const sheetTitle = title ?? (mode === 'wechat_bind_phone' ? '绑定手机号' : '验证手机号');
|
||||
const sheetDesc =
|
||||
description ??
|
||||
(mode === 'wechat_bind_phone'
|
||||
? '建议绑定手机号,便于订单通知与售后;关闭可跳过继续支付'
|
||||
: '建议绑定手机号,便于订单通知与售后;关闭可跳过继续下单');
|
||||
|
||||
return (
|
||||
<div className="phone-verify-overlay" role="dialog" aria-modal="true">
|
||||
<button type="button" className="phone-verify-backdrop" aria-label="关闭" onClick={onClose} />
|
||||
<div className="phone-verify-sheet">
|
||||
<h3 className="phone-verify-title">{sheetTitle}</h3>
|
||||
<p className="phone-verify-desc">{sheetDesc}</p>
|
||||
<div className="login-field">
|
||||
<span className="login-field-prefix">+86</span>
|
||||
<input
|
||||
type="tel"
|
||||
className="login-field-input"
|
||||
placeholder="请输入手机号"
|
||||
maxLength={11}
|
||||
inputMode="numeric"
|
||||
value={phone}
|
||||
onChange={(e) => {
|
||||
setPhone(normalizePhoneInput(e.target.value));
|
||||
setError('');
|
||||
clearMessages();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="login-field">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
className="login-field-input"
|
||||
placeholder="请输入验证码"
|
||||
maxLength={6}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={`login-get-code${codeCooldown > 0 || sending ? ' disabled' : ''}`}
|
||||
disabled={codeCooldown > 0 || sending}
|
||||
onClick={onSendCode}
|
||||
>
|
||||
{sending
|
||||
? '发送中...'
|
||||
: codeCooldown > 0
|
||||
? `${codeCooldown}s 后重新获取`
|
||||
: '获取验证码'}
|
||||
</button>
|
||||
</div>
|
||||
{(error || sentHint) && (
|
||||
<p className={`login-msg${sentHint && !error ? ' login-msg--hint' : ''}`}>{error || sentHint}</p>
|
||||
)}
|
||||
<button type="button" className="login-sms-btn" disabled={loading} onClick={submit}>
|
||||
{loading ? '验证中...' : mode === 'wechat_bind_phone' ? '确认绑定' : '确认验证'}
|
||||
</button>
|
||||
<button type="button" className="phone-verify-skip" onClick={onClose}>
|
||||
暂不绑定
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import AppImage from '@dukang/shared-ui/AppImage';
|
||||
|
||||
type Props = {
|
||||
images: string[];
|
||||
alt: string;
|
||||
variant?: 'home' | 'detail' | 'store';
|
||||
};
|
||||
|
||||
export default function ProductCarousel({ images, alt, variant = 'home' }: Props) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const slides = images.length > 0 ? images : [''];
|
||||
|
||||
function onScroll() {
|
||||
const el = scrollRef.current;
|
||||
if (!el || el.offsetWidth === 0) return;
|
||||
setActiveIndex(Math.round(el.scrollLeft / el.offsetWidth));
|
||||
}
|
||||
|
||||
const wrapClass =
|
||||
variant === 'store'
|
||||
? 'store-detail-carousel-wrap'
|
||||
: variant === 'detail'
|
||||
? 'detail-carousel-wrap'
|
||||
: 'home-carousel-wrap';
|
||||
const trackClass =
|
||||
variant === 'store'
|
||||
? 'store-detail-carousel'
|
||||
: variant === 'detail'
|
||||
? 'detail-carousel'
|
||||
: 'home-carousel';
|
||||
const dotClass =
|
||||
variant === 'store'
|
||||
? 'store-detail-carousel-dot'
|
||||
: variant === 'detail'
|
||||
? 'detail-carousel-dot'
|
||||
: 'home-carousel-dot';
|
||||
const itemClass =
|
||||
variant === 'store'
|
||||
? 'store-detail-carousel-item'
|
||||
: variant === 'detail'
|
||||
? 'detail-carousel-item'
|
||||
: 'home-carousel-item';
|
||||
const placeholderClass =
|
||||
variant === 'store'
|
||||
? 'store-detail-carousel-placeholder'
|
||||
: variant === 'detail'
|
||||
? 'detail-carousel-placeholder'
|
||||
: 'home-carousel-placeholder';
|
||||
|
||||
return (
|
||||
<div className={wrapClass}>
|
||||
<div className={trackClass} ref={scrollRef} onScroll={onScroll}>
|
||||
{slides.map((src, i) => (
|
||||
<div key={i} className={itemClass}>
|
||||
{src ? (
|
||||
<AppImage src={src} alt={alt} wrapperClassName="app-image--fill" />
|
||||
) : (
|
||||
<div className={placeholderClass} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{slides.length > 1 && (
|
||||
<div className={variant === 'store' ? 'store-detail-carousel-dots' : variant === 'detail' ? 'detail-carousel-dots' : 'home-carousel-dots'}>
|
||||
{slides.map((_, i) => (
|
||||
<span key={i} className={`${dotClass}${i === activeIndex ? ' active' : ''}`} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
REGION_ALL,
|
||||
getCities,
|
||||
getCitiesForPicker,
|
||||
getDistricts,
|
||||
getDistrictsForPicker,
|
||||
getProvincesForPicker,
|
||||
normalizeRegionSelection,
|
||||
toCityLevelRegion,
|
||||
type RegionSelection,
|
||||
} from '../lib/region-data';
|
||||
|
||||
type RegionPickerProps = {
|
||||
open: boolean;
|
||||
value: RegionSelection;
|
||||
onClose: () => void;
|
||||
onConfirm: (region: RegionSelection) => void;
|
||||
/** 2 = 仅省/市(门店列表);3 = 省/市/区(地址等) */
|
||||
levels?: 2 | 3;
|
||||
};
|
||||
|
||||
type PickerLevel = 'province' | 'city' | 'district';
|
||||
|
||||
const ALL_TABS: Array<{ key: PickerLevel; label: string }> = [
|
||||
{ key: 'province', label: '省份' },
|
||||
{ key: 'city', label: '城市' },
|
||||
{ key: 'district', label: '区县' },
|
||||
];
|
||||
|
||||
function initialTab(value: RegionSelection, levels: 2 | 3): PickerLevel {
|
||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
||||
if (levels === 2) {
|
||||
return normalized.province && normalized.province !== REGION_ALL ? 'city' : 'province';
|
||||
}
|
||||
if (normalized.district && normalized.district !== REGION_ALL) return 'district';
|
||||
if (normalized.city && normalized.city !== REGION_ALL) return 'city';
|
||||
return 'province';
|
||||
}
|
||||
|
||||
function tabLabel(tab: PickerLevel, draft: RegionSelection, fallback: string) {
|
||||
if (tab === 'province') {
|
||||
return draft.province && draft.province !== REGION_ALL ? draft.province : fallback;
|
||||
}
|
||||
if (tab === 'city') {
|
||||
return draft.city && draft.city !== REGION_ALL ? draft.city : fallback;
|
||||
}
|
||||
return draft.district && draft.district !== REGION_ALL ? draft.district : fallback;
|
||||
}
|
||||
|
||||
export default function RegionPicker({
|
||||
open,
|
||||
value,
|
||||
onClose,
|
||||
onConfirm,
|
||||
levels = 3,
|
||||
}: RegionPickerProps) {
|
||||
const [draft, setDraft] = useState<RegionSelection>(value);
|
||||
const [activeTab, setActiveTab] = useState<PickerLevel>('province');
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const tabs = levels === 2 ? ALL_TABS.slice(0, 2) : ALL_TABS;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const normalized = levels === 2 ? toCityLevelRegion(value) : normalizeRegionSelection(value);
|
||||
setDraft(normalized);
|
||||
setActiveTab(initialTab(value, levels));
|
||||
}, [open, value, levels]);
|
||||
|
||||
const listItems = useMemo(() => {
|
||||
if (activeTab === 'province') return getProvincesForPicker();
|
||||
if (activeTab === 'city') return getCitiesForPicker(draft.province);
|
||||
return getDistrictsForPicker(draft.province, draft.city);
|
||||
}, [activeTab, draft.province, draft.city]);
|
||||
|
||||
const selectedValue =
|
||||
activeTab === 'province' ? draft.province : activeTab === 'city' ? draft.city : draft.district;
|
||||
|
||||
const canConfirm =
|
||||
levels === 2
|
||||
? Boolean(draft.province && draft.city)
|
||||
: Boolean(draft.province && draft.city && draft.district);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
scrollActiveIntoView(listRef.current, selectedValue);
|
||||
}, [open, activeTab, selectedValue, listItems.length]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
function scrollActiveIntoView(container: HTMLDivElement | null, label: string) {
|
||||
if (!container || !label) return;
|
||||
const active = container.querySelector<HTMLElement>(`[data-label="${CSS.escape(label)}"]`);
|
||||
active?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
function selectProvince(province: string) {
|
||||
if (province === REGION_ALL) {
|
||||
setDraft({ province: REGION_ALL, city: REGION_ALL, district: REGION_ALL });
|
||||
setActiveTab('city');
|
||||
return;
|
||||
}
|
||||
const nextCities = getCities(province);
|
||||
const city = nextCities[0] ?? '';
|
||||
if (levels === 2) {
|
||||
setDraft({
|
||||
province,
|
||||
city,
|
||||
district: REGION_ALL,
|
||||
});
|
||||
setActiveTab('city');
|
||||
return;
|
||||
}
|
||||
const nextDistricts = getDistricts(province, city);
|
||||
setDraft({
|
||||
province,
|
||||
city,
|
||||
district: nextDistricts[0] ?? '',
|
||||
});
|
||||
setActiveTab('city');
|
||||
}
|
||||
|
||||
function selectCity(city: string) {
|
||||
if (city === REGION_ALL) {
|
||||
setDraft({ ...draft, city: REGION_ALL, district: REGION_ALL });
|
||||
if (levels === 3) setActiveTab('district');
|
||||
return;
|
||||
}
|
||||
if (levels === 2) {
|
||||
setDraft({
|
||||
...draft,
|
||||
city,
|
||||
district: REGION_ALL,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const nextDistricts = getDistricts(draft.province, city);
|
||||
setDraft({
|
||||
...draft,
|
||||
city,
|
||||
district: nextDistricts[0] ?? '',
|
||||
});
|
||||
setActiveTab('district');
|
||||
}
|
||||
|
||||
function selectDistrict(district: string) {
|
||||
setDraft({ ...draft, district });
|
||||
}
|
||||
|
||||
function onSelectItem(item: string) {
|
||||
if (activeTab === 'province') selectProvince(item);
|
||||
else if (activeTab === 'city') selectCity(item);
|
||||
else selectDistrict(item);
|
||||
}
|
||||
|
||||
function onTabClick(tab: PickerLevel) {
|
||||
if (tab === 'city' && !draft.province) return;
|
||||
if (tab === 'district' && (!draft.province || !draft.city)) return;
|
||||
setActiveTab(tab);
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
if (!canConfirm) return;
|
||||
const next = levels === 2 ? toCityLevelRegion(draft) : normalizeRegionSelection(draft);
|
||||
onConfirm(next);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="region-picker-overlay" role="presentation" onClick={onClose}>
|
||||
<div
|
||||
className="region-picker-sheet"
|
||||
role="dialog"
|
||||
aria-label="选择地区"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="region-picker-toolbar">
|
||||
<div className="region-picker-tabs" role="tablist">
|
||||
{tabs.map((tab) => {
|
||||
const disabled =
|
||||
(tab.key === 'city' && !draft.province) ||
|
||||
(tab.key === 'district' && (!draft.province || !draft.city));
|
||||
return (
|
||||
<button
|
||||
key={tab.key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === tab.key}
|
||||
disabled={disabled}
|
||||
className={`region-picker-tab${activeTab === tab.key ? ' active' : ''}`}
|
||||
onClick={() => onTabClick(tab.key)}
|
||||
>
|
||||
{tabLabel(tab.key, draft, tab.label)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={`region-picker-confirm${canConfirm ? ' ready' : ''}`}
|
||||
disabled={!canConfirm}
|
||||
onClick={handleConfirm}
|
||||
>
|
||||
确定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="region-picker-list" ref={listRef}>
|
||||
{listItems.map((item) => (
|
||||
<button
|
||||
key={item}
|
||||
type="button"
|
||||
data-label={item}
|
||||
className={`region-picker-option${selectedValue === item ? ' selected' : ''}${
|
||||
item === REGION_ALL ? ' region-picker-option--all' : ''
|
||||
}`}
|
||||
onClick={() => onSelectItem(item)}
|
||||
>
|
||||
{item}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
type SubPageHeaderProps = {
|
||||
title: string;
|
||||
onBack: () => void;
|
||||
};
|
||||
|
||||
export default function SubPageHeader({ title, onBack }: SubPageHeaderProps) {
|
||||
return (
|
||||
<header className="sub-page-header" aria-label={title}>
|
||||
<button type="button" className="sub-page-header-back" aria-label="返回" onClick={onBack}>
|
||||
<span className="material-symbols-outlined">arrow_back</span>
|
||||
</button>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
type TabMainHeaderProps = {
|
||||
title: string;
|
||||
extra?: ReactNode;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export default function TabMainHeader({ title, extra, className = '' }: TabMainHeaderProps) {
|
||||
// H5:系统标题已展示;无右侧内容时整栏不渲染,避免顶部留白
|
||||
if (!extra) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<header className={`tab-main-header${className ? ` ${className}` : ''}`} aria-label={title}>
|
||||
{extra ? <div className="tab-main-header-extra">{extra}</div> : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { applyDefaultWechatShare } from '../lib/wechat-share';
|
||||
|
||||
/** 路由变化时刷新微信右上角分享卡片 */
|
||||
export default function WechatShareBootstrap() {
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
void applyDefaultWechatShare().catch(() => {});
|
||||
}, [location.pathname, location.search]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react';
|
||||
import {
|
||||
bootstrapSession,
|
||||
clearAuth,
|
||||
ensureSession,
|
||||
getDeviceKey,
|
||||
request,
|
||||
saveSession,
|
||||
type SessionPayload,
|
||||
type UserProfile,
|
||||
} from '../lib/api';
|
||||
import { touchPromoIfNeeded } from '../lib/promo';
|
||||
|
||||
type UserSessionContextValue = {
|
||||
ready: boolean;
|
||||
profile: UserProfile | null;
|
||||
phoneVerified: boolean;
|
||||
applySession: (session: SessionPayload) => void;
|
||||
refreshProfile: () => Promise<void>;
|
||||
resetSession: () => Promise<void>;
|
||||
};
|
||||
|
||||
const UserSessionContext = createContext<UserSessionContextValue | null>(null);
|
||||
|
||||
export function UserSessionProvider({ children }: { children: ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||
const [phoneVerified, setPhoneVerified] = useState(false);
|
||||
|
||||
const applySession = useCallback((session: SessionPayload) => {
|
||||
saveSession(session);
|
||||
if (session.user) setProfile(session.user);
|
||||
setPhoneVerified(!!session.phoneVerified || !!session.user?.phoneVerified);
|
||||
}, []);
|
||||
|
||||
const refreshProfile = useCallback(async () => {
|
||||
const me = await request<UserProfile>('USER_H5', '/auth/me');
|
||||
setProfile(me);
|
||||
setPhoneVerified(!!me.phoneVerified);
|
||||
}, []);
|
||||
|
||||
const resetSession = useCallback(async () => {
|
||||
clearAuth();
|
||||
const session = await bootstrapSession();
|
||||
applySession(session);
|
||||
}, [applySession]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const session = await ensureSession();
|
||||
if (cancelled) return;
|
||||
applySession(session);
|
||||
if (!session.user) {
|
||||
await refreshProfile();
|
||||
}
|
||||
await touchPromoIfNeeded();
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
try {
|
||||
const session = await bootstrapSession();
|
||||
applySession(session);
|
||||
await refreshProfile();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setReady(true);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [applySession, refreshProfile]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
ready,
|
||||
profile,
|
||||
phoneVerified,
|
||||
applySession,
|
||||
refreshProfile,
|
||||
resetSession,
|
||||
}),
|
||||
[ready, profile, phoneVerified, applySession, refreshProfile, resetSession],
|
||||
);
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="session-boot">
|
||||
<p className="session-boot-text">加载中...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <UserSessionContext.Provider value={value}>{children}</UserSessionContext.Provider>;
|
||||
}
|
||||
|
||||
export function useUserSession() {
|
||||
const ctx = useContext(UserSessionContext);
|
||||
if (!ctx) throw new Error('useUserSession must be used within UserSessionProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function useOptionalUserSession() {
|
||||
return useContext(UserSessionContext);
|
||||
}
|
||||
|
||||
/** @deprecated use profile from useUserSession */
|
||||
export { getDeviceKey };
|
||||
@@ -1,42 +0,0 @@
|
||||
import { NavLink, Outlet } from 'react-router-dom';
|
||||
|
||||
const TABS = [
|
||||
{ to: '/', end: true, icon: 'home', label: '首页', fillActive: false },
|
||||
{ to: '/stores', icon: 'storefront', label: '门店', fillActive: true },
|
||||
{ to: '/benefit', icon: 'card_giftcard', label: '好客权益', fillActive: false },
|
||||
{ to: '/mine', icon: 'person', label: '我的', fillActive: true },
|
||||
] as const;
|
||||
|
||||
export default function TabLayout() {
|
||||
return (
|
||||
<>
|
||||
<Outlet />
|
||||
<nav className="app-tabbar">
|
||||
{TABS.map((tab) => (
|
||||
<NavLink
|
||||
key={tab.to}
|
||||
to={tab.to}
|
||||
end={tab.end}
|
||||
className={({ isActive }) => `app-tabbar-item${isActive ? ' active' : ''}`}
|
||||
>
|
||||
{({ isActive }) => (
|
||||
<>
|
||||
<span
|
||||
className="material-symbols-outlined app-tabbar-icon"
|
||||
style={
|
||||
isActive && tab.fillActive
|
||||
? { fontVariationSettings: "'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24" }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{tab.icon}
|
||||
</span>
|
||||
<span className="app-tabbar-label">{tab.label}</span>
|
||||
</>
|
||||
)}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { createUserTracker, getSessionId } from '@dukang/client-logging';
|
||||
import { apiBase } from './api';
|
||||
|
||||
const tracker = createUserTracker({
|
||||
apiBase,
|
||||
clientApp: 'USER_H5',
|
||||
});
|
||||
|
||||
export { getSessionId };
|
||||
|
||||
export function track(eventName: string, params?: Record<string, unknown>) {
|
||||
tracker.track(eventName, params);
|
||||
}
|
||||
|
||||
export function trackPageView(eventName: string, params?: Record<string, unknown>) {
|
||||
tracker.trackPageView(eventName, params);
|
||||
}
|
||||
|
||||
export function initUserAnalytics() {
|
||||
tracker.trackSessionStart();
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
|
||||
export const BRAND = {
|
||||
red: '#A02D30',
|
||||
yellow: '#FFC107',
|
||||
bg: '#f5f5f5',
|
||||
text: '#333',
|
||||
muted: '#999',
|
||||
};
|
||||
|
||||
export const apiBase = '/api/v1';
|
||||
const CLIENT_APP = 'USER_H5';
|
||||
|
||||
export type UserProfile = {
|
||||
id: string;
|
||||
userNo: string;
|
||||
phone: string | null;
|
||||
phoneVerified: boolean;
|
||||
nickname: string | null;
|
||||
avatarUrl: string | null;
|
||||
hasWechat: boolean;
|
||||
};
|
||||
|
||||
export type SessionPayload = {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
deviceKey?: string;
|
||||
phoneVerified: boolean;
|
||||
user?: UserProfile;
|
||||
};
|
||||
|
||||
const DEVICE_KEY = 'deviceKey';
|
||||
const ACCESS_TOKEN = 'accessToken';
|
||||
const REFRESH_TOKEN = 'refreshToken';
|
||||
|
||||
export function getDeviceKey() {
|
||||
return localStorage.getItem(DEVICE_KEY);
|
||||
}
|
||||
|
||||
export function saveSession(data: SessionPayload) {
|
||||
localStorage.setItem(ACCESS_TOKEN, data.accessToken);
|
||||
localStorage.setItem(REFRESH_TOKEN, data.refreshToken);
|
||||
if (data.deviceKey) localStorage.setItem(DEVICE_KEY, data.deviceKey);
|
||||
}
|
||||
|
||||
export function saveAuth(data: { accessToken: string; refreshToken?: string; deviceKey?: string }) {
|
||||
localStorage.setItem(ACCESS_TOKEN, data.accessToken);
|
||||
if (data.refreshToken) localStorage.setItem(REFRESH_TOKEN, data.refreshToken);
|
||||
if (data.deviceKey) localStorage.setItem(DEVICE_KEY, data.deviceKey);
|
||||
}
|
||||
|
||||
export function clearAuth() {
|
||||
localStorage.removeItem(ACCESS_TOKEN);
|
||||
localStorage.removeItem(REFRESH_TOKEN);
|
||||
}
|
||||
|
||||
export function isLoggedIn() {
|
||||
return !!localStorage.getItem(ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const AUTH_RECOVERY_EXEMPT_PATHS = ['/auth/session/bootstrap', '/auth/token/refresh'];
|
||||
|
||||
async function recoverSession(): Promise<SessionPayload> {
|
||||
const refreshed = await refreshSession();
|
||||
if (refreshed) return refreshed;
|
||||
clearAuth();
|
||||
return bootstrapSession();
|
||||
}
|
||||
|
||||
async function rawRequest<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
token?: string | null,
|
||||
): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': CLIENT_APP,
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
const authToken = token ?? localStorage.getItem(ACCESS_TOKEN);
|
||||
if (authToken) headers.Authorization = `Bearer ${authToken}`;
|
||||
|
||||
const res = await fetch(`${apiBase}${path}`, { ...options, headers });
|
||||
const json = await res.json();
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
}
|
||||
|
||||
async function requestWithAuthRetry<T>(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
retried = false,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await rawRequest<T>(path, options);
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const canRecover =
|
||||
err.status === 401 &&
|
||||
!retried &&
|
||||
!AUTH_RECOVERY_EXEMPT_PATHS.some((p) => path.startsWith(p));
|
||||
if (!canRecover) throw e;
|
||||
await recoverSession();
|
||||
return requestWithAuthRetry<T>(path, options, true);
|
||||
}
|
||||
}
|
||||
|
||||
export async function request<T>(
|
||||
_clientApp: string,
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<T> {
|
||||
if (!isLoggedIn() && !AUTH_RECOVERY_EXEMPT_PATHS.some((p) => path.startsWith(p))) {
|
||||
await bootstrapSession();
|
||||
}
|
||||
return requestWithAuthRetry<T>(path, options);
|
||||
}
|
||||
|
||||
export async function bootstrapSession(): Promise<SessionPayload> {
|
||||
const deviceKey = getDeviceKey();
|
||||
const data = await rawRequest<SessionPayload>(
|
||||
'/auth/session/bootstrap',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(deviceKey ? { deviceKey } : {}),
|
||||
},
|
||||
null,
|
||||
);
|
||||
saveSession(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function refreshSession(): Promise<SessionPayload | null> {
|
||||
const refreshToken = localStorage.getItem(REFRESH_TOKEN);
|
||||
if (!refreshToken) return null;
|
||||
try {
|
||||
const data = await rawRequest<SessionPayload>(
|
||||
'/auth/token/refresh',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
},
|
||||
null,
|
||||
);
|
||||
saveSession(data);
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureSession(): Promise<SessionPayload> {
|
||||
if (isLoggedIn()) {
|
||||
try {
|
||||
const me = await rawRequest<UserProfile>('/auth/me');
|
||||
return {
|
||||
accessToken: localStorage.getItem(ACCESS_TOKEN) ?? '',
|
||||
refreshToken: localStorage.getItem(REFRESH_TOKEN) ?? '',
|
||||
deviceKey: getDeviceKey() ?? undefined,
|
||||
phoneVerified: !!me.phoneVerified,
|
||||
user: me,
|
||||
};
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
if (err.status === 401) {
|
||||
clearAuth();
|
||||
} else {
|
||||
const refreshed = await refreshSession();
|
||||
if (refreshed) return refreshed;
|
||||
}
|
||||
}
|
||||
}
|
||||
return bootstrapSession();
|
||||
}
|
||||
|
||||
export async function bindPhone(phone: string, code: string): Promise<SessionPayload> {
|
||||
if (!isLoggedIn()) {
|
||||
await bootstrapSession();
|
||||
}
|
||||
const data = await requestWithAuthRetry<SessionPayload>('/auth/phone/bind', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, code }),
|
||||
});
|
||||
saveSession(data);
|
||||
return data;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { getWechatLocation } from '@dukang/weixin-sdk';
|
||||
import { weixinSdk } from './weixin';
|
||||
|
||||
export type ClientGpsLocation = {
|
||||
province?: string;
|
||||
city?: string;
|
||||
district?: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
address?: string;
|
||||
};
|
||||
|
||||
/** 尝试获取客户端 GPS(微信优先,其次 H5 Geolocation),失败返回 null 不阻塞下单 */
|
||||
export async function tryGetClientGpsLocation(): Promise<ClientGpsLocation | null> {
|
||||
const loc = await weixinSdk.getLocation();
|
||||
if (!loc) return null;
|
||||
return {
|
||||
latitude: loc.latitude,
|
||||
longitude: loc.longitude,
|
||||
};
|
||||
}
|
||||
|
||||
/** @deprecated 使用 tryGetClientGpsLocation */
|
||||
export { getWechatLocation };
|
||||
@@ -1,43 +0,0 @@
|
||||
import { CUSTOMER_SERVICE_PHONE, CUSTOMER_SERVICE_WECOM_URL } from '@dukang/shared-types';
|
||||
import { fetchClientConfig } from './pay-wechat';
|
||||
import { isWechatEnv } from './weixin';
|
||||
|
||||
let cachedPhone = CUSTOMER_SERVICE_PHONE;
|
||||
|
||||
/** 企微客服链接:优先 Vite env,否则 shared-types 默认 */
|
||||
export function getCustomerServiceWecomUrl(): string {
|
||||
const fromEnv = import.meta.env.VITE_CS_WECOM_URL?.trim();
|
||||
return fromEnv || CUSTOMER_SERVICE_WECOM_URL;
|
||||
}
|
||||
|
||||
export function getCustomerServicePhone(): string {
|
||||
return cachedPhone;
|
||||
}
|
||||
|
||||
/** 从系统设置拉取客服电话(失败则保持默认常量) */
|
||||
export async function loadCustomerServicePhone(): Promise<string> {
|
||||
try {
|
||||
const cfg = await fetchClientConfig();
|
||||
const phone = cfg.customerServicePhone?.trim();
|
||||
if (phone) cachedPhone = phone;
|
||||
} catch {
|
||||
/* keep fallback */
|
||||
}
|
||||
return cachedPhone;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开企业微信客服会话(须在微信内;需用户点击手势)。
|
||||
* @returns true 已跳转;false 非微信环境已提示
|
||||
*/
|
||||
export function openWecomCustomerService(): boolean {
|
||||
if (!isWechatEnv()) {
|
||||
window.alert('请在微信中打开以联系在线客服');
|
||||
return false;
|
||||
}
|
||||
window.location.href = getCustomerServiceWecomUrl();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @deprecated 请用 getCustomerServicePhone(),保留兼容旧引用 */
|
||||
export { CUSTOMER_SERVICE_PHONE };
|
||||
@@ -1,62 +0,0 @@
|
||||
export type CheckoutContext = {
|
||||
productId?: string | null;
|
||||
qty?: string | number | null;
|
||||
addressId?: string | null;
|
||||
cross?: boolean | string | null;
|
||||
select?: boolean | string | null;
|
||||
};
|
||||
|
||||
export function readCheckoutContext(params: URLSearchParams): CheckoutContext {
|
||||
return {
|
||||
productId: params.get('productId'),
|
||||
qty: params.get('qty'),
|
||||
addressId: params.get('addressId'),
|
||||
cross: params.get('cross'),
|
||||
select: params.get('select'),
|
||||
};
|
||||
}
|
||||
|
||||
export function appendCheckoutContext(qs: URLSearchParams, ctx: CheckoutContext) {
|
||||
if (ctx.productId) qs.set('productId', ctx.productId);
|
||||
if (ctx.qty != null && ctx.qty !== '') qs.set('qty', String(ctx.qty));
|
||||
if (ctx.addressId) qs.set('addressId', ctx.addressId);
|
||||
if (ctx.cross === true || ctx.cross === '1') qs.set('cross', '1');
|
||||
if (ctx.select === true || ctx.select === '1') qs.set('select', '1');
|
||||
}
|
||||
|
||||
export function buildOrderConfirmUrl(search: CheckoutContext) {
|
||||
const qs = new URLSearchParams();
|
||||
if (search.productId) qs.set('productId', search.productId);
|
||||
if (search.qty != null && search.qty !== '') qs.set('qty', String(search.qty));
|
||||
if (search.addressId) qs.set('addressId', search.addressId);
|
||||
if (search.cross === true || search.cross === '1') qs.set('cross', '1');
|
||||
const query = qs.toString();
|
||||
return query ? `/order/confirm?${query}` : '/order/confirm';
|
||||
}
|
||||
|
||||
export function buildAddressListUrl(ctx: CheckoutContext = {}) {
|
||||
const qs = new URLSearchParams();
|
||||
appendCheckoutContext(qs, ctx);
|
||||
const query = qs.toString();
|
||||
return query ? `/addresses?${query}` : '/addresses';
|
||||
}
|
||||
|
||||
export function buildAddressEditUrl(id: string | 'new', ctx: CheckoutContext = {}) {
|
||||
const path = id === 'new' ? '/addresses/new' : `/addresses/${id}/edit`;
|
||||
const qs = new URLSearchParams();
|
||||
appendCheckoutContext(qs, ctx);
|
||||
const query = qs.toString();
|
||||
return query ? `${path}?${query}` : path;
|
||||
}
|
||||
|
||||
export function buildProductDetailUrl(productId?: string | null) {
|
||||
return productId ? `/product/${productId}` : '/';
|
||||
}
|
||||
|
||||
export function buildOrderAddressSelectUrl(orderId: string) {
|
||||
return `/addresses?orderId=${orderId}&select=1`;
|
||||
}
|
||||
|
||||
export function hasCheckoutContext(ctx: CheckoutContext) {
|
||||
return Boolean(ctx.productId || ctx.select === true || ctx.select === '1');
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
/** Stitch 确认订单页商品缩略图 */
|
||||
export const STITCH_ORDER_PRODUCT_IMAGE =
|
||||
'https://lh3.googleusercontent.com/aida-public/AB6AXuAfqy5X1jKiMBB-L5amwR3xfLYbFBc_qsPbB9mdQZxWlV3rrOARPFVhLRDlW7r8Ig03O6c_ZJKLcVEsgYCblwKg8FZ4-EWwcc5bMNc3UsmBycu3bZ5E6S_aH9UBv0_nEP0sMD8rJsC_rMYBiGDMvRbd52taX-Ir_sfRiVvQu7ImFV-YvU54iXE2x51naVuR8qxwmK7YKitPClg0Pysga859a2-yiJ_ID0QR5xM2o84QbMwNyOEoDDTKSDNqG6J9jfeTsiIYb5vdVmc';
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { ClientRuntimeConfig, WechatLoginResult } from '@dukang/shared-types';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { toAppPath } from '@dukang/weixin-sdk';
|
||||
import { isWechatEnv, weixinSdk } from './weixin';
|
||||
import { request, saveSession, type UserProfile } from './api';
|
||||
|
||||
const WECHAT_AUTH_REQUIRED = 'WECHAT_AUTH_REQUIRED';
|
||||
|
||||
export function isWechatAuthRequiredError(err: unknown): boolean {
|
||||
return err instanceof Error && err.message === WECHAT_AUTH_REQUIRED;
|
||||
}
|
||||
|
||||
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
||||
return request<ClientRuntimeConfig>('USER_H5', '/common/client-config');
|
||||
}
|
||||
|
||||
export async function fetchUserProfile(): Promise<UserProfile> {
|
||||
return request<UserProfile>('USER_H5', '/auth/me');
|
||||
}
|
||||
|
||||
/** 真实微信支付且未绑定微信时需要授权 */
|
||||
export function needsWechatAuthForPay(
|
||||
config: ClientRuntimeConfig,
|
||||
profile: UserProfile | null,
|
||||
): boolean {
|
||||
if (!isWxAuthorizeEnabled(config)) return false;
|
||||
return !config.mockPay && config.wechatPayEnabled && isWechatEnv() && !profile?.hasWechat;
|
||||
}
|
||||
|
||||
export function saveWechatLoginResult(result: WechatLoginResult): boolean {
|
||||
if (!result.accessToken) return false;
|
||||
saveSession({
|
||||
accessToken: result.accessToken,
|
||||
refreshToken: result.refreshToken ?? '',
|
||||
deviceKey: result.deviceKey,
|
||||
phoneVerified: !!result.phoneVerified,
|
||||
user: result.user as never,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function authorizeWechatForPay(): Promise<WechatLoginResult | void> {
|
||||
const config = await fetchClientConfig();
|
||||
if (!isWxAuthorizeEnabled(config)) return;
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开以完成授权');
|
||||
}
|
||||
return weixinSdk.login();
|
||||
}
|
||||
|
||||
export function buildLoginReturnUrl(pathname: string, search: string) {
|
||||
return `${toAppPath('/login')}?return=${encodeURIComponent(`${pathname}${search}`)}`;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
const MOBILE_PHONE_RE = /^1[3-9]\d{9}$/;
|
||||
|
||||
export function normalizePhoneInput(value: string): string {
|
||||
return value.replace(/\D/g, '').slice(0, 11);
|
||||
}
|
||||
|
||||
export function validateMobilePhone(phone: string): { ok: boolean; message?: string } {
|
||||
const trimmed = phone.trim();
|
||||
if (!trimmed) {
|
||||
return { ok: false, message: '请输入手机号码' };
|
||||
}
|
||||
if (trimmed.length !== 11) {
|
||||
return { ok: false, message: '手机号码须为 11 位' };
|
||||
}
|
||||
if (!MOBILE_PHONE_RE.test(trimmed)) {
|
||||
return { ok: false, message: '请输入正确的手机号码' };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/** 商品无图时的占位图 */
|
||||
export const PRODUCT_IMAGE_FALLBACK = '/images/1.png';
|
||||
|
||||
export type ProductImageSource = {
|
||||
mainImageUrl?: string | null;
|
||||
carouselUrls?: string[] | null;
|
||||
detailImageUrls?: string[] | null;
|
||||
};
|
||||
|
||||
function uniqueUrls(urls: Array<string | null | undefined>) {
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
for (const url of urls) {
|
||||
if (!url || seen.has(url)) continue;
|
||||
seen.add(url);
|
||||
result.push(url);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 首页/列表轮播图:优先 CAROUSEL,否则封面 */
|
||||
export function getProductImages(source?: ProductImageSource | null): string[] {
|
||||
const carousel = uniqueUrls(source?.carouselUrls ?? []);
|
||||
if (carousel.length > 0) return carousel;
|
||||
|
||||
const main = source?.mainImageUrl;
|
||||
if (main) return [main];
|
||||
|
||||
return [PRODUCT_IMAGE_FALLBACK];
|
||||
}
|
||||
|
||||
/** 单张主图:封面优先 */
|
||||
export function getProductMainImage(source?: ProductImageSource | null): string {
|
||||
return source?.mainImageUrl ?? source?.carouselUrls?.[0] ?? PRODUCT_IMAGE_FALLBACK;
|
||||
}
|
||||
|
||||
/** 详情页顶部轮播 */
|
||||
export function getProductCarouselImages(source?: ProductImageSource | null): string[] {
|
||||
const carousel = uniqueUrls(source?.carouselUrls ?? []);
|
||||
if (carousel.length > 0) return carousel;
|
||||
return getProductImages(source);
|
||||
}
|
||||
|
||||
/** 详情页图文长图 */
|
||||
export function getProductDetailImages(source?: ProductImageSource | null): string[] {
|
||||
return uniqueUrls(source?.detailImageUrls ?? []);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { apiBase } from './api';
|
||||
|
||||
export const PROMO_STORAGE_KEY = 'dukang_promo_code';
|
||||
export const PROMO_PID_STORAGE_KEY = 'dukang_promo_pid';
|
||||
|
||||
function readPromoFromSearch(search: string): { code: string | null; pid: string | null } {
|
||||
const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
|
||||
const code = params.get('promo')?.trim();
|
||||
const pid = params.get('pid')?.trim();
|
||||
return {
|
||||
code: code ? code.toUpperCase() : null,
|
||||
pid: pid || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 解析 URL 中的 ?promo= / ?pid= 并写入 sessionStorage */
|
||||
export function capturePromoFromUrl(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
let parsed = readPromoFromSearch(window.location.search);
|
||||
if (!parsed.code && !parsed.pid && window.location.hash.includes('?')) {
|
||||
const hashQuery = window.location.hash.slice(window.location.hash.indexOf('?'));
|
||||
parsed = readPromoFromSearch(hashQuery);
|
||||
}
|
||||
if (parsed.code) {
|
||||
sessionStorage.setItem(PROMO_STORAGE_KEY, parsed.code);
|
||||
}
|
||||
if (parsed.pid) {
|
||||
sessionStorage.setItem(PROMO_PID_STORAGE_KEY, parsed.pid);
|
||||
}
|
||||
return parsed.code ?? sessionStorage.getItem(PROMO_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function getStoredPromoCode(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return sessionStorage.getItem(PROMO_STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function getStoredPromoPid(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return sessionStorage.getItem(PROMO_PID_STORAGE_KEY);
|
||||
}
|
||||
|
||||
/** 调用 /promo/touch 完成扫码归因(OptionalJwt:未登录也累加 scan_count) */
|
||||
export async function touchPromoIfNeeded(): Promise<void> {
|
||||
const promoCode = getStoredPromoCode();
|
||||
const qrcodeId = getStoredPromoPid();
|
||||
if (!promoCode && !qrcodeId) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': 'USER_H5',
|
||||
};
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
try {
|
||||
const res = await fetch(`${apiBase}/promo/touch`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
...(promoCode ? { promoCode } : {}),
|
||||
...(qrcodeId ? { qrcodeId } : {}),
|
||||
}),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (json.code !== 0) return;
|
||||
} catch {
|
||||
/* 静默失败,不阻断用户流程 */
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import { regionData } from 'element-china-area-data';
|
||||
|
||||
export type RegionTree = Record<string, Record<string, string[]>>;
|
||||
|
||||
/** 由国家标准省市区数据构建三级树 */
|
||||
function buildRegionTree(): RegionTree {
|
||||
const tree: RegionTree = {};
|
||||
for (const province of regionData) {
|
||||
const cities: Record<string, string[]> = {};
|
||||
for (const city of province.children ?? []) {
|
||||
cities[city.label] = (city.children ?? []).map((district) => district.label);
|
||||
}
|
||||
tree[province.label] = cities;
|
||||
}
|
||||
return tree;
|
||||
}
|
||||
|
||||
export const REGION_TREE: RegionTree = buildRegionTree();
|
||||
|
||||
export const PROVINCES = Object.keys(REGION_TREE);
|
||||
|
||||
/** 三级选择「全市」选项(省/市/区列表首项) */
|
||||
export const REGION_ALL = '全市';
|
||||
|
||||
export function getCities(province: string): string[] {
|
||||
if (province === REGION_ALL) return [];
|
||||
return Object.keys(REGION_TREE[province] ?? {});
|
||||
}
|
||||
|
||||
export function getDistricts(province: string, city: string): string[] {
|
||||
if (province === REGION_ALL || city === REGION_ALL) return [];
|
||||
return REGION_TREE[province]?.[city] ?? [];
|
||||
}
|
||||
|
||||
/** 省份列表(含全市) */
|
||||
export function getProvincesForPicker(): string[] {
|
||||
return [...PROVINCES];
|
||||
}
|
||||
|
||||
/** 城市列表(含全市) */
|
||||
export function getCitiesForPicker(province: string): string[] {
|
||||
if (province === REGION_ALL) return [REGION_ALL];
|
||||
return [...getCities(province)];
|
||||
}
|
||||
|
||||
/** 区县列表(含全市) */
|
||||
export function getDistrictsForPicker(province: string, city: string): string[] {
|
||||
if (province === REGION_ALL || city === REGION_ALL) return [REGION_ALL];
|
||||
return [REGION_ALL, ...getDistricts(province, city)];
|
||||
}
|
||||
|
||||
export function formatRegion(province: string, city: string, district: string): string {
|
||||
if (!province) return '';
|
||||
if (province === REGION_ALL) return REGION_ALL;
|
||||
if (city === REGION_ALL) return `${province} ${REGION_ALL}`;
|
||||
if (district === REGION_ALL) return `${province} ${city} ${REGION_ALL}`;
|
||||
if (!city || !district) return '';
|
||||
return `${province} ${city} ${district}`;
|
||||
}
|
||||
|
||||
/** 仅展示省、市两级(门店列表等场景) */
|
||||
export function formatRegionCity(province: string, city: string): string {
|
||||
if (!province) return '';
|
||||
if (province === REGION_ALL) return REGION_ALL;
|
||||
if (city === REGION_ALL) return `${province} ${REGION_ALL}`;
|
||||
if (!city) return province;
|
||||
return `${province} ${city}`;
|
||||
}
|
||||
|
||||
/** 门店筛选:固定为市级,不按区县过滤 */
|
||||
export function toCityLevelRegion(selection: RegionSelection): RegionSelection {
|
||||
const normalized = normalizeRegionSelection(selection);
|
||||
return {
|
||||
province: normalized.province,
|
||||
city: normalized.city,
|
||||
district: REGION_ALL,
|
||||
};
|
||||
}
|
||||
|
||||
export type RegionSelection = {
|
||||
province: string;
|
||||
city: string;
|
||||
district: string;
|
||||
};
|
||||
|
||||
export const DEFAULT_REGION: RegionSelection = {
|
||||
province: '河南省',
|
||||
city: '郑州市',
|
||||
district: '金水区',
|
||||
};
|
||||
|
||||
export const FALLBACK_CITY_REGION: RegionSelection = {
|
||||
province: '河南省',
|
||||
city: '郑州市',
|
||||
district: REGION_ALL,
|
||||
};
|
||||
|
||||
export function regionFromGeo(province: string, city: string, district?: string): RegionSelection {
|
||||
const cityName = city.endsWith('市') ? city : `${city}市`;
|
||||
const provinceInTree = PROVINCES.includes(province) ? province : DEFAULT_REGION.province;
|
||||
const cities = getCities(provinceInTree);
|
||||
const matchedCity = cities.includes(cityName)
|
||||
? cityName
|
||||
: cities.find((c) => c.replace(/市$/, '') === city.replace(/市$/, '')) ?? cityName;
|
||||
const districts = getDistricts(provinceInTree, matchedCity);
|
||||
const districtName =
|
||||
district && districts.includes(district)
|
||||
? district
|
||||
: REGION_ALL;
|
||||
return normalizeRegionSelection({
|
||||
province: provinceInTree,
|
||||
city: cities.includes(matchedCity) ? matchedCity : matchedCity,
|
||||
district: districtName,
|
||||
});
|
||||
}
|
||||
|
||||
/** 校验已选地区是否仍存在于数据源中 */
|
||||
export function normalizeRegionSelection(selection: RegionSelection): RegionSelection {
|
||||
if (selection.province === REGION_ALL) {
|
||||
return { province: REGION_ALL, city: REGION_ALL, district: REGION_ALL };
|
||||
}
|
||||
|
||||
const province = PROVINCES.includes(selection.province)
|
||||
? selection.province
|
||||
: DEFAULT_REGION.province;
|
||||
|
||||
if (selection.city === REGION_ALL) {
|
||||
return { province, city: REGION_ALL, district: REGION_ALL };
|
||||
}
|
||||
|
||||
const cities = getCities(province);
|
||||
const city = cities.includes(selection.city) ? selection.city : (cities[0] ?? DEFAULT_REGION.city);
|
||||
|
||||
if (selection.district === REGION_ALL) {
|
||||
return { province, city, district: REGION_ALL };
|
||||
}
|
||||
|
||||
const districts = getDistricts(province, city);
|
||||
const district = districts.includes(selection.district)
|
||||
? selection.district
|
||||
: (districts[0] ?? DEFAULT_REGION.district);
|
||||
|
||||
return { province, city, district };
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/** Stitch user/22 门店详情页 — 图集与地图占位 */
|
||||
export const STITCH_STORE_GALLERY = [
|
||||
'https://lh3.googleusercontent.com/aida-public/AB6AXuDqN0DeYRsWNcXyfSRec8k2fhjJsqdji3-7zrtegkiEs5lwt3Sx4l79Uzmfys2pnl_gUY_m3Dpy5cAM8HW7JcR8qPtfO2G8YNcZ3x0DGSN1DUPJPq4emVhmIuwmaLEQ944UT9hjpNQsjdqieKV8R-X-2YvSOrsEa74kyfI5UNgRQaGdinhLw6co29ji3F9BRgfgWCQ1KqjotRBC4r9lzWBdeue-xryXvN8jEp_7hjwrBNOOZoIDPnKkpQQwLLpaa7Di6kfEfwzamCg',
|
||||
'https://lh3.googleusercontent.com/aida-public/AB6AXuAW3oxOc6XpywVJmpwYxIPBlP32ftPIOUB8JbYcqOAcLg1gbzKIgbDgBaPVUyH0gjdoWa7Hi0u1-NBYBwc5Jd3YpqufVWIou_ySFB2oLXA6T0u7DgUWKhtxbMnqMue-oasf8GlEy_e7-Rh41ZxVFkc30tQVAYz-Psm3CNgfRFqXoHDXCZAZz5ggOFOB2dScURBVN9qp_Ribo4DuE4LARgf19R8eKZR8mbDQdHesLaVl0icifdcQEb75QM6-VqCR3ch9BNKzLJ5hKMM',
|
||||
'https://lh3.googleusercontent.com/aida-public/AB6AXuDuv4URDejJ5j26kuBPG2fqmOmI90qQomZki-aHr3MmdF47Pq5HM7tiH68E77rrF0XjeaZjkQ0e39j5gY1-N_981-eguGZn8VIRZI0n6t-f8QVIhAyjL8kg-5ZD2yRsfgw5mnOYYPMyNUI54efLiU4M6mni6nJvTAXMvX0oBMXtTItj5U66d9BIvie7VfHoVYMelEW9ppZsSRzA7ZoIu6aRp_72OwAIcTFuiI2zccaAmfTk7dChjjHIHZ85B8dDc2G8Tym34SuJAZc',
|
||||
] as const;
|
||||
|
||||
export const STITCH_STORE_MAP =
|
||||
'https://lh3.googleusercontent.com/aida-public/AB6AXuByauC4oncButUsGa_t2ntIVz-iPk9zVUnYA6_P_URyFYzrWALFa2TKfdpEyrGs61N_sEjRYksO_HeKCZGJQXfRhXqf1iXrk8JPIfzDwb33bDacTr2J0HM-cSnNjcM1c5l6r_yuzsE0zuLBZpuAWVPwkOJUkdfk6xxNpABh-OQ0B6736YmxFQM-WJ5h0eLHpRB7RuyTFr5c_TwTysKyY6QVDZ-oJrx9Vc3FQE7Pc64o3bzP6qW3GEqdqm4WVIAMKiNKqUcXvkN8E48';
|
||||
|
||||
export function getStoreGalleryImages(coverUrl?: string | null, media?: Array<{ url: string }>) {
|
||||
const fromMedia = (media || []).map((m) => m.url).filter(Boolean);
|
||||
if (fromMedia.length > 0) return fromMedia;
|
||||
if (coverUrl) return [coverUrl, ...STITCH_STORE_GALLERY.slice(1)];
|
||||
return [...STITCH_STORE_GALLERY];
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import { apiBase } from './api';
|
||||
import {
|
||||
compressImageFileIfNeeded,
|
||||
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
formatOssMaxSizeMb,
|
||||
} from '@dukang/shared-ui/compressImage';
|
||||
|
||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||
|
||||
export type UploadFileResult = {
|
||||
url: string;
|
||||
ossKey: string;
|
||||
bucket: string;
|
||||
mock: boolean;
|
||||
};
|
||||
|
||||
/** 经 API 服务端转存 OSS */
|
||||
export async function uploadFileToOss(
|
||||
file: File,
|
||||
options: { bizType: string; mediaType?: OssMediaType },
|
||||
): Promise<UploadFileResult> {
|
||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||
let prepared = file;
|
||||
if (mediaType === 'IMAGE') {
|
||||
prepared = await compressImageFileIfNeeded(file);
|
||||
if (prepared.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||
}
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', prepared);
|
||||
formData.append('bizType', options.bizType);
|
||||
formData.append('mediaType', mediaType);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'X-Client-App': 'USER_H5',
|
||||
};
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${apiBase}/common/resources/upload`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (json.code !== 0) throw new Error(json.message || '上传失败');
|
||||
return json.data as UploadFileResult;
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { SmsScene } from '@dukang/shared-types';
|
||||
import { request } from './api';
|
||||
import { fetchClientConfig } from './pay-wechat';
|
||||
import { validateMobilePhone } from './phone';
|
||||
|
||||
export function useSmsCode() {
|
||||
const [codeCooldown, setCodeCooldown] = useState(0);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [sentHint, setSentHint] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [mockSms, setMockSms] = useState(true);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientConfig()
|
||||
.then((cfg) => setMockSms(cfg.mockSms))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startCooldown = useCallback(() => {
|
||||
setCodeCooldown(60);
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
timerRef.current = setInterval(() => {
|
||||
setCodeCooldown((c) => {
|
||||
if (c <= 1) {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
return 0;
|
||||
}
|
||||
return c - 1;
|
||||
});
|
||||
}, 1000);
|
||||
}, []);
|
||||
|
||||
const sendCode = useCallback(
|
||||
async (phone: string, scene: SmsScene) => {
|
||||
const phoneCheck = validateMobilePhone(phone);
|
||||
if (!phoneCheck.ok) {
|
||||
setError(phoneCheck.message ?? '请输入正确的手机号码');
|
||||
return false;
|
||||
}
|
||||
setSending(true);
|
||||
setError('');
|
||||
setSentHint('');
|
||||
try {
|
||||
await request('USER_H5', '/auth/sms/send', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, scene }),
|
||||
});
|
||||
setSentHint(mockSms ? '验证码已发送(开发模式)' : '验证码已发送,请注意查收');
|
||||
startCooldown();
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '发送失败');
|
||||
return false;
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
},
|
||||
[mockSms, startCooldown],
|
||||
);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setError('');
|
||||
setSentHint('');
|
||||
}, []);
|
||||
|
||||
return {
|
||||
sendCode,
|
||||
sending,
|
||||
codeCooldown,
|
||||
sentHint,
|
||||
error,
|
||||
setError,
|
||||
clearMessages,
|
||||
mockSms,
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { trackPageView } from './analytics';
|
||||
|
||||
export function usePageView(eventName: string, params?: Record<string, unknown>) {
|
||||
const fired = useRef(false);
|
||||
useEffect(() => {
|
||||
if (fired.current) return;
|
||||
fired.current = true;
|
||||
trackPageView(eventName, params);
|
||||
}, [eventName, params]);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { WechatLoginResult } from '@dukang/shared-types';
|
||||
import { isWxAuthorizeEnabled } from '@dukang/shared-types';
|
||||
import { isWechatEnv, weixinSdk } from './weixin';
|
||||
import {
|
||||
authorizeWechatForPay,
|
||||
fetchClientConfig,
|
||||
fetchUserProfile,
|
||||
needsWechatAuthForPay,
|
||||
saveWechatLoginResult,
|
||||
} from './pay-wechat';
|
||||
|
||||
export type WechatAuthEnsureResult =
|
||||
| { ok: true }
|
||||
| { ok: false; redirecting: true }
|
||||
| { ok: false; needBindPhone: true; wxSessionKey: string };
|
||||
|
||||
export async function checkNeedsWechatAuth(): Promise<boolean> {
|
||||
const [config, profile] = await Promise.all([fetchClientConfig(), fetchUserProfile()]);
|
||||
return needsWechatAuthForPay(config, profile);
|
||||
}
|
||||
|
||||
/** 真实微信支付前确保已绑定微信;OAuth 跳转时返回 redirecting */
|
||||
export async function ensureWechatAuthForPay(): Promise<WechatAuthEnsureResult> {
|
||||
if (!isWechatEnv()) return { ok: true };
|
||||
if (!(await checkNeedsWechatAuth())) return { ok: true };
|
||||
|
||||
const result = await authorizeWechatForPay();
|
||||
if (!result) return { ok: false, redirecting: true };
|
||||
|
||||
if (result.needBindPhone && result.wxSessionKey) {
|
||||
return { ok: false, needBindPhone: true, wxSessionKey: result.wxSessionKey };
|
||||
}
|
||||
|
||||
if (saveWechatLoginResult(result)) {
|
||||
return { ok: true };
|
||||
}
|
||||
return { ok: false, redirecting: true };
|
||||
}
|
||||
|
||||
export async function handleWechatAuthCallback(): Promise<WechatLoginResult | null> {
|
||||
if (!isWechatEnv()) return null;
|
||||
const config = await fetchClientConfig();
|
||||
if (!isWxAuthorizeEnabled(config)) return null;
|
||||
return weixinSdk.handleOAuthCallback();
|
||||
}
|
||||
|
||||
export async function loginWithWechatSdk(): Promise<WechatLoginResult | void> {
|
||||
const config = await fetchClientConfig();
|
||||
if (!isWxAuthorizeEnabled(config)) return;
|
||||
if (!isWechatEnv()) {
|
||||
throw new Error('请在微信内打开以使用微信一键授权');
|
||||
}
|
||||
return weixinSdk.login();
|
||||
}
|
||||
|
||||
export function applyWechatLoginResult(result: WechatLoginResult): boolean {
|
||||
return saveWechatLoginResult(result);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import { getWechatLocationDetailed } from '@dukang/weixin-sdk';
|
||||
import { apiBase } from './api';
|
||||
import { weixinSdk } from './weixin';
|
||||
import { regionFromGeo, type RegionSelection } from './region-data';
|
||||
|
||||
export const GPS_CITY_STORAGE_KEY = 'dukang_gps_city';
|
||||
export const CITY_STORAGE_KEY = 'dukang_selected_city';
|
||||
export const FALLBACK_CITY_CODE = '410100';
|
||||
|
||||
export type ResolvedUserCity = {
|
||||
province: string;
|
||||
city: string;
|
||||
district: string;
|
||||
cityCode?: string;
|
||||
cityName?: string;
|
||||
openCity: boolean;
|
||||
region: RegionSelection;
|
||||
displayCity: string;
|
||||
};
|
||||
|
||||
type GpsCityCache = ResolvedUserCity & { timestamp: number };
|
||||
|
||||
function readCache(): GpsCityCache | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(GPS_CITY_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as GpsCityCache;
|
||||
if (Date.now() - parsed.timestamp > 30 * 60 * 1000) return null;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(data: ResolvedUserCity) {
|
||||
sessionStorage.setItem(
|
||||
GPS_CITY_STORAGE_KEY,
|
||||
JSON.stringify({ ...data, timestamp: Date.now() } satisfies GpsCityCache),
|
||||
);
|
||||
}
|
||||
|
||||
async function reportLocationToServer(payload: {
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
sdk: 'jssdk' | 'geolocation';
|
||||
status: 'success' | 'fail';
|
||||
errMsg?: string;
|
||||
}) {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Client-App': 'USER_H5',
|
||||
};
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${apiBase}/common/wechat/location`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (json.code !== 0) {
|
||||
throw new Error(json.message || '定位上报失败');
|
||||
}
|
||||
return json.data as {
|
||||
province?: string;
|
||||
city?: string;
|
||||
district?: string;
|
||||
cityCode?: string;
|
||||
cityName?: string;
|
||||
openCity?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
function toResolved(data: {
|
||||
province?: string;
|
||||
city?: string;
|
||||
district?: string;
|
||||
cityCode?: string;
|
||||
cityName?: string;
|
||||
openCity?: boolean;
|
||||
}): ResolvedUserCity | null {
|
||||
if (!data.province || !data.city) return null;
|
||||
const region = regionFromGeo(data.province, data.city, data.district);
|
||||
const displayCity = data.cityName ?? (data.city.endsWith('市') ? data.city : `${data.city}市`);
|
||||
return {
|
||||
province: data.province,
|
||||
city: data.city,
|
||||
district: data.district ?? '',
|
||||
cityCode: data.cityCode,
|
||||
cityName: data.cityName,
|
||||
openCity: !!data.openCity,
|
||||
region,
|
||||
displayCity,
|
||||
};
|
||||
}
|
||||
|
||||
/** 获取并解析用户当前城市(微信 JSSDK 优先),失败返回 null */
|
||||
export async function resolveUserCity(force = false): Promise<ResolvedUserCity | null> {
|
||||
if (!force) {
|
||||
const cached = readCache();
|
||||
if (cached) return cached;
|
||||
}
|
||||
|
||||
const outcome = await getWechatLocationDetailed({
|
||||
apiBase,
|
||||
clientApp: 'USER_H5',
|
||||
getAccessToken: () => localStorage.getItem('accessToken'),
|
||||
});
|
||||
|
||||
if (!outcome.location) {
|
||||
await reportLocationToServer({
|
||||
sdk: outcome.sdk,
|
||||
status: 'fail',
|
||||
errMsg: outcome.errMsg,
|
||||
}).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await reportLocationToServer({
|
||||
latitude: outcome.location.latitude,
|
||||
longitude: outcome.location.longitude,
|
||||
sdk: outcome.sdk,
|
||||
status: 'success',
|
||||
});
|
||||
const resolved = toResolved(data);
|
||||
if (resolved) {
|
||||
writeCache(resolved);
|
||||
if (resolved.openCity && resolved.cityCode) {
|
||||
localStorage.setItem(CITY_STORAGE_KEY, resolved.cityCode);
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function syncCityCodeFromGps(resolved: ResolvedUserCity) {
|
||||
if (resolved.openCity && resolved.cityCode) {
|
||||
localStorage.setItem(CITY_STORAGE_KEY, resolved.cityCode);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import type { WechatShareData } from '@dukang/weixin-sdk';
|
||||
import { getWechatShareLink, toAppPath } from '@dukang/weixin-sdk';
|
||||
import { isWechatEnv, weixinSdk } from './weixin';
|
||||
|
||||
export const DEFAULT_SHARE_TITLE = '你吃饭,杜康买单';
|
||||
export const DEFAULT_SHARE_DESC = '杜康好客 · 买酒享权益,全城门店可用';
|
||||
export const WECHAT_SHARE_HINT = '请点击右上角 ··· 分享给好友';
|
||||
|
||||
export function getDefaultShareImageUrl(): string {
|
||||
if (typeof window === 'undefined') return toAppPath('/logo.png');
|
||||
return new URL(toAppPath('/logo.png'), window.location.origin).href;
|
||||
}
|
||||
|
||||
export function buildDefaultShareData(
|
||||
overrides?: Partial<WechatShareData>,
|
||||
): WechatShareData {
|
||||
return {
|
||||
title: overrides?.title ?? DEFAULT_SHARE_TITLE,
|
||||
desc: overrides?.desc ?? DEFAULT_SHARE_DESC,
|
||||
link: overrides?.link ?? getWechatShareLink(),
|
||||
imgUrl: overrides?.imgUrl ?? getDefaultShareImageUrl(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function applyDefaultWechatShare(
|
||||
overrides?: Partial<WechatShareData>,
|
||||
): Promise<void> {
|
||||
if (!isWechatEnv()) return;
|
||||
await weixinSdk.setShare(buildDefaultShareData(overrides));
|
||||
}
|
||||
|
||||
export function handleShareButtonClick(onHint: (message: string) => void): void {
|
||||
const showHint = (message: string) => {
|
||||
onHint(message);
|
||||
if (message) {
|
||||
window.setTimeout(() => onHint(''), 2500);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isWechatEnv()) {
|
||||
showHint('请在微信内打开后分享');
|
||||
return;
|
||||
}
|
||||
void applyDefaultWechatShare()
|
||||
.then(() => showHint(WECHAT_SHARE_HINT))
|
||||
.catch(() => showHint('分享配置失败,请刷新页面后重试'));
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createWeixinSdk, isWechatEnv } from '@dukang/weixin-sdk';
|
||||
|
||||
const CLIENT_APP = 'USER_H5';
|
||||
|
||||
export const weixinSdk = createWeixinSdk({
|
||||
apiBase: '/api/v1',
|
||||
clientApp: CLIENT_APP,
|
||||
getAccessToken: () => localStorage.getItem('accessToken'),
|
||||
});
|
||||
|
||||
export { isWechatEnv };
|
||||
@@ -1,21 +0,0 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { getRouterBasename } from '@dukang/weixin-sdk';
|
||||
import { installClientErrorReporting } from '@dukang/client-logging';
|
||||
import App from './App';
|
||||
import { initUserAnalytics } from './lib/analytics';
|
||||
import { apiBase } from './lib/api';
|
||||
import './styles.css';
|
||||
import './styles/legal.css';
|
||||
|
||||
installClientErrorReporting({ apiBase, clientApp: 'USER_H5' });
|
||||
initUserAnalytics();
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter basename={getRouterBasename()}>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -1,237 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
import SubPageHeader from '../components/SubPageHeader';
|
||||
import RegionPicker from '../components/RegionPicker';
|
||||
import { request } from '../lib/api';
|
||||
import { buildAddressListUrl, readCheckoutContext } from '../lib/navigation';
|
||||
import { DEFAULT_REGION, formatRegion } from '../lib/region-data';
|
||||
import { normalizePhoneInput, validateMobilePhone } from '../lib/phone';
|
||||
import { usePageView } from '../lib/usePageView';
|
||||
|
||||
type AddressForm = {
|
||||
receiverName: string;
|
||||
phone: string;
|
||||
province: string;
|
||||
city: string;
|
||||
district: string;
|
||||
detail: string;
|
||||
isDefault: boolean;
|
||||
};
|
||||
|
||||
export default function AddressEditPage() {
|
||||
const { id } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const isEdit = Boolean(id);
|
||||
usePageView('address_edit', { mode: isEdit ? 'edit' : 'create' });
|
||||
const navigate = useNavigate();
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<AddressForm>({
|
||||
receiverName: '',
|
||||
phone: '',
|
||||
province: DEFAULT_REGION.province,
|
||||
city: params.get('city') || DEFAULT_REGION.city,
|
||||
district: DEFAULT_REGION.district,
|
||||
detail: '',
|
||||
isDefault: true,
|
||||
});
|
||||
|
||||
const checkoutCtx = readCheckoutContext(params);
|
||||
|
||||
function goBackToList() {
|
||||
navigate(buildAddressListUrl(checkoutCtx));
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
request<Array<Record<string, unknown>>>('USER_H5', '/user/addresses').then((list) => {
|
||||
const found = list.find((a) => String(a.id) === id);
|
||||
if (found) {
|
||||
setForm({
|
||||
receiverName: String(found.receiverName),
|
||||
phone: String(found.phone),
|
||||
province: String(found.province),
|
||||
city: String(found.city),
|
||||
district: String(found.district),
|
||||
detail: String(found.detail),
|
||||
isDefault: found.isDefault === 1,
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [id]);
|
||||
|
||||
const regionText = formatRegion(form.province, form.city, form.district);
|
||||
|
||||
function validateForm(): string | null {
|
||||
if (!form.receiverName.trim()) return '请输入收货人姓名';
|
||||
const phoneCheck = validateMobilePhone(form.phone);
|
||||
if (!phoneCheck.ok) return phoneCheck.message ?? '请输入正确的手机号码';
|
||||
if (!form.province || !form.city || !form.district) return '请选择所在地区';
|
||||
if (!form.detail.trim()) return '请输入详细地址';
|
||||
return null;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const validationError = validateForm();
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
if (isEdit && id) {
|
||||
await request('USER_H5', `/user/addresses/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
} else {
|
||||
await request('USER_H5', '/user/addresses', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
}
|
||||
navigate(buildAddressListUrl(checkoutCtx));
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="address-edit-page">
|
||||
<SubPageHeader
|
||||
title={isEdit ? '编辑收货地址' : '添加收货地址'}
|
||||
onBack={goBackToList}
|
||||
/>
|
||||
|
||||
<main className="address-edit-main sub-page-body">
|
||||
<section className="address-edit-card">
|
||||
<div className="address-edit-field">
|
||||
<label className="address-edit-label">收货人姓名</label>
|
||||
<div className="address-edit-line">
|
||||
<input
|
||||
type="text"
|
||||
className="address-edit-input"
|
||||
placeholder="请输入姓名"
|
||||
value={form.receiverName}
|
||||
onChange={(e) => {
|
||||
setForm({ ...form, receiverName: e.target.value });
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
<span className="material-symbols-outlined address-edit-field-icon">person</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="address-edit-field">
|
||||
<label className="address-edit-label">手机号码</label>
|
||||
<div className="address-edit-line">
|
||||
<span className="address-edit-prefix">+86</span>
|
||||
<input
|
||||
type="tel"
|
||||
className="address-edit-input"
|
||||
placeholder="请输入手机号"
|
||||
maxLength={11}
|
||||
inputMode="numeric"
|
||||
value={form.phone}
|
||||
onChange={(e) => {
|
||||
setForm({ ...form, phone: normalizePhoneInput(e.target.value) });
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
<span className="material-symbols-outlined address-edit-field-icon">smartphone</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" className="address-edit-field address-edit-region" onClick={() => setPickerOpen(true)}>
|
||||
<div className="address-edit-line address-edit-line--picker address-edit-line--region">
|
||||
<span className={regionText ? 'address-edit-region-value' : 'address-edit-region-placeholder'}>
|
||||
{regionText || '省份、城市、区县'}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div className="address-edit-field address-edit-field--last">
|
||||
<label className="address-edit-label">详细地址</label>
|
||||
<div className="address-edit-textarea-wrap">
|
||||
<textarea
|
||||
className="address-edit-textarea"
|
||||
placeholder="街道、门牌号、小区名称等"
|
||||
rows={3}
|
||||
value={form.detail}
|
||||
onChange={(e) => {
|
||||
setForm({ ...form, detail: e.target.value });
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="address-edit-card address-edit-default">
|
||||
<div className="address-edit-default-info">
|
||||
<div className="address-edit-default-icon">
|
||||
<span className="material-symbols-outlined fill-icon">stars</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="address-edit-default-title">设为默认地址</h3>
|
||||
<p className="address-edit-default-desc">每次下单时将优先使用此地址</p>
|
||||
</div>
|
||||
</div>
|
||||
<label className="address-edit-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.isDefault}
|
||||
onChange={(e) => setForm({ ...form, isDefault: e.target.checked })}
|
||||
/>
|
||||
<span className="address-edit-toggle-track" />
|
||||
<span className="address-edit-toggle-thumb" />
|
||||
</label>
|
||||
</section>
|
||||
|
||||
{error && <p className="address-edit-error">{error}</p>}
|
||||
|
||||
<div className="address-edit-security">
|
||||
<span className="material-symbols-outlined">location_on</span>
|
||||
<span>已通过杜康云安全加密处理</span>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<nav className="address-edit-footer">
|
||||
<button type="button" className="address-edit-cancel-btn" onClick={goBackToList}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
<span>取消</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="address-edit-save-btn"
|
||||
disabled={saving}
|
||||
onClick={save}
|
||||
>
|
||||
<span className="material-symbols-outlined">publish</span>
|
||||
<span>{saving ? '保存中...' : '保存并发布'}</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<RegionPicker
|
||||
open={pickerOpen}
|
||||
value={{ province: form.province, city: form.city, district: form.district }}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
onConfirm={(region) => {
|
||||
setForm((f) => ({
|
||||
...f,
|
||||
province: region.province,
|
||||
city: region.city,
|
||||
district: region.district,
|
||||
}));
|
||||
setPickerOpen(false);
|
||||
setError('');
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import SubPageHeader from '../components/SubPageHeader';
|
||||
import { request } from '../lib/api';
|
||||
import { useUserSession } from '../contexts/UserSessionContext';
|
||||
import { buildAddressEditUrl, buildAddressListUrl, buildOrderConfirmUrl, hasCheckoutContext, readCheckoutContext } from '../lib/navigation';
|
||||
import { usePageView } from '../lib/usePageView';
|
||||
|
||||
type Address = {
|
||||
id: string;
|
||||
receiverName: string;
|
||||
phone: string;
|
||||
province: string;
|
||||
city: string;
|
||||
district: string;
|
||||
detail: string;
|
||||
isDefault?: number;
|
||||
};
|
||||
|
||||
function maskPhone(phone: string) {
|
||||
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
|
||||
}
|
||||
|
||||
function formatAddress(a: Address) {
|
||||
return `${a.province}${a.city}${a.district}${a.detail}`;
|
||||
}
|
||||
|
||||
export default function AddressListPage() {
|
||||
usePageView('address_list_view');
|
||||
const { profile } = useUserSession();
|
||||
const [list, setList] = useState<Address[]>([]);
|
||||
const [pendingAddress, setPendingAddress] = useState<Address | null>(null);
|
||||
const [savingOrderAddress, setSavingOrderAddress] = useState(false);
|
||||
const [params] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const selectMode = params.get('select') === '1';
|
||||
const orderId = params.get('orderId') || '';
|
||||
const productId = params.get('productId') || '';
|
||||
const qty = params.get('qty') || '';
|
||||
const cross = params.get('cross') === '1';
|
||||
const currentAddressId = params.get('addressId') || '';
|
||||
|
||||
const loadList = useCallback(() => {
|
||||
request<Address[]>('USER_H5', '/user/addresses').then(setList);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadList();
|
||||
}, [loadList, profile?.id]);
|
||||
|
||||
function selectAddress(addr: Address) {
|
||||
if (!selectMode) return;
|
||||
if (orderId) {
|
||||
setPendingAddress(addr);
|
||||
return;
|
||||
}
|
||||
const qs = new URLSearchParams();
|
||||
if (productId) qs.set('productId', productId);
|
||||
if (qty) qs.set('qty', qty);
|
||||
if (cross) qs.set('cross', '1');
|
||||
qs.set('addressId', addr.id);
|
||||
navigate(`/order/confirm?${qs.toString()}`);
|
||||
}
|
||||
|
||||
async function confirmOrderAddress() {
|
||||
if (!orderId || !pendingAddress) return;
|
||||
setSavingOrderAddress(true);
|
||||
try {
|
||||
await request('USER_H5', `/trade/orders/${orderId}/address`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
receiverName: pendingAddress.receiverName,
|
||||
receiverPhone: pendingAddress.phone,
|
||||
receiverProvince: pendingAddress.province,
|
||||
receiverCity: pendingAddress.city,
|
||||
receiverDistrict: pendingAddress.district,
|
||||
receiverAddress: `${pendingAddress.province}${pendingAddress.city}${pendingAddress.district}${pendingAddress.detail}`,
|
||||
}),
|
||||
});
|
||||
navigate(`/orders/${orderId}`);
|
||||
} catch (e) {
|
||||
window.alert(e instanceof Error ? e.message : '修改地址失败');
|
||||
} finally {
|
||||
setSavingOrderAddress(false);
|
||||
setPendingAddress(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function setDefault(addr: Address, e: React.MouseEvent) {
|
||||
e.stopPropagation();
|
||||
if (addr.isDefault === 1) return;
|
||||
await request('USER_H5', `/user/addresses/${addr.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
receiverName: addr.receiverName,
|
||||
phone: addr.phone,
|
||||
province: addr.province,
|
||||
city: addr.city,
|
||||
district: addr.district,
|
||||
detail: addr.detail,
|
||||
isDefault: true,
|
||||
}),
|
||||
});
|
||||
loadList();
|
||||
}
|
||||
|
||||
async function removeAddress(id: string, e: React.MouseEvent) {
|
||||
e.stopPropagation();
|
||||
if (!window.confirm('确定删除该收货地址吗?')) return;
|
||||
await request('USER_H5', `/user/addresses/${id}`, { method: 'DELETE' });
|
||||
loadList();
|
||||
}
|
||||
|
||||
const checkoutCtx = readCheckoutContext(params);
|
||||
|
||||
function goEdit(id: string, e: React.MouseEvent) {
|
||||
e.stopPropagation();
|
||||
navigate(buildAddressEditUrl(id, checkoutCtx));
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (orderId) {
|
||||
navigate(`/orders/${orderId}`);
|
||||
return;
|
||||
}
|
||||
if (hasCheckoutContext(checkoutCtx)) {
|
||||
navigate(buildOrderConfirmUrl(checkoutCtx));
|
||||
return;
|
||||
}
|
||||
navigate('/mine');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="address-list-page">
|
||||
<SubPageHeader title={orderId ? '选择收货地址' : '我的地址'} onBack={goBack} />
|
||||
|
||||
<main className="address-list-main sub-page-body">
|
||||
{list.length === 0 && (
|
||||
<p className="address-list-empty">暂无收货地址,请新增</p>
|
||||
)}
|
||||
|
||||
<div className="address-list-cards">
|
||||
{list.map((a) => {
|
||||
const isDefault = Number(a.isDefault) === 1;
|
||||
const isSelected = selectMode && currentAddressId === String(a.id);
|
||||
return (
|
||||
<article
|
||||
key={a.id}
|
||||
className={`address-list-card${isDefault ? ' is-default' : ''}${isSelected ? ' is-selected' : ''}${selectMode ? ' is-selectable' : ''}`}
|
||||
onClick={() => selectAddress(a)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
selectAddress(a);
|
||||
}
|
||||
}}
|
||||
role={selectMode ? 'button' : undefined}
|
||||
tabIndex={selectMode ? 0 : undefined}
|
||||
>
|
||||
<div className="address-list-card-head">
|
||||
<div className="address-list-card-contact">
|
||||
<span className="address-list-name">{a.receiverName}</span>
|
||||
<span className="address-list-phone">{maskPhone(a.phone)}</span>
|
||||
</div>
|
||||
{isDefault && <span className="address-list-default-badge">默认</span>}
|
||||
</div>
|
||||
|
||||
<p className="address-list-detail">{formatAddress(a)}</p>
|
||||
|
||||
<div className="address-list-divider" />
|
||||
|
||||
<div className="address-list-actions">
|
||||
{isDefault ? (
|
||||
<div className="address-list-default-label">
|
||||
<span className="material-symbols-outlined fill-icon">check_circle</span>
|
||||
<span>默认地址</span>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="address-list-set-default"
|
||||
onClick={(e) => setDefault(a, e)}
|
||||
>
|
||||
<span className="material-symbols-outlined">radio_button_unchecked</span>
|
||||
<span>设为默认</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="address-list-action-btns">
|
||||
<button type="button" className="address-list-action-btn" onClick={(e) => goEdit(String(a.id), e)}>
|
||||
<span className="material-symbols-outlined">edit</span>
|
||||
<span>编辑</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="address-list-action-btn"
|
||||
onClick={(e) => removeAddress(String(a.id), e)}
|
||||
>
|
||||
<span className="material-symbols-outlined">delete</span>
|
||||
<span>删除</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{list.length > 0 && (
|
||||
<div className="address-list-brand" aria-hidden>
|
||||
<div className="address-list-brand-icon">
|
||||
<span className="material-symbols-outlined">location_on</span>
|
||||
</div>
|
||||
<p>DUKANG HERITAGE SERVICE</p>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
<footer className="address-list-footer">
|
||||
<Link
|
||||
to={buildAddressEditUrl('new', checkoutCtx)}
|
||||
className="address-list-add-btn"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<span className="material-symbols-outlined">add</span>
|
||||
<span>新增收货地址</span>
|
||||
</Link>
|
||||
</footer>
|
||||
|
||||
{pendingAddress && (
|
||||
<div className="order-address-modal-overlay" onClick={() => setPendingAddress(null)}>
|
||||
<div className="order-address-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="order-address-modal-head">
|
||||
<span className="material-symbols-outlined">location_on</span>
|
||||
<h3>修改收货地址</h3>
|
||||
</div>
|
||||
<div className="order-address-modal-body">
|
||||
<p>确认将订单收货地址修改为:</p>
|
||||
<p className="order-address-modal-target">
|
||||
{pendingAddress.receiverName} {maskPhone(pendingAddress.phone)}
|
||||
<br />
|
||||
{formatAddress(pendingAddress)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="order-address-modal-actions">
|
||||
<button type="button" onClick={() => setPendingAddress(null)}>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
disabled={savingOrderAddress}
|
||||
onClick={confirmOrderAddress}
|
||||
>
|
||||
{savingOrderAddress ? '保存中...' : '确认修改'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { TICKET_TYPE_LABELS, type TicketTypeDto } from '@dukang/shared-types';
|
||||
import SubPageHeader from '../components/SubPageHeader';
|
||||
import { request } from '../lib/api';
|
||||
import { usePageView } from '../lib/usePageView';
|
||||
|
||||
type TicketRow = {
|
||||
id: string;
|
||||
ticketNo: string;
|
||||
ticketType: TicketTypeDto;
|
||||
status: string;
|
||||
orderNo?: string;
|
||||
remark?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
PENDING: '待处理',
|
||||
OPEN: '处理中',
|
||||
RESOLVED: '已完成',
|
||||
REJECTED: '已驳回',
|
||||
CLOSED: '已关闭',
|
||||
};
|
||||
|
||||
export default function AfterSaleListPage() {
|
||||
usePageView('after_sale_list_view');
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<TicketRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
request<{ items: TicketRow[] }>('USER_H5', '/trade/after-sale-tickets?pageSize=50')
|
||||
.then((res) => setItems(res.items ?? []))
|
||||
.catch(() => setItems([]))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="after-sale-page">
|
||||
<SubPageHeader title="我的售后" onBack={() => navigate(-1)} />
|
||||
<main className="after-sale-body">
|
||||
{loading ? (
|
||||
<p className="after-sale-empty">加载中…</p>
|
||||
) : items.length === 0 ? (
|
||||
<div className="after-sale-empty-box">
|
||||
<p className="after-sale-empty">暂无售后工单</p>
|
||||
<button type="button" className="after-sale-primary" onClick={() => navigate('/after-sale')}>
|
||||
申请售后
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="after-sale-order-list">
|
||||
{items.map((t) => (
|
||||
<div key={t.id} className="after-sale-order-item after-sale-ticket-card">
|
||||
<div className="after-sale-ticket-head">
|
||||
<span>{TICKET_TYPE_LABELS[t.ticketType] ?? t.ticketType}</span>
|
||||
<span className="after-sale-ticket-status">{STATUS_LABEL[t.status] ?? t.status}</span>
|
||||
</div>
|
||||
<p className="after-sale-order-no">{t.ticketNo}</p>
|
||||
<p className="after-sale-order-meta">订单 {t.orderNo ?? '—'} · {new Date(t.createdAt).toLocaleString()}</p>
|
||||
{t.remark ? <p className="after-sale-order-meta">{t.remark}</p> : null}
|
||||
</div>
|
||||
))}
|
||||
<button type="button" className="after-sale-primary" onClick={() => navigate('/after-sale')}>
|
||||
新建售后
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
AFTER_SALE_TICKET_TYPES,
|
||||
TICKET_TYPE_LABELS,
|
||||
type AfterSaleTicketType,
|
||||
} from '@dukang/shared-types';
|
||||
import SubPageHeader from '../components/SubPageHeader';
|
||||
import { request } from '../lib/api';
|
||||
import { uploadFileToOss } from '../lib/upload';
|
||||
import { usePageView } from '../lib/usePageView';
|
||||
import { track } from '../lib/analytics';
|
||||
|
||||
type OrderRow = {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
status: string;
|
||||
payAmount: number | string;
|
||||
productName?: string;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
const STEPS = ['类型', '订单', '凭证', '完成'] as const;
|
||||
|
||||
export default function AfterSalePage() {
|
||||
usePageView('after_sale_apply');
|
||||
const navigate = useNavigate();
|
||||
const [params] = useSearchParams();
|
||||
const presetOrderId = params.get('orderId') || '';
|
||||
const presetType = (params.get('type') as AfterSaleTicketType | null) || null;
|
||||
|
||||
const [step, setStep] = useState(0);
|
||||
const [ticketType, setTicketType] = useState<AfterSaleTicketType | null>(
|
||||
presetType && AFTER_SALE_TICKET_TYPES.includes(presetType) ? presetType : null,
|
||||
);
|
||||
const [orders, setOrders] = useState<OrderRow[]>([]);
|
||||
const [orderId, setOrderId] = useState(presetOrderId);
|
||||
const [remark, setRemark] = useState('');
|
||||
const [evidenceUrls, setEvidenceUrls] = useState<string[]>([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [ticketNo, setTicketNo] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
request<{ list?: OrderRow[] }>('USER_H5', '/trade/orders?tab=paid&pageSize=50'),
|
||||
request<{ list?: OrderRow[] }>('USER_H5', '/trade/orders?tab=completed&pageSize=50'),
|
||||
])
|
||||
.then(([paid, completed]) => {
|
||||
const map = new Map<string, OrderRow>();
|
||||
[...(paid.list ?? []), ...(completed.list ?? [])].forEach((o) => map.set(o.id, o));
|
||||
setOrders([...map.values()]);
|
||||
})
|
||||
.catch(() => setOrders([]));
|
||||
}, []);
|
||||
|
||||
const selectedOrder = useMemo(() => orders.find((o) => o.id === orderId), [orders, orderId]);
|
||||
|
||||
async function onPickFiles(files: FileList | null) {
|
||||
if (!files?.length) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const uploaded: string[] = [];
|
||||
for (const file of Array.from(files).slice(0, 6 - evidenceUrls.length)) {
|
||||
const res = await uploadFileToOss(file, { bizType: 'after-sale' });
|
||||
uploaded.push(res.url);
|
||||
}
|
||||
setEvidenceUrls((prev) => [...prev, ...uploaded].slice(0, 6));
|
||||
} catch (e) {
|
||||
window.alert(e instanceof Error ? e.message : '上传失败');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!ticketType || !orderId) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const ticket = await request<{ ticketNo: string }>('USER_H5', `/trade/orders/${orderId}/after-sale-tickets`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
ticketType,
|
||||
remark: remark.trim() || undefined,
|
||||
evidenceUrls,
|
||||
}),
|
||||
});
|
||||
setTicketNo(ticket.ticketNo);
|
||||
setStep(3);
|
||||
} catch (e) {
|
||||
window.alert(e instanceof Error ? e.message : '提交失败');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function nextFromType() {
|
||||
if (!ticketType) {
|
||||
window.alert('请选择售后类型');
|
||||
return;
|
||||
}
|
||||
setStep(1);
|
||||
}
|
||||
|
||||
function nextFromOrder() {
|
||||
if (!orderId) {
|
||||
window.alert('请选择订单');
|
||||
return;
|
||||
}
|
||||
setStep(2);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="after-sale-page">
|
||||
<SubPageHeader title="申请售后" onBack={() => navigate(-1)} />
|
||||
|
||||
<div className="after-sale-steps">
|
||||
{STEPS.map((label, i) => (
|
||||
<span key={label} className={`after-sale-step${i === step ? ' is-active' : i < step ? ' is-done' : ''}`}>
|
||||
{label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<main className="after-sale-body">
|
||||
{step === 0 && (
|
||||
<div className="after-sale-type-list">
|
||||
{AFTER_SALE_TICKET_TYPES.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={`after-sale-type-item${ticketType === t ? ' is-selected' : ''}`}
|
||||
onClick={() => setTicketType(t)}
|
||||
>
|
||||
<span>{TICKET_TYPE_LABELS[t]}</span>
|
||||
<span className="material-symbols-outlined">chevron_right</span>
|
||||
</button>
|
||||
))}
|
||||
<button type="button" className="after-sale-primary" onClick={nextFromType}>
|
||||
下一步
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 1 && (
|
||||
<div className="after-sale-order-list">
|
||||
{orders.length === 0 ? (
|
||||
<p className="after-sale-empty">暂无可售后订单</p>
|
||||
) : (
|
||||
orders.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
className={`after-sale-order-item${orderId === o.id ? ' is-selected' : ''}`}
|
||||
onClick={() => setOrderId(o.id)}
|
||||
>
|
||||
<p className="after-sale-order-no">{o.orderNo}</p>
|
||||
<p className="after-sale-order-meta">
|
||||
{o.productName || '商品'} · ¥{Number(o.payAmount).toFixed(2)}
|
||||
</p>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
<div className="after-sale-actions">
|
||||
<button type="button" className="after-sale-secondary" onClick={() => setStep(0)}>
|
||||
上一步
|
||||
</button>
|
||||
<button type="button" className="after-sale-primary" onClick={nextFromOrder}>
|
||||
下一步
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<div className="after-sale-form">
|
||||
<p className="after-sale-summary">
|
||||
{ticketType ? TICKET_TYPE_LABELS[ticketType] : ''} · {selectedOrder?.orderNo ?? orderId}
|
||||
</p>
|
||||
<label className="after-sale-label">问题描述</label>
|
||||
<textarea
|
||||
className="after-sale-textarea"
|
||||
rows={4}
|
||||
placeholder="请描述问题(选填)"
|
||||
value={remark}
|
||||
onChange={(e) => setRemark(e.target.value)}
|
||||
/>
|
||||
<label className="after-sale-label">凭证图片(破损类建议上传)</label>
|
||||
<div className="after-sale-evidence">
|
||||
{evidenceUrls.map((url) => (
|
||||
<img key={url} src={url} alt="" className="after-sale-evidence-img" />
|
||||
))}
|
||||
{evidenceUrls.length < 6 && (
|
||||
<label className="after-sale-evidence-add">
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
disabled={uploading}
|
||||
onChange={(e) => void onPickFiles(e.target.files)}
|
||||
/>
|
||||
{uploading ? '上传中' : '+'}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div className="after-sale-actions">
|
||||
<button type="button" className="after-sale-secondary" onClick={() => setStep(1)}>
|
||||
上一步
|
||||
</button>
|
||||
<button type="button" className="after-sale-primary" disabled={submitting} onClick={() => void submit()}>
|
||||
{submitting ? '提交中…' : '提交工单'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<div className="after-sale-success">
|
||||
<span className="material-symbols-outlined after-sale-success-icon">check_circle</span>
|
||||
<p className="after-sale-success-title">售后已提交</p>
|
||||
<p className="after-sale-success-no">工单号 {ticketNo}</p>
|
||||
<p className="after-sale-success-hint">总部将尽快审核,请留意处理进度</p>
|
||||
<button type="button" className="after-sale-primary" onClick={() => navigate('/after-sale/list')}>
|
||||
查看我的售后
|
||||
</button>
|
||||
<button type="button" className="after-sale-secondary" onClick={() => navigate('/orders')}>
|
||||
返回订单
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user