53 Commits

Author SHA1 Message Date
jacy bb831f0580 merge(dev_jacy): v4.0.2 活动图模板与合伙人选择持久化
CI / verify (push) Waiting to run
2026-08-30 21:37:04 +08:00
jacy 3166467518 feat(ops): v4.0.2 活动图模板、合伙人选择持久化与用户管理主图
HQ 上传底图与码栏;合伙人单选写入 partner_account.activity_poster_id,用户管理下次登录仍显示同一张图。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 21:36:43 +08:00
jacy 0ff61c2cd1 chore(deploy): shop/partner/admin 禁止搜索引擎抓取
nginx 直出 robots.txt 并加 X-Robots-Tag,避免内部三端被收录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 15:50:22 +08:00
jacy fb66258b6a merge(dev_jacy): 门店账单确认打款支持上传凭证照片
CI / verify (push) Waiting to run
2026-08-30 15:26:32 +08:00
jacy e68eb4d38c feat(settlement): 门店账单确认打款支持上传凭证照片
财务确认打款与提现通过可附带 OSS 凭证图,详情与导出展示。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 15:25:56 +08:00
jacy b375fab44a v3.5.16小程序首页动画 2026-08-30 15:07:58 +08:00
jacy 58010feed8 Merge branch 'main' of git.yqidian.com:jacy/dukang into dev
CI / verify (push) Waiting to run
2026-08-30 14:40:56 +08:00
jacy 9f14c59f22 merge(dev_jacy): v4.0.1 partner assoc and H5 user management 2026-08-30 14:35:56 +08:00
jacy 9c8d5f2cad feat(assoc): v4.0.1 合伙人关联码、分佣账单与 H5 用户管理
订单佣金只认关联用户;合伙人备注写入独立表;H5 增加用户管理与首页统计。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 14:35:39 +08:00
jacy 870494563d merge(dev): store bill issue date to today
CI / verify (push) Has been cancelled
2026-08-28 14:14:39 +08:00
jacy 4c9b3f72bc merge(dev_jacy): store bill issue date to today 2026-08-28 14:13:28 +08:00
jacy 3b669f7e38 fix(settlement): 门店 T+1 出账日改为窗口中的今天
HQ 门店账单列名改为出账日;billDate 记今日(昨日 00:00–今日 00:00 右端),启动时把旧数据从核销自然日对齐过来。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 14:12:35 +08:00
jacy 14c5c8c3f3 merge(dev): v3.5.18 HQ 明文手机、任务版本与核销快链
CI / verify (push) Has been cancelled
2026-08-28 13:58:57 +08:00
jacy a7f3283ae5 merge(dev_jacy): v3.5.18 HQ 明文手机、任务版本与核销快链 2026-08-28 13:58:37 +08:00
jacy da19c39965 feat(admin): v3.5.18 用户详情明文手机、任务关联版本与核销快链
HQ 后台:用户/核销记录展示完整手机号;任务列表与编辑可关联版本;账单核销单号与券号/用户可快链;门店账单日标明为出账自然日;技术支持操作按钮右对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:58:08 +08:00
jacy c06251f0a4 merge(dev): HQ 订单筛选改版与用户商品模糊搜索
CI / verify (push) Has been cancelled
2026-08-28 13:12:52 +08:00
jacy faa1830bde merge(dev_jacy): HQ 订单筛选改版与用户商品模糊搜索 2026-08-28 13:11:17 +08:00
jacy b226af2adc feat(admin): 订单页筛选改版并支持用户与商品模糊搜索
收起次要筛选项,去掉过滤测试;列表可按用户编号/昵称/备注/手机与商品名称/规格查询。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:10:36 +08:00
jacy 2b5f42acdf merge(dev): HQ 推广码订单只计已完成并补快链
CI / verify (push) Has been cancelled
2026-08-28 12:57:03 +08:00
jacy 71149044ca merge(dev_jacy): HQ 推广码订单只计已完成并补快链 2026-08-28 12:56:02 +08:00
jacy fccfd7abbe feat(promo): HQ 推广码订单只计已完成并补扫码订单快链
列表与详情的订单数/转化率按 COMPLETED 实时统计;扫码、订单、事件 ID 可跳到对应页。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 12:55:19 +08:00
jacy 1ecc6a11df merge(dev): 企微结算账单明细与成交播报用户明文
CI / verify (push) Has been cancelled
2026-08-27 11:46:12 +08:00
jacy cfd42dfc32 merge(dev_jacy): 企微结算账单明细与成交播报用户明文 2026-08-27 11:45:59 +08:00
jacy 737efb89a3 feat(wecom): 结算账单明细与成交播报用户明文
支付/核销补 HQ 备注且手机号不脱敏;结算通知按城市、合伙人、笔数和累计金额分块推送。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 11:45:08 +08:00
jacy a423fb71e8 merge(dev): v3.5.14 提交订单/支付成功日志端修复
CI / verify (push) Has been cancelled
2026-08-26 17:25:25 +08:00
jacy 4111e5c0a6 merge(dev_jacy): v3.5.14 提交订单/支付成功日志端修复 2026-08-26 17:25:15 +08:00
jacy 3dbb73e428 fix(trade): v3.5.14 提交订单/支付成功日志使用真实 clientApp
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 17:24:56 +08:00
jacy 3a9f27eb38 merge(dev): v3.5.12 大屏BGM、中文展示、分类删除与侧栏
CI / verify (push) Has been cancelled
2026-08-26 10:55:40 +08:00
jacy e2f5aa9dd8 merge(dev_jacy): v3.5.12 大屏BGM、中文展示、分类删除与侧栏 2026-08-26 10:55:14 +08:00
jacy 58a8b47532 feat(admin): v3.5.12 大屏BGM、中文展示、分类删除修复与侧栏顺序
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 10:54:19 +08:00
jacy 6a5c0cb090 Merge pull request 'Dev' (#53) from dev into main
CI / verify (push) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/53
2026-08-26 09:56:50 +08:00
jacy 448b9983d3 Merge pull request 'Dev jacy v3.5.11 企业微信通知调整' (#52) from dev_jacy into dev
CI / verify (pull_request) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/52
2026-08-26 09:56:36 +08:00
jacy 3afbdfe6b9 v3.5.11企业微信通知调整
CI / verify (pull_request) Has been cancelled
2026-08-26 09:55:19 +08:00
jacy 632539e8dc 增加现场提货的配置 2026-08-26 09:22:29 +08:00
jacy c7cd0f6cf2 C端SKU数量小于等于1不展示chip
后端修复规格轴数据错乱显示问题
2026-08-26 07:43:26 +08:00
jacy 00bb6a2227 Merge pull request 'Dev' (#51) from dev into main
CI / verify (push) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/51
2026-08-26 07:16:04 +08:00
jacy 1f06530894 Merge pull request '小程序版本号' (#50) from dev_jacy into dev
CI / verify (pull_request) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/50
2026-08-26 07:15:52 +08:00
jacy 1f4506f60b 小程序版本号
CI / verify (pull_request) Has been cancelled
2026-08-26 07:13:54 +08:00
jacy 93390ccf75 merge(dev): 同城运费路由与配送单信息
CI / verify (push) Has been cancelled
2026-08-25 21:13:05 +08:00
jacy a2976cdc8f merge(dev_jacy): 同城运费路由与配送单信息 2026-08-25 21:12:53 +08:00
jacy cc0c0a6ef8 feat(fulfillment): 同城运费与路由修复,配送单展示商品用户地址
同城 MANUAL/ZZXFX 按小飞侠价规计费,路由查询回退仓配凭证;HQ 配送单补商品、用户和收货地址。门店核销回跳与小程序核销码一并带上。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 21:12:36 +08:00
jacy 8f2ebbfef4 merge(dev): 补承运商删除操作常量
CI / verify (push) Has been cancelled
2026-08-25 14:32:32 +08:00
jacy ee1a3f4b6c merge(dev_jacy): 补承运商删除操作常量 2026-08-25 14:32:27 +08:00
jacy 52a7d3789d fix(ops): 补承运商删除操作常量以便生产构建
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 14:32:08 +08:00
jacy f2fbf95c53 merge(dev): v3.5.10 同城配送提示与企微客服
CI / verify (push) Has been cancelled
2026-08-25 14:30:43 +08:00
jacy 98d52ff173 merge(dev_jacy): v3.5.10 同城配送提示与企微客服 2026-08-25 14:30:10 +08:00
jacy 797b20979d feat(mini-user): v3.5.10 同城配送提示可配置并支持换行
承运商 HTML 按收货市下发;textarea 回车在 C 端转成换行。含门店去掉分享按钮与小程序企微客服。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 14:29:48 +08:00
jacy 43de361e61 merge(dev): 列设置靠右与订单状态多选
CI / verify (push) Has been cancelled
2026-08-25 14:20:39 +08:00
jacy b1511ecb92 merge(dev_jacy): 列设置靠右与订单状态多选 2026-08-25 14:20:13 +08:00
jacy fed8ff3d3a fix(admin): 列设置靠右并支持订单状态多选
HQ 列表主操作居右、列设置贴最右侧;订单筛选状态可多选,导出同步过滤。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 14:19:49 +08:00
jacy 0b548a2764 Merge pull request 'Dev' (#49) from dev into main
CI / verify (push) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/49
2026-08-25 12:39:52 +08:00
jacy 30f8d649cb Merge pull request 'v3.5.9版本迭代列表优化' (#48) from dev_jacy into dev
CI / verify (pull_request) Has been cancelled
Reviewed-on: https://git.yqidian.com/jacy/dukang/pulls/48
2026-08-25 12:39:30 +08:00
jacy f4da71e952 v3.5.9版本迭代列表优化
CI / verify (pull_request) Has been cancelled
2026-08-25 12:38:21 +08:00
304 changed files with 19050 additions and 6842 deletions
+1 -1
View File
@@ -89,7 +89,7 @@ await this.prisma.order.update({ ... });
```typescript ```typescript
const benefitAmount = product.benefitAmount ?? product.price; const benefitAmount = product.benefitAmount ?? product.price;
// 核销:直接核销按全部 ACTIVE 权益总余额;带单据核销按该单据可用金额 // 核销:直接核销按全部 ACTIVE 权益总余额;带单据核销按该单据可用金额
// 同城 min 2 瓶 / 跨城 min 6 瓶 // 起购:提货/同城 min 2 瓶 / 跨城 min 6 瓶(城市配置,非承运商)
// 支付成功 → log_third_party + user_order.pay_status=PAID // 支付成功 → log_third_party + user_order.pay_status=PAID
// → user_benefit_coupon + common_event(BENEFIT_LEDGER, GRANT) // → user_benefit_coupon + common_event(BENEFIT_LEDGER, GRANT)
+1 -1
View File
@@ -37,7 +37,7 @@ disable-model-invocation: true
``` ```
权益额 = 订单实付 1:1(永久) 权益额 = 订单实付 1:1(永久)
同城起购 2 瓶 / 跨城 1 箱(6瓶) 起购:现场提货 2 瓶 / 同城 2 瓶 / 跨城 1 箱(6瓶);属城市,非承运商
门店结算 = 核销额 × 60% 门店结算 = 核销额 × 60%
单合伙人:订单佣金 + 核销佣金 ≤ 5%(默认 0% + 3%) 单合伙人:订单佣金 + 核销佣金 ≤ 5%(默认 0% + 3%)
核销码 TTL = 3 分钟;试核销固定 ¥100 核销码 TTL = 3 分钟;试核销固定 ¥100
@@ -12,9 +12,9 @@
| REQ-U-004 | 定位 | 右上角市区;默认 IP;可授权精确定位 | | REQ-U-004 | 定位 | 右上角市区;默认 IP;可授权精确定位 |
| REQ-U-005 | 首页商品 | 4 款酒祖杜康;大图、标题加粗、价格标红、权益金额 | | REQ-U-005 | 首页商品 | 4 款酒祖杜康;大图、标题加粗、价格标红、权益金额 |
| REQ-U-006 | 商品详情 | 规格瓶/箱、度数、价格、权益、详情图 | | REQ-U-006 | 商品详情 | 规格瓶/箱、度数、价格、权益、详情图 |
| REQ-U-007 | 同城 | 小飞侠;≥2 瓶免运费;物流节点+拍照;24h 自动完成 | | REQ-U-007 | 同城 | 小飞侠;起购 ≥2 瓶(城市 `localMinQty`);≥2 瓶免运费;物流节点+拍照;24h 自动完成 |
| REQ-U-008 | 现场提货 | 隐藏入口;支付即完成;强提示在现场 | | REQ-U-008 | 现场提货 | 隐藏入口;起购 ≥2 瓶(城市 `pickupMinQty`);支付即完成;强提示在现场 |
| REQ-U-009 | 跨城 | 未开通城市;≥1 箱;总部物流到付 | | REQ-U-009 | 跨城 | 未开通城市;起购 ≥1 箱(城市 `crossMinQty`=6 瓶当量);总部物流到付 |
| REQ-U-010 | 锁单 | 待付款 30 分钟取消 | | REQ-U-010 | 锁单 | 待付款 30 分钟取消 |
| REQ-U-011 | 权益 | 支付成功 1:1 永久 | | REQ-U-011 | 权益 | 支付成功 1:1 永久 |
| REQ-U-012 | 客服 | 已付款起电话/微信客服 | | REQ-U-012 | 客服 | 已付款起电话/微信客服 |
+1
View File
@@ -26,3 +26,4 @@ server/dukang-api/assets/fonts/*.ttc
server/dukang-api/assets/fonts/*.otf server/dukang-api/assets/fonts/*.otf
deploy/auto-release.env deploy/auto-release.env
deploy/backups/ deploy/backups/
.playwright-mcp/
+1 -1
View File
@@ -35,7 +35,7 @@
``` ```
权益额 = benefit_amount ?? price 权益额 = benefit_amount ?? price
同城起购 2 瓶 / 跨城 6 瓶 起购:现场提货 2 瓶 / 同城 2 瓶 / 跨城 6 瓶(1 箱);属城市,非承运商
核销:直接核销 0 < amount ≤ 全部 ACTIVE 权益总余额;带单据核销 0 < amount ≤ 该单据可用金额;Redis 码 3 分钟 核销:直接核销 0 < amount ≤ 全部 ACTIVE 权益总余额;带单据核销 0 < amount ≤ 该单据可用金额;Redis 码 3 分钟
C 端门店仅 status=OPEN C 端门店仅 status=OPEN
订单 Tab:待付款 | 已付款 | 已完成 订单 Tab:待付款 | 已付款 | 已完成
+1 -1
View File
@@ -92,7 +92,7 @@
```text ```text
权益发放额 = common_product_item.benefit_amount ?? price 权益发放额 = common_product_item.benefit_amount ?? price
同城起购 2 瓶 / 跨城 6 瓶 起购:现场提货 2 瓶 / 同城 2 瓶 / 跨城 6 瓶(1 箱);属城市,非承运商
核销:直接核销 0 < amount ≤ 全部 ACTIVE 权益总余额;带单据核销 0 < amount ≤ 该单据可用金额 核销:直接核销 0 < amount ≤ 全部 ACTIVE 权益总余额;带单据核销 0 < amount ≤ 该单据可用金额
C 端门店列表仅 status=OPEN C 端门店列表仅 status=OPEN
订单 Taball | pending_pay | pending_ship | pending_receive | completed 订单 Taball | pending_pay | pending_ship | pending_receive | completed
+1
View File
@@ -3,6 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex, nofollow, noarchive" />
<title>杜康好客 · HQ 管理后台</title> <title>杜康好客 · HQ 管理后台</title>
</head> </head>
<body> <body>
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+2
View File
@@ -25,6 +25,7 @@ import FulfillmentProvidersPage from './pages/FulfillmentProvidersPage';
import StoreMediaPage from './pages/StoreMediaPage'; import StoreMediaPage from './pages/StoreMediaPage';
import StoreCategoriesPage from './pages/StoreCategoriesPage'; import StoreCategoriesPage from './pages/StoreCategoriesPage';
import PromoCodesPage from './pages/PromoCodesPage'; import PromoCodesPage from './pages/PromoCodesPage';
import ActivityPostersPage from './pages/ActivityPostersPage';
import PromoCodeDetailLayout from './pages/promo/PromoCodeDetailLayout'; import PromoCodeDetailLayout from './pages/promo/PromoCodeDetailLayout';
import PromoCodeDetailPage from './pages/promo/PromoCodeDetailPage'; import PromoCodeDetailPage from './pages/promo/PromoCodeDetailPage';
import PromoCodeUsersPage from './pages/promo/PromoCodeUsersPage'; import PromoCodeUsersPage from './pages/promo/PromoCodeUsersPage';
@@ -86,6 +87,7 @@ export default function App() {
<Route path="/wechat-bindings" element={<WechatBindingsPage />} /> <Route path="/wechat-bindings" element={<WechatBindingsPage />} />
<Route path="/orders" element={<OrdersPage />} /> <Route path="/orders" element={<OrdersPage />} />
<Route path="/promo-codes" element={<PromoCodesPage />} /> <Route path="/promo-codes" element={<PromoCodesPage />} />
<Route path="/activity-posters" element={<ActivityPostersPage />} />
<Route path="/promo-codes/:id" element={<PromoCodeDetailLayout />}> <Route path="/promo-codes/:id" element={<PromoCodeDetailLayout />}>
<Route index element={<PromoCodeDetailPage />} /> <Route index element={<PromoCodeDetailPage />} />
<Route path="users" element={<PromoCodeUsersPage />} /> <Route path="users" element={<PromoCodeUsersPage />} />
+177
View File
@@ -46,6 +46,132 @@ body,
text-overflow: clip; text-overflow: clip;
} }
/* 拖表头分割线改列宽 */
.admin-layout .ant-table-thead > tr > th.admin-th-resizable {
position: relative;
}
.admin-col-resize-handle {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 10px;
cursor: col-resize;
z-index: 3;
user-select: none;
touch-action: none;
}
.admin-col-resize-handle:hover,
.admin-col-resizing .admin-col-resize-handle {
background: rgba(22, 119, 255, 0.18);
}
body.admin-col-resizing,
body.admin-col-resizing * {
cursor: col-resize !important;
user-select: none !important;
}
/* 订单页筛选:第一行常驻,第二行起可收起 */
.admin-orders-filter-row {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
align-items: flex-end;
margin-bottom: 12px;
}
.admin-orders-filter-row--tools {
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
}
.admin-orders-filter-item {
margin-bottom: 0 !important;
}
.admin-orders-filter-item--sm {
width: 140px;
}
.admin-orders-filter-item--md {
width: 168px;
}
.admin-orders-filter-item--search {
width: 180px;
}
.admin-users-filter-item--keyword {
width: 240px;
}
.admin-orders-filter-item--status {
width: 220px;
min-width: 180px;
flex: 1 1 180px;
max-width: 280px;
}
.admin-orders-filter-item--date {
flex: 1 1 auto;
}
.admin-orders-filter-actions {
margin-left: auto;
}
.admin-orders-date-picker {
width: 240px;
}
/* 列表页顶栏:标题左、主操作右、列设置最右 */
.admin-list-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 16px;
}
.admin-list-header-left {
min-width: 0;
}
.admin-list-header-desc {
margin-top: 4px;
color: rgba(0, 0, 0, 0.45);
line-height: 1.5;
}
.admin-list-header-right {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-shrink: 0;
margin-left: auto;
}
.admin-list-settings-slot {
display: inline-flex;
margin-left: auto;
order: 99;
flex-shrink: 0;
}
.admin-list-settings-btn.ant-btn {
color: rgba(0, 0, 0, 0.55);
padding-inline: 8px;
}
.admin-list-settings-btn.ant-btn:hover {
color: rgba(0, 0, 0, 0.88);
}
/* 操作列保持可见 */ /* 操作列保持可见 */
.admin-layout .ant-table-cell:has(.ant-btn), .admin-layout .ant-table-cell:has(.ant-btn),
.ant-drawer .ant-table-cell:has(.ant-btn), .ant-drawer .ant-table-cell:has(.ant-btn),
@@ -81,6 +207,23 @@ body,
font-size: 12px; font-size: 12px;
} }
.admin-primary-link {
display: inline;
margin: 0;
padding: 0;
border: 0;
background: none;
font: inherit;
color: inherit;
text-decoration: underline;
text-underline-offset: 3px;
cursor: pointer;
}
.admin-primary-link:hover {
color: #1677ff;
}
.admin-table-nowrap .ant-table-cell, .admin-table-nowrap .ant-table-cell,
.admin-table-nowrap .ant-table-cell-ellipsis { .admin-table-nowrap .ant-table-cell-ellipsis {
white-space: nowrap; white-space: nowrap;
@@ -219,6 +362,40 @@ body:has(.big-screen-page),
gap: 12px; gap: 12px;
} }
.big-screen-bgm {
display: inline-flex;
align-items: center;
gap: 8px;
margin-right: 8px;
padding: 6px 14px 6px 12px;
border: 1px solid rgba(105, 192, 255, 0.45);
border-radius: 6px;
background: rgba(8, 28, 56, 0.7);
color: rgba(230, 244, 255, 0.92);
font-size: 14px;
font-weight: 700;
letter-spacing: 1px;
cursor: pointer;
line-height: 1;
}
.big-screen-bgm:hover {
border-color: rgba(105, 192, 255, 0.85);
color: #fff;
}
.big-screen-bgm.is-on {
border-color: rgba(64, 169, 255, 0.85);
box-shadow: 0 0 12px rgba(64, 169, 255, 0.28);
color: #fff;
}
.big-screen-bgm-icon {
display: inline-flex;
width: 16px;
height: 16px;
}
.big-screen-live-label { .big-screen-live-label {
font-size: 18px; font-size: 18px;
color: rgba(230, 244, 255, 0.88); color: rgba(230, 244, 255, 0.88);
Binary file not shown.
@@ -0,0 +1,110 @@
import { useCallback, useRef } from 'react';
import { DEFAULT_ACTIVITY_POSTER_QR_SLOT, type ActivityPosterQrSlot } from '@dukang/shared-types';
type Props = {
imageUrl?: string;
value?: ActivityPosterQrSlot;
onChange?: (slot: ActivityPosterQrSlot) => void;
};
export default function ActivityPosterQrSlotEditor({ imageUrl, value, onChange }: Props) {
const boxRef = useRef<HTMLDivElement>(null);
const dragRef = useRef<{
mode: 'move' | 'resize';
startX: number;
startY: number;
start: ActivityPosterQrSlot;
} | null>(null);
const slot = value ?? DEFAULT_ACTIVITY_POSTER_QR_SLOT;
const apply = useCallback((next: ActivityPosterQrSlot) => {
const size = Math.min(50, Math.max(5, next.qrSizePct));
const box = boxRef.current;
const ratio = box && box.clientHeight > 0 ? box.clientWidth / box.clientHeight : 1;
const heightPct = size * ratio;
const x = Math.min(100 - size, Math.max(0, next.qrXPct));
const y = Math.min(Math.max(0, 100 - heightPct), Math.max(0, next.qrYPct));
onChange?.({
qrXPct: Number(x.toFixed(2)),
qrYPct: Number(y.toFixed(2)),
qrSizePct: Number(size.toFixed(2)),
});
}, [onChange]);
function onPointerDown(mode: 'move' | 'resize', e: React.PointerEvent) {
e.preventDefault();
e.stopPropagation();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragRef.current = { mode, startX: e.clientX, startY: e.clientY, start: { ...slot } };
}
function onPointerMove(e: React.PointerEvent) {
const drag = dragRef.current;
const box = boxRef.current;
if (!drag || !box) return;
const dx = ((e.clientX - drag.startX) / box.clientWidth) * 100;
const dy = ((e.clientY - drag.startY) / box.clientHeight) * 100;
if (drag.mode === 'move') {
apply({
...drag.start,
qrXPct: drag.start.qrXPct + dx,
qrYPct: drag.start.qrYPct + dy,
});
} else {
apply({ ...drag.start, qrSizePct: drag.start.qrSizePct + dx });
}
}
function endDrag() {
dragRef.current = null;
}
if (!imageUrl) {
return <div style={{ color: 'rgba(0,0,0,0.45)' }}></div>;
}
return (
<div>
<div
ref={boxRef}
style={{ position: 'relative', width: '100%', maxWidth: 420, userSelect: 'none', touchAction: 'none' }}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
<img src={imageUrl} alt="活动图预览" style={{ width: '100%', display: 'block' }} draggable={false} />
<div
style={{
position: 'absolute',
left: `${slot.qrXPct}%`,
top: `${slot.qrYPct}%`,
width: `${slot.qrSizePct}%`,
aspectRatio: '1',
border: '2px dashed #1677ff',
background: 'rgba(22,119,255,0.14)',
cursor: 'move',
boxSizing: 'border-box',
}}
onPointerDown={(e) => onPointerDown('move', e)}
>
<div
style={{
position: 'absolute',
right: -6,
bottom: -6,
width: 14,
height: 14,
background: '#1677ff',
borderRadius: 2,
cursor: 'nwse-resize',
}}
onPointerDown={(e) => onPointerDown('resize', e)}
/>
</div>
</div>
<div style={{ marginTop: 8, color: 'rgba(0,0,0,0.45)', fontSize: 12 }}>
{slot.qrSizePct}%
</div>
</div>
);
}
@@ -0,0 +1,36 @@
import type { ReactNode } from 'react';
import { Space, Typography } from 'antd';
/** 列表页顶栏:标题在左,主操作在右,列设置永远最右 */
export function AdminListHeader({
title,
description,
actions,
settings,
}: {
title?: ReactNode;
description?: ReactNode;
actions?: ReactNode;
settings?: ReactNode;
}) {
return (
<div className="admin-list-header">
<div className="admin-list-header-left">
{title == null || title === '' ? null : typeof title === 'string' || typeof title === 'number' ? (
<Typography.Title level={4} style={{ margin: 0 }}>
{title}
</Typography.Title>
) : (
title
)}
{description ? (
<div className="admin-list-header-desc">{description}</div>
) : null}
</div>
<div className="admin-list-header-right">
{actions ? <Space wrap>{actions}</Space> : null}
{settings}
</div>
</div>
);
}
@@ -0,0 +1,25 @@
import type { MouseEvent, ReactNode } from 'react';
/** HQ 主列表主展示列:下划线,点击进入编辑或详情 */
export function AdminPrimaryLink({
children,
onClick,
}: {
children?: ReactNode;
onClick: (e?: MouseEvent) => void;
}) {
const empty = children == null || children === '';
return (
<button
type="button"
className="admin-primary-link"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClick(e);
}}
>
{empty ? '—' : children}
</button>
);
}
@@ -11,10 +11,23 @@ import PackageImagesUpload from './PackageImagesUpload';
type PackageRow = StorePackageItemDto; type PackageRow = StorePackageItemDto;
export type AdminStorePackagesHandle = { export type AdminStorePackagesHandle = {
/** 套餐已加载时写入;加载中则跳过,避免空数据覆盖线上套餐 */ /** 仅在用户改过套餐时写入;加载中或未改动则跳过,避免空表单覆盖刚审核通过的线上套餐 */
saveIfLoaded: (opts?: { quiet?: boolean }) => Promise<{ skipped: boolean }>; saveIfLoaded: (opts?: { quiet?: boolean }) => Promise<{ skipped: boolean }>;
}; };
function mapLiveRows(live: StorePackagesResponse['live']): PackageRow[] {
return (live ?? []).map((p, i) => {
const imageUrls = normalizeStorePackageImageUrls(p);
return {
...p,
price: String(p.price),
imageUrl: imageUrls[0] ?? '',
imageUrls,
sortOrder: i,
};
});
}
function emptyRow(index = 0): PackageRow { function emptyRow(index = 0): PackageRow {
return { return {
name: '', name: '',
@@ -37,6 +50,7 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
const [pendingRequest, setPendingRequest] = useState<StorePackagesResponse['pendingRequest']>(null); const [pendingRequest, setPendingRequest] = useState<StorePackagesResponse['pendingRequest']>(null);
const itemsRef = useRef(items); const itemsRef = useRef(items);
const loadingRef = useRef(loading); const loadingRef = useRef(loading);
const dirtyRef = useRef(false);
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
@@ -47,36 +61,33 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
loadingRef.current = loading; loadingRef.current = loading;
}, [loading]); }, [loading]);
function applyServerPackages(data: StorePackagesResponse) {
dirtyRef.current = false;
setPendingRequest(data.pendingRequest ?? null);
setItems(mapLiveRows(data.live));
}
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
setPendingRequest(null); setPendingRequest(null);
dirtyRef.current = false;
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`) request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
.then((data) => { .then((data) => applyServerPackages(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 : '加载套餐失败')) .catch((e) => message.error(e instanceof Error ? e.message : '加载套餐失败'))
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, [storeId]); }, [storeId]);
// 审核页完成审核后,自动刷新本页「有待审核套餐」提醒 // 审核通过/驳回后刷新提醒;用户未改套餐时同步线上结果,避免抽屉里仍显示空套餐
useEffect(() => { useEffect(() => {
const onChanged = () => { const onChanged = () => {
request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`) request<StorePackagesResponse>(`/admin/stores/${storeId}/packages`)
.then((data) => setPendingRequest(data.pendingRequest ?? null)) .then((data) => {
setPendingRequest(data.pendingRequest ?? null);
if (!dirtyRef.current) {
dirtyRef.current = false;
setItems(mapLiveRows(data.live));
}
})
.catch(() => undefined); .catch(() => undefined);
}; };
window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged); window.addEventListener(PACKAGE_AUDIT_CHANGED_EVENT, onChanged);
@@ -108,16 +119,19 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
) : null; ) : null;
function updateAt(index: number, patch: Partial<PackageRow>) { function updateAt(index: number, patch: Partial<PackageRow>) {
dirtyRef.current = true;
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item))); setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
} }
function addRow() { function addRow() {
if (items.length >= STORE_PACKAGE_MAX_COUNT) return; if (items.length >= STORE_PACKAGE_MAX_COUNT) return;
dirtyRef.current = true;
setItems((prev) => [...prev, emptyRow(prev.length)]); setItems((prev) => [...prev, emptyRow(prev.length)]);
} }
function removeAt(index: number) { function removeAt(index: number) {
const run = () => { const run = () => {
dirtyRef.current = true;
setItems((prev) => { setItems((prev) => {
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i })); const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
return next.length ? next : []; return next.length ? next : [];
@@ -203,20 +217,8 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
}), }),
}); });
if (!opts?.quiet) message.success('套餐已保存并生效'); if (!opts?.quiet) message.success('套餐已保存并生效');
setItems( dirtyRef.current = false;
data.live?.length setItems(mapLiveRows(data.live));
? data.live.map((p, i) => {
const imageUrls = normalizeStorePackageImageUrls(p);
return {
...p,
price: String(p.price),
imageUrl: imageUrls[0] ?? '',
imageUrls,
sortOrder: i,
};
})
: [],
);
} catch (e) { } catch (e) {
if (!opts?.quiet) message.error(e instanceof Error ? e.message : '保存失败'); if (!opts?.quiet) message.error(e instanceof Error ? e.message : '保存失败');
throw e; throw e;
@@ -227,7 +229,7 @@ const AdminStorePackagesSection = forwardRef<AdminStorePackagesHandle, { storeId
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
saveIfLoaded: async (opts) => { saveIfLoaded: async (opts) => {
if (loadingRef.current) return { skipped: true }; if (loadingRef.current || !dirtyRef.current) return { skipped: true };
await save(opts); await save(opts);
return { skipped: false }; return { skipped: false };
}, },
@@ -26,10 +26,12 @@ import {
type PartnerPermissionKey, type PartnerPermissionKey,
} from '@dukang/shared-types'; } from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { omitNullFields } from '../lib/omit-null-fields';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region'; import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import CityDistrictMultiSelect from './CityDistrictMultiSelect'; import CityDistrictMultiSelect from './CityDistrictMultiSelect';
import PartnerSubAccountList from './PartnerSubAccountList'; import PartnerSubAccountList from './PartnerSubAccountList';
import PartnerAssocPanel from './PartnerAssocPanel';
type PartnerRow = { type PartnerRow = {
id: string; id: string;
@@ -186,7 +188,7 @@ export default function CityPartnersPanel({
await request(`/admin/partners/${detail.id}`, { await request(`/admin/partners/${detail.id}`, {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ body: JSON.stringify({
...v, ...omitNullFields(v),
orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100, orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100,
redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100, redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100,
districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined, districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined,
@@ -345,6 +347,11 @@ export default function CityPartnersPanel({
/> />
), ),
}, },
{
key: 'assoc',
label: '关联码',
children: <PartnerAssocPanel partnerId={detail.id} />,
},
]} ]}
/> />
)} )}
@@ -0,0 +1,97 @@
import { useEffect, useState } from 'react';
import { Image, Input, Modal, Space, Typography } from 'antd';
import { PAYMENT_PROOF_IMAGE_MAX_COUNT } from '@dukang/shared-types';
import MultiImageUpload from './MultiImageUpload';
export function parsePaymentProofUrls(raw: unknown): string[] {
if (!Array.isArray(raw)) return [];
return raw.map((u) => String(u ?? '').trim()).filter(Boolean);
}
export function PaymentProofGallery({ urls }: { urls?: unknown }) {
const list = parsePaymentProofUrls(urls);
if (!list.length) return <></>;
return (
<Image.PreviewGroup>
<Space wrap size={8}>
{list.map((url, index) => (
<Image
key={`${url}-${index}`}
src={url}
width={72}
height={72}
style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #f0f0f0' }}
/>
))}
</Space>
</Image.PreviewGroup>
);
}
type FinancePayProofModalProps = {
open: boolean;
title: string;
hint: string;
okText: string;
confirmLoading?: boolean;
onCancel: () => void;
onOk: (payload: { paymentRef?: string; paymentProofUrls?: string[] }) => Promise<void>;
};
export function FinancePayProofModal({
open,
title,
hint,
okText,
confirmLoading,
onCancel,
onOk,
}: FinancePayProofModalProps) {
const [paymentRef, setPaymentRef] = useState('');
const [proofUrls, setProofUrls] = useState<string[]>([]);
useEffect(() => {
if (open) {
setPaymentRef('');
setProofUrls([]);
}
}, [open]);
return (
<Modal
title={title}
open={open}
okText={okText}
cancelText="取消"
confirmLoading={confirmLoading}
destroyOnClose
width={480}
onCancel={onCancel}
onOk={async () => {
await onOk({
paymentRef: paymentRef.trim() || undefined,
paymentProofUrls: proofUrls.length ? proofUrls : undefined,
});
}}
>
<Typography.Paragraph style={{ marginBottom: 12 }}>{hint}</Typography.Paragraph>
<Input
placeholder="打款凭证号(可选)"
value={paymentRef}
onChange={(e) => setPaymentRef(e.target.value)}
style={{ marginBottom: 12 }}
/>
<Typography.Text type="secondary"></Typography.Text>
<div style={{ marginTop: 8 }}>
<MultiImageUpload
bizType="PAYMENT_PROOF"
value={proofUrls}
onChange={setProofUrls}
maxCount={PAYMENT_PROOF_IMAGE_MAX_COUNT}
buttonText="上传凭证照片"
tip={`最多 ${PAYMENT_PROOF_IMAGE_MAX_COUNT} 张,支持一次选择多张`}
/>
</div>
</Modal>
);
}
@@ -173,7 +173,9 @@ export default function OrderTrackDrawer({
<Empty <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE} image={Empty.PRESENTED_IMAGE_SIMPLE}
description={ description={
track?.manualQueryUrl track?.queryError
? track.queryError
: track?.manualQueryUrl
? '暂无实时路由节点,可使用上方物流查询链接' ? '暂无实时路由节点,可使用上方物流查询链接'
: '暂无路由信息,请稍后刷新' : '暂无路由信息,请稍后刷新'
} }
@@ -0,0 +1,150 @@
import { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Button, Popconfirm, Space, Table, Typography, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { PartnerAssocSummary, PartnerAssocUserItem } from '@dukang/shared-types';
import { request, type HqProfile, type Paginated } from '../lib/api';
import { fmtTime } from '../lib/constants';
function formatNicknameWithRemark(row: PartnerAssocUserItem) {
const name = row.nickname?.trim() || '—';
const remark = row.hqRemark?.trim();
return remark ? `${name}${remark}` : name;
}
type PartnerAssocPanelProps = {
partnerId: string;
};
export default function PartnerAssocPanel({ partnerId }: PartnerAssocPanelProps) {
const [summary, setSummary] = useState<PartnerAssocSummary | null>(null);
const [users, setUsers] = useState<PartnerAssocUserItem[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [issuing, setIssuing] = useState(false);
const [canEditAssoc, setCanEditAssoc] = useState(false);
const loadSummary = useCallback(async () => {
const data = await request<PartnerAssocSummary>(`/admin/partners/${partnerId}/assoc`);
setSummary(data);
}, [partnerId]);
const loadUsers = useCallback(async (p = 1) => {
setLoading(true);
try {
const res = await request<Paginated<PartnerAssocUserItem>>(
`/admin/partners/${partnerId}/assoc/users?page=${p}&pageSize=20`,
);
setUsers(res.items ?? []);
setTotal(res.total ?? 0);
setPage(p);
} finally {
setLoading(false);
}
}, [partnerId]);
useEffect(() => {
void request<HqProfile>('/admin/auth/me')
.then((p) => setCanEditAssoc((p.permissionKeys ?? []).includes('users_partner_assoc')))
.catch(() => setCanEditAssoc(false));
}, []);
useEffect(() => {
void loadSummary().catch((e) => message.error(e instanceof Error ? e.message : '加载关联码失败'));
void loadUsers(1).catch(() => undefined);
}, [loadSummary, loadUsers]);
async function reissue() {
setIssuing(true);
try {
await request(`/admin/partners/${partnerId}/assoc/qrcode`, { method: 'POST' });
message.success('已重新生成关联码');
await loadSummary();
} catch (e) {
message.error(e instanceof Error ? e.message : '生成失败');
} finally {
setIssuing(false);
}
}
async function unbind(userId: string) {
try {
await request(`/admin/partners/${partnerId}/assoc/users/${userId}/unbind`, { method: 'POST' });
message.success('已解绑');
await Promise.all([loadSummary(), loadUsers(page)]);
} catch (e) {
message.error(e instanceof Error ? e.message : '解绑失败');
}
}
const columns: ColumnsType<PartnerAssocUserItem> = [
{ title: '用户编号', dataIndex: 'userNo', width: 140 },
{
title: '用户',
dataIndex: 'nickname',
render: (_, row) => (
<Link
className="admin-primary-link"
to={`/users?userId=${encodeURIComponent(row.id)}`}
title="在用户列表中查看"
>
{formatNicknameWithRemark(row)}
</Link>
),
},
{ title: '手机', dataIndex: 'phone', render: (v) => v || '—' },
{ title: '关联时间', dataIndex: 'boundAt', render: (v) => (v ? fmtTime(v) : '—') },
{ title: '已付订单', dataIndex: 'orderCount', width: 90 },
...(canEditAssoc
? [
{
title: '操作',
width: 90,
render: (_: unknown, row: PartnerAssocUserItem) => (
<Popconfirm title="解绑后该用户新单不再计订单佣金" onConfirm={() => void unbind(row.id)}>
<Button type="link" size="small" danger>
</Button>
</Popconfirm>
),
} satisfies ColumnsType<PartnerAssocUserItem>[number],
]
: []),
];
return (
<div>
<Space align="start" style={{ marginBottom: 16 }} wrap>
{summary?.qrcodeUrl ? (
<img src={summary.qrcodeUrl} alt="关联码" style={{ width: 160, height: 160, background: '#fff' }} />
) : (
<Typography.Text type="secondary"></Typography.Text>
)}
<div>
<Typography.Paragraph style={{ marginBottom: 8 }}>
<Link to={`/users?assocPartnerAccountId=${encodeURIComponent(partnerId)}`}>
{summary?.userCount ?? 0}
</Link>
</Typography.Paragraph>
<Button loading={issuing} onClick={() => void reissue()}>
{summary?.qrcodeUrl ? '补发关联码' : '生成关联码'}
</Button>
</div>
</Space>
<Table
rowKey="id"
size="small"
loading={loading}
columns={columns}
dataSource={users}
pagination={{
current: page,
pageSize: 20,
total,
onChange: (p) => void loadUsers(p),
}}
/>
</div>
);
}
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { import {
Button, Image, Input, InputNumber, Modal, Radio, Select, Space, Switch, Table, Typography, message, Button, Image, Input, InputNumber, Modal, Radio, Select, Space, Switch, Table, Typography, message,
} from 'antd'; } from 'antd';
@@ -50,34 +50,9 @@ function keyOf(ids: string[]) {
return [...ids].sort().join('_'); return [...ids].sort().join('_');
} }
type Props = { function normalizeSkuRows(initialSkus: SkuRow[]): SkuRow[] {
productId: string; if (!initialSkus.length) {
initialAttrs: SpecAttr[]; return [
initialSkus: SkuRow[];
onSaved: () => void;
};
export default function ProductSpecsEditor({ productId, initialAttrs, initialSkus, onSaved }: Props) {
const [attrs, setAttrs] = useState<SpecAttr[]>(
initialAttrs.length
? initialAttrs
: [],
);
const [skus, setSkus] = useState<SkuRow[]>(
initialSkus.length
? initialSkus.map((s) => ({
...s,
specValueIds: s.specValueIds ?? [],
status: s.status || 'ON_SALE',
allowOnlinePurchase: s.allowOnlinePurchase !== false,
allowCrossCityDelivery: s.allowCrossCityDelivery !== false,
allowOnSitePickup: !!s.allowOnSitePickup,
saleUnit: s.saleUnit === 'BOX' ? 'BOX' : 'BOTTLE',
bottlesPerUnit: s.bottlesPerUnit || (s.saleUnit === 'BOX' ? 6 : 1),
isDefault: !!s.isDefault,
imageUrl: s.imageUrl ?? '',
}))
: [
{ {
specValueIds: [], specValueIds: [],
barcode69: '', barcode69: '',
@@ -91,11 +66,43 @@ export default function ProductSpecsEditor({ productId, initialAttrs, initialSku
isDefault: true, isDefault: true,
imageUrl: '', imageUrl: '',
}, },
], ];
); }
return initialSkus.map((s) => ({
...s,
specValueIds: s.specValueIds ?? [],
status: s.status || 'ON_SALE',
allowOnlinePurchase: s.allowOnlinePurchase !== false,
allowCrossCityDelivery: s.allowCrossCityDelivery !== false,
allowOnSitePickup: !!s.allowOnSitePickup,
saleUnit: s.saleUnit === 'BOX' ? 'BOX' : 'BOTTLE',
bottlesPerUnit: s.bottlesPerUnit || (s.saleUnit === 'BOX' ? 6 : 1),
isDefault: !!s.isDefault,
imageUrl: s.imageUrl ?? '',
}));
}
type Props = {
productId: string;
initialAttrs: SpecAttr[];
initialSkus: SkuRow[];
onSaved: () => void;
};
export default function ProductSpecsEditor({ productId, initialAttrs, initialSkus, onSaved }: Props) {
const [attrs, setAttrs] = useState<SpecAttr[]>(() => (initialAttrs.length ? initialAttrs : []));
const [skus, setSkus] = useState<SkuRow[]>(() => normalizeSkuRows(initialSkus));
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [editIndex, setEditIndex] = useState<number | null>(null); const [editIndex, setEditIndex] = useState<number | null>(null);
useEffect(() => {
setAttrs(initialAttrs.length ? initialAttrs : []);
setSkus(normalizeSkuRows(initialSkus));
setEditIndex(null);
// 仅切商品时重载,避免父组件重渲染冲掉编辑中内容
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [productId]);
const combos = useMemo(() => cartesian(attrs.filter((a) => a.name.trim() && a.values.some((v) => v.name.trim()))), [attrs]); const combos = useMemo(() => cartesian(attrs.filter((a) => a.name.trim() && a.values.some((v) => v.name.trim()))), [attrs]);
function regenerateMatrix() { function regenerateMatrix() {
@@ -54,6 +54,7 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
const [skuId, setSkuId] = useState<string>(); const [skuId, setSkuId] = useState<string>();
const [quantity, setQuantity] = useState(2); const [quantity, setQuantity] = useState(2);
const [promoCodeId, setPromoCodeId] = useState<string>(); const [promoCodeId, setPromoCodeId] = useState<string>();
const [assocPartnerAccountId, setAssocPartnerAccountId] = useState<string>();
const [deliveryMode, setDeliveryMode] = useState<PartnerProxyDeliveryMode>('ADDRESS'); const [deliveryMode, setDeliveryMode] = useState<PartnerProxyDeliveryMode>('ADDRESS');
const [autoReceive, setAutoReceive] = useState(false); const [autoReceive, setAutoReceive] = useState(false);
const [preview, setPreview] = useState<PartnerProxyOrderPreviewResult | null>(null); const [preview, setPreview] = useState<PartnerProxyOrderPreviewResult | null>(null);
@@ -168,6 +169,7 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
setProductId(undefined); setProductId(undefined);
setSkuId(undefined); setSkuId(undefined);
setPromoCodeId(undefined); setPromoCodeId(undefined);
setAssocPartnerAccountId(undefined);
setDeliveryMode('ADDRESS'); setDeliveryMode('ADDRESS');
setAutoReceive(false); setAutoReceive(false);
setPreview(null); setPreview(null);
@@ -235,6 +237,7 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
quantity, quantity,
promoCodeId: promoCodeId || undefined, promoCodeId: promoCodeId || undefined,
skuId: skuId || undefined, skuId: skuId || undefined,
assocPartnerAccountId: assocPartnerAccountId || undefined,
}; };
setSubmitting(true); setSubmitting(true);
@@ -388,6 +391,21 @@ export default function ProxyOrderModal({ open, onClose, onSuccess }: ProxyOrder
/> />
</Form.Item> </Form.Item>
<Form.Item label="关联合伙人(选填)">
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="不选则本单不计订单佣金"
value={assocPartnerAccountId}
onChange={setAssocPartnerAccountId}
options={(options?.partners ?? []).map((p) => ({
value: p.id,
label: `${p.companyName || p.name}${p.phone ? ` · ${p.phone}` : ''}`,
}))}
/>
</Form.Item>
{(options?.promoCodes.length ?? 0) > 0 ? ( {(options?.promoCodes.length ?? 0) > 0 ? (
<Form.Item label="绑定推广码(选填)"> <Form.Item label="绑定推广码(选填)">
<Select <Select
@@ -15,7 +15,13 @@ type Props = {
export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone = false }: Props) { export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone = false }: Props) {
const user = detail.user as const user = detail.user as
| { userNo?: string; nickname?: string | null; phone?: string | null } | {
id?: string;
userNo?: string;
nickname?: string | null;
phone?: string | null;
hqRemark?: string | null;
}
| undefined; | undefined;
const store = detail.store as const store = detail.store as
| { | {
@@ -41,7 +47,13 @@ export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone =
<Descriptions.Item label="结算额">¥{Number(detail.settleAmount ?? 0).toFixed(2)}</Descriptions.Item> <Descriptions.Item label="结算额">¥{Number(detail.settleAmount ?? 0).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt ?? ''))}</Descriptions.Item> <Descriptions.Item label="时间">{fmtTime(String(detail.createdAt ?? ''))}</Descriptions.Item>
<Descriptions.Item label="用户编号">{user?.userNo ?? '—'}</Descriptions.Item> <Descriptions.Item label="用户编号">{user?.userNo ?? '—'}</Descriptions.Item>
<Descriptions.Item label="用户昵称">{user?.nickname?.trim() || '—'}</Descriptions.Item> <Descriptions.Item label="用户昵称">
{(() => {
const name = user?.nickname?.trim() || '—';
const remark = user?.hqRemark?.trim();
return remark ? `${name}${remark}` : name;
})()}
</Descriptions.Item>
<Descriptions.Item label="用户手机"> <Descriptions.Item label="用户手机">
{maskUserPhone ? maskPhone(user?.phone) : user?.phone || '—'} {maskUserPhone ? maskPhone(user?.phone) : user?.phone || '—'}
</Descriptions.Item> </Descriptions.Item>
@@ -91,6 +103,9 @@ export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone =
<Descriptions.Item label="评价"> <Descriptions.Item label="评价">
{(detail.rating as { serviceScore?: number }).serviceScore ?? '—'} / {' '} {(detail.rating as { serviceScore?: number }).serviceScore ?? '—'} / {' '}
{(detail.rating as { envScore?: number }).envScore ?? '—'} {(detail.rating as { envScore?: number }).envScore ?? '—'}
{(detail.rating as { comment?: string | null }).comment
? ` · ${(detail.rating as { comment?: string }).comment}`
: ''}
</Descriptions.Item> </Descriptions.Item>
) : null} ) : null}
</Descriptions> </Descriptions>
+36 -23
View File
@@ -19,8 +19,13 @@ import {
SettingOutlined, SettingOutlined,
AccountBookOutlined, AccountBookOutlined,
ProjectOutlined, ProjectOutlined,
PictureOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { hasAnySystemSettingsPermission, hasAnyStoreMenuPermission } from '@dukang/shared-types'; import {
hasAnySystemSettingsPermission,
hasAnyStoreMenuPermission,
HQ_ADMIN_ROLES,
} from '@dukang/shared-types';
import { clearAuth, request, type HqProfile } from '../lib/api'; import { clearAuth, request, type HqProfile } from '../lib/api';
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title'; import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events'; import { AUDIT_NOTICE_CHANGED_EVENT, PACKAGE_AUDIT_CHANGED_EVENT } from '../lib/admin-events';
@@ -28,12 +33,15 @@ import { ListColumnPrefsProvider } from '../lib/ListColumnPrefsContext';
const { Header, Sider, Content } = Layout; const { Header, Sider, Content } = Layout;
const HQ_ROLE_LABELS: Record<string, string> = Object.fromEntries(
HQ_ADMIN_ROLES.map((r) => [r.value, r.label]),
);
type MenuItem = NonNullable<MenuProps['items']>[number]; type MenuItem = NonNullable<MenuProps['items']>[number];
const MENU_ITEMS: MenuProps['items'] = [ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/', icon: <DashboardOutlined />, label: '概览' }, { key: '/', icon: <DashboardOutlined />, label: '概览' },
{ key: '/users', icon: <UserOutlined />, label: '用户' }, { key: '/users', icon: <UserOutlined />, label: '用户' },
{ key: '/wechat-bindings', icon: <UserOutlined />, label: '微信绑定' },
{ {
key: 'products-group', key: 'products-group',
icon: <ShoppingOutlined />, icon: <ShoppingOutlined />,
@@ -44,18 +52,17 @@ const MENU_ITEMS: MenuProps['items'] = [
], ],
}, },
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' }, { key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
{ {
key: 'wecom-group', key: 'partners-group',
icon: <TeamOutlined />, icon: <TeamOutlined />,
label: '企微机器人', label: '开城',
children: [ children: [
{ key: '/wecom/bots', label: '智能机器人' }, { key: '/cities', label: '城市' },
{ key: '/wecom/pushes', label: '消息推送' }, { key: '/city-partners', label: '城市合伙人' },
{ key: '/city-warehouses', label: '仓库' },
{ key: '/fulfillment-providers', label: '仓配管理' },
], ],
}, },
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
{ {
key: 'stores-group', key: 'stores-group',
icon: <ShopOutlined />, icon: <ShopOutlined />,
@@ -69,17 +76,6 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/store-media', label: '门店资源' }, { key: '/store-media', label: '门店资源' },
], ],
}, },
{
key: 'partners-group',
icon: <TeamOutlined />,
label: '开城',
children: [
{ key: '/cities', label: '城市' },
{ key: '/city-partners', label: '城市合伙人' },
{ key: '/city-warehouses', label: '仓库' },
{ key: '/fulfillment-providers', label: '仓配管理' },
],
},
{ {
key: 'finance-group', key: 'finance-group',
icon: <AccountBookOutlined />, icon: <AccountBookOutlined />,
@@ -121,6 +117,21 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/tickets/support', label: '技术支持' }, { key: '/tickets/support', label: '技术支持' },
], ],
}, },
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票' },
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
{ key: '/activity-posters', icon: <PictureOutlined />, label: '活动图' },
{ key: '/wechat-bindings', icon: <UserOutlined />, label: '微信绑定' },
{
key: 'wecom-group',
icon: <TeamOutlined />,
label: '企微机器人',
children: [
{ key: '/wecom/bots', label: '智能机器人' },
{ key: '/wecom/pushes', label: '消息推送' },
],
},
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
{ {
key: 'dev-plan-group', key: 'dev-plan-group',
icon: <ProjectOutlined />, icon: <ProjectOutlined />,
@@ -131,7 +142,6 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/dev-plan/settings', label: '开发设置' }, { key: '/dev-plan/settings', label: '开发设置' },
], ],
}, },
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票管理' },
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' }, { key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
{ {
key: 'logs-group', key: 'logs-group',
@@ -148,9 +158,9 @@ const MENU_ITEMS: MenuProps['items'] = [
], ],
}, },
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' }, { key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
{ key: '/hq-accounts', icon: <SafetyOutlined />, label: 'HQ账户' },
{ key: '/test-whitelist', icon: <SafetyOutlined />, label: '白名单管理' }, { key: '/test-whitelist', icon: <SafetyOutlined />, label: '白名单管理' },
{ key: '/system-settings', icon: <SettingOutlined />, label: '系统设置' }, { key: '/system-settings', icon: <SettingOutlined />, label: '系统设置' },
{ key: '/hq-accounts', icon: <SafetyOutlined />, label: 'HQ账户' },
]; ];
function menuAllowed(key: string, permissionKeys: string[]): boolean { function menuAllowed(key: string, permissionKeys: string[]): boolean {
@@ -172,6 +182,7 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
'/product-detail-templates': 'products', '/product-detail-templates': 'products',
'/orders': 'orders', '/orders': 'orders',
'/promo-codes': 'promo_codes', '/promo-codes': 'promo_codes',
'/activity-posters': 'activity_posters',
'/wecom/bots': 'wecom_bots', '/wecom/bots': 'wecom_bots',
'/wecom/pushes': 'wecom_bots', '/wecom/pushes': 'wecom_bots',
'wecom-group': 'wecom_bots', 'wecom-group': 'wecom_bots',
@@ -405,7 +416,9 @@ export default function AdminLayout() {
</Typography.Title> </Typography.Title>
<Space> <Space>
<span>{profile?.name || '—'}</span> <span>{profile?.name || '—'}</span>
<span style={{ color: '#999' }}>{profile?.adminRole}</span> <span style={{ color: '#999' }}>
{HQ_ROLE_LABELS[profile?.adminRole ?? ''] || profile?.adminRole || ''}
</span>
<Button type="text" icon={<LogoutOutlined />} onClick={logout}> <Button type="text" icon={<LogoutOutlined />} onClick={logout}>
退 退
</Button> </Button>
@@ -35,7 +35,11 @@ export function ListColumnPrefsProvider({
`/admin/me/list-columns/${listKey}`, `/admin/me/list-columns/${listKey}`,
{ {
method: 'PUT', method: 'PUT',
body: JSON.stringify(next ? { order: next.order, hidden: next.hidden } : { reset: true }), body: JSON.stringify(
next
? { order: next.order, hidden: next.hidden, widths: next.widths }
: { reset: true },
),
}, },
); );
setPrefs(res.listColumnPrefs ?? {}); setPrefs(res.listColumnPrefs ?? {});
+10 -1
View File
@@ -183,6 +183,12 @@ export type AdminUserRow = {
benefitUsedAmount?: number; benefitUsedAmount?: number;
/** 好客权益·剩余未使用 */ /** 好客权益·剩余未使用 */
benefitBalance?: number; benefitBalance?: number;
assocPartner?: {
id: string;
name: string;
companyName?: string | null;
phone?: string | null;
} | null;
}; };
export type AdminOrderItem = { export type AdminOrderItem = {
@@ -202,6 +208,7 @@ export type AdminOrderRow = {
productName?: string; productName?: string;
productSpec?: string; productSpec?: string;
quantity?: number; quantity?: number;
saleUnit?: string;
receiverName: string; receiverName: string;
receiverPhone: string; receiverPhone: string;
receiverProvince?: string; receiverProvince?: string;
@@ -228,12 +235,14 @@ export type AdminOrderRow = {
proxyPartnerName?: string | null; proxyPartnerName?: string | null;
proxyPartnerPhone?: string | null; proxyPartnerPhone?: string | null;
isTest?: boolean; isTest?: boolean;
user?: { id: string; userNo: string; phone: string | null; nickname: string | null }; user?: { id: string; userNo: string; phone: string | null; nickname: string | null; hqRemark?: string | null };
delivery?: { delivery?: {
provider: string; provider: string;
trackingNo: string | null; trackingNo: string | null;
providerOrderNo: string | null; providerOrderNo: string | null;
logisticsCompany?: string | null; logisticsCompany?: string | null;
manualQueryUrl?: string | null; manualQueryUrl?: string | null;
/** 当次应付物流费(按瓶当量 × 承运商计价) */
logisticsFee?: number | null;
}; };
}; };
+67
View File
@@ -0,0 +1,67 @@
import type { MouseEvent, ReactNode } from 'react';
import type { ColumnType } from 'antd/es/table';
export const MIN_COL_WIDTH = 48;
export const MAX_COL_WIDTH = 960;
export function clampColWidth(n: number): number {
return Math.min(MAX_COL_WIDTH, Math.max(MIN_COL_WIDTH, Math.round(n)));
}
export function beginColumnResize(
e: MouseEvent,
startWidth: number,
onMove: (width: number) => void,
onEnd: (width: number) => void,
) {
e.preventDefault();
e.stopPropagation();
const startX = e.clientX;
let latest = clampColWidth(startWidth);
let moved = false;
document.body.classList.add('admin-col-resizing');
const onMouseMove = (ev: globalThis.MouseEvent) => {
moved = true;
latest = clampColWidth(startWidth + ev.clientX - startX);
onMove(latest);
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
document.body.classList.remove('admin-col-resizing');
if (moved) onEnd(latest);
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
export function withResizeTitle<T>(
title: ColumnType<T>['title'],
onMouseDown: (e: MouseEvent) => void,
): ColumnType<T>['title'] {
const handle: ReactNode = (
<span
role="separator"
aria-orientation="vertical"
aria-label="拖动调整列宽"
className="admin-col-resize-handle"
onClick={(ev) => ev.stopPropagation()}
onMouseDown={onMouseDown}
/>
);
if (typeof title === 'function') {
return (props) => (
<>
{title(props)}
{handle}
</>
);
}
return (
<>
{title}
{handle}
</>
);
}
+16
View File
@@ -7,6 +7,12 @@ export const DELIVERY_PROVIDER_LABELS: Record<string, string> = {
MANUAL: '手动', MANUAL: '手动',
}; };
export const DELIVERY_TYPE_LABELS: Record<string, string> = {
LOCAL: '同城',
CROSS_CITY: '跨城',
ON_SITE_PICKUP: '现场提货',
};
export const ORDER_STATUS_LABELS: Record<string, string> = { export const ORDER_STATUS_LABELS: Record<string, string> = {
PENDING_PAY: '待付款', PENDING_PAY: '待付款',
PENDING_SHIP: '待发货', PENDING_SHIP: '待发货',
@@ -25,9 +31,18 @@ export const ORDER_STATUS_OPERATOR_LABELS: Record<string, string> = {
USER_ON_SITE: '用户·现场取货', USER_ON_SITE: '用户·现场取货',
USER_WECHAT_CONFIRM: '用户·微信确认收货', USER_WECHAT_CONFIRM: '用户·微信确认收货',
WECHAT_TRADE_MANAGE: '微信结算同步', WECHAT_TRADE_MANAGE: '微信结算同步',
WECHAT_PAY: '微信支付',
MOCK: 'Mock', MOCK: 'Mock',
MOCK_PAY: 'Mock 支付', MOCK_PAY: 'Mock 支付',
SYSTEM: '系统', SYSTEM: '系统',
SYSTEM_AUTO_EXPIRE: '系统·超时取消',
PARTNER_PROXY: '合伙人代下单',
HQ_PROXY: 'HQ 代操作',
HQ_LOGISTICS: 'HQ 物流',
WAREHOUSE_MANUAL: '仓库手工',
HQ: '总部',
STORE: '门店',
PARTNER: '合伙人',
}; };
/** 订单状态 Tag 颜色(Ant Design preset */ /** 订单状态 Tag 颜色(Ant Design preset */
@@ -105,6 +120,7 @@ export const RESOURCE_BIZ_TYPE_LABELS: Record<string, string> = {
QRCODE: '二维码', QRCODE: '二维码',
SIGN_PHOTO: '签收照', SIGN_PHOTO: '签收照',
VIDEO: '视频', VIDEO: '视频',
ACTIVITY_POSTER: '活动图',
}; };
export const RESOURCE_STATUS_LABELS: Record<string, string> = { export const RESOURCE_STATUS_LABELS: Record<string, string> = {
+359
View File
@@ -0,0 +1,359 @@
import {
LEDGER_TYPE_LABELS,
ORDER_STATUS_LABELS,
ORDER_STATUS_OPERATOR_LABELS,
} from './constants';
import { HQ_OPERATION_ACTION_LABELS } from './hq-log';
import { USER_LOG_CATEGORY_LABELS } from './user-log';
import {
PARTNER_LOG_CATEGORY_LABELS,
HQ_ADMIN_ROLES,
resolvePartnerLogCategory,
resolveStoreLogCategory,
resolveUserLogCategory,
STORE_LOG_CATEGORY_LABELS,
WECOM_BOT_PERMISSION_LABELS,
} from '@dukang/shared-types';
export function zhLabel(dict: Record<string, string>, value?: string | null, empty = '—'): string {
if (value == null || value === '') return empty;
return dict[value] ?? value;
}
export const CLIENT_APP_LABELS: Record<string, string> = {
USER_MINI: 'C 端小程序',
USER_H5: 'C 端 H5',
PARTNER_MINI: '合伙人小程序',
PARTNER_H5: '合伙人 H5',
HQ_MINI: 'HQ 小程序',
HQ_WEB: 'HQ 后台',
SHOP_H5: '门店 H5',
};
export const REF_TYPE_LABELS: Record<string, string> = {
ORDER: '订单',
USER: '用户',
STORE: '门店',
PARTNER: '合伙人',
CITY: '城市',
PRODUCT: '商品',
COUPON: '权益券',
TICKET: '工单',
SUPPORT_TICKET: '技术支持工单',
INVOICE: '发票',
PROMO: '推广码',
PROMO_CODE: '推广码',
ACTIVITY_POSTER: '活动图',
HQ: '总部',
HQ_ACCOUNT: 'HQ 账号',
STORE_ACCOUNT: '门店账号',
PARTNER_ACCOUNT: '合伙人账号',
PAYOUT: '打款',
WITHDRAWAL: '提现',
BILL: '账单',
DELIVERY: '配送单',
REDEEM: '核销',
WAREHOUSE: '仓库',
PACKAGE: '套餐',
};
export const DOMAIN_EVENT_TYPE_LABELS: Record<string, string> = {
ORDER_STATUS: '订单状态',
BENEFIT_LEDGER: '权益流水',
STORE_AUDIT: '门店审核',
TICKET_COLLAB: '工单协作',
PROMO_TOUCH: '推广触达',
HQ_OPERATION: 'HQ 操作',
};
export const PARAM_DESC_LABELS: Record<string, string> = {
from_status: '原状态',
to_status: '目标状态',
operator: '操作人',
ledger_type: '流水类型',
coupon_id: '权益券 ID',
action: '行为',
target_type: '对象类型',
target_id: '对象 ID',
};
export const USER_LOG_EVENT_LABELS: Record<string, string> = {
login_success: '登录成功',
sms_login: '短信登录',
sms_send: '发送验证码',
sms_verify_fail: '验证码校验失败',
session_start: '会话开始',
home_view: '浏览首页',
product_list_view: '浏览商品列表',
product_click: '点击商品',
product_detail_view: '浏览商品详情',
order_confirm_view: '浏览确认订单',
order_submit: '提交订单',
order_list_view: '浏览订单列表',
order_detail_view: '浏览订单详情',
order_cancel: '取消订单',
pay_page_view: '进入支付页',
pay_success: '支付成功',
pay_fail: '支付失败',
wechat_login: '微信登录',
wechat_phone: '微信授权手机号',
wechat_phone_login: '微信手机号登录',
wechat_location: '微信定位',
wechat_album: '微信选图',
wechat_bind: '绑定微信',
store_list_view: '浏览门店列表',
store_detail_view: '浏览门店详情',
benefit_page_view: '浏览权益页',
benefit_detail_view: '浏览权益详情',
benefit_redeem_start: '开始核销',
benefit_redeem_success: '核销成功',
redeem_code_view: '查看核销码',
redeem_success_view: '核销成功页',
profile_update: '修改资料',
bind_phone: '绑定手机号',
address_list_view: '浏览地址列表',
address_edit: '编辑地址',
promo_touch: '推广触达',
promo_share: '分享推广',
cs_contact: '联系客服',
after_sale_list_view: '浏览售后列表',
after_sale_apply: '申请售后',
client_error: '前端异常',
};
export const STORE_LOG_EVENT_LABELS: Record<string, string> = {
store_sms_send: '发送验证码',
store_sms_login: '短信登录',
store_sms_verify_fail: '验证码校验失败',
store_login_success: '登录成功',
store_select: '选择门店',
store_wechat_login: '微信登录',
store_wechat_bind: '绑定微信',
store_home_view: '浏览首页',
store_redeem_entry_view: '进入核销页',
store_redeem_confirm_view: '核销确认页',
store_phone_redeem_view: '手机号核销页',
store_records_view: '浏览核销记录',
store_withdraw_view: '浏览提现页',
store_packages_view: '浏览套餐页',
store_mine_view: '浏览我的',
store_staff_view: '浏览子账号',
store_redeem_preview: '核销预览',
store_redeem_confirm: '确认核销',
store_redeem_confirm_fail: '核销失败',
store_redeem_weaknet_threshold: '弱网阈值',
store_redeem_pending_submit: '提交挂起核销',
store_redeem_pending_complete: '完成挂起核销',
store_redeem_pending_reject: '驳回挂起核销',
store_redeem_phone_lookup_sms: '手机号核销发码',
store_redeem_phone_balance: '查询用户权益余额',
store_redeem_phone_prepare: '手机号核销准备',
store_redeem_scan_start: '扫码核销开始',
store_payout_created: '生成打款单',
store_payout_paid: '打款完成',
store_withdraw_applied: '申请提现',
store_withdraw_paid: '提现已打款',
store_status_change: '变更营业状态',
store_staff_create: '新增子账号',
store_staff_update: '编辑子账号',
store_staff_delete: '删除子账号',
store_staff_permission_update: '更新子账号权限',
store_package_apply: '申请套餐',
store_package_audit_view: '查看套餐审核',
};
export const PARTNER_LOG_EVENT_LABELS: Record<string, string> = {
partner_sms_send: '发送验证码',
partner_sms_login: '短信登录',
partner_sms_verify_fail: '验证码校验失败',
partner_login_success: '登录成功',
partner_wechat_login: '微信登录',
partner_wechat_bind: '绑定微信',
partner_home_view: '浏览首页',
partner_store_list_view: '浏览门店列表',
partner_store_detail_view: '浏览门店详情',
partner_store_create_view: '进入录店页',
partner_order_list_view: '浏览订单列表',
partner_order_detail_view: '浏览订单详情',
partner_proxy_order_view: '进入代下单页',
partner_bills_view: '浏览账单列表',
partner_bill_detail_view: '浏览账单详情',
partner_staff_list_view: '浏览子账号',
partner_leaderboard_view: '浏览排行榜',
partner_weekly_report_view: '浏览周报',
partner_staff_create: '新增子账号',
partner_staff_sms_send: '子账号发验证码',
partner_staff_sms_verify_fail: '子账号验证码失败',
partner_staff_update: '编辑子账号',
partner_staff_delete: '删除子账号',
partner_staff_permission_update: '更新子账号权限',
partner_store_create: '录入门店',
partner_store_status_change: '变更门店状态',
partner_store_audit_approved: '门店审核通过',
partner_store_audit_rejected: '门店审核驳回',
partner_order_ship: '订单发货',
partner_delivery_advance: '推进配送',
partner_proxy_order_create: '代下单',
partner_bill_view: '查看账单',
partner_bill_confirm: '确认账单',
partner_warehouse_view: '浏览仓库',
partner_warehouse_update: '更新仓库',
};
export const EVENT_NAME_LABELS: Record<string, string> = {
...USER_LOG_EVENT_LABELS,
...STORE_LOG_EVENT_LABELS,
...PARTNER_LOG_EVENT_LABELS,
};
export const THIRD_PARTY_PROVIDER_LABELS: Record<string, string> = {
WECHAT_AUTH: '微信授权',
WECHAT_PAY: '微信支付',
WECHAT_REFUND: '微信退款',
WECHAT_MAP: '微信/腾讯地图',
ALIYUN_OSS: '阿里云 OSS',
ALIYUN_SMS: '阿里云短信',
MOCK_SMS: 'Mock 短信',
SMS: '短信',
XFX: '小飞侠',
LOGISTICS: '物流快递',
MANUAL: '手动',
};
export const THIRD_PARTY_STATUS_LABELS: Record<string, string> = {
SUCCESS: '成功',
FAILED: '失败',
PENDING: '处理中',
};
export const THIRD_PARTY_SCENE_LABELS: Record<string, string> = {
LOGIN: '登录',
USERINFO: '用户信息',
JSSDK_CONFIG: 'JSSDK 配置',
BIND_PHONE: '绑定手机号',
GET_LOCATION: '获取定位',
CHOOSE_IMAGE: '选择图片',
ORDER_PAY: '订单支付',
ORDER_REFUND: '订单退款',
UPLOAD_SHIPPING: '上传发货信息',
TRADE_MANAGE_PUSH: '交易结算推送',
ORDER_DISPATCH: '配送下单',
ORDER_DISPATCH_HOLD: '配送暂不下发',
TRACK_CALLBACK: '物流回调',
UPLOAD_TOKEN: '上传凭证',
UPLOAD_PUT_OBJECT: '上传文件',
GEOCODE: '地理编码',
REVERSE_GEOCODE: '逆地理编码',
};
export const WECOM_BOT_ACTION_LABELS: Record<string, string> = {
...WECOM_BOT_PERMISSION_LABELS,
'user.read_sms.start': '查询用户·发送验证码',
'user.read_sms.verify': '查询用户·校验验证码',
};
export const GENERIC_STATUS_LABELS: Record<string, string> = {
...ORDER_STATUS_LABELS,
...LEDGER_TYPE_LABELS,
...THIRD_PARTY_STATUS_LABELS,
PENDING: '待处理',
APPROVED: '已通过',
REJECTED: '已驳回',
ACTIVE: '正常',
DISABLED: '停用',
SUCCESS: '成功',
FAILED: '失败',
OPEN: '营业中',
PAUSED: '已暂停',
CLOSED: '已关闭',
};
export const HQ_ROLE_LABELS: Record<string, string> = Object.fromEntries(
HQ_ADMIN_ROLES.map((r) => [r.value, r.label]),
);
const CODE_ZH: Record<string, string> = {
...CLIENT_APP_LABELS,
...REF_TYPE_LABELS,
...DOMAIN_EVENT_TYPE_LABELS,
...EVENT_NAME_LABELS,
...ORDER_STATUS_LABELS,
...ORDER_STATUS_OPERATOR_LABELS,
...LEDGER_TYPE_LABELS,
...HQ_OPERATION_ACTION_LABELS,
...HQ_ROLE_LABELS,
...THIRD_PARTY_PROVIDER_LABELS,
...THIRD_PARTY_STATUS_LABELS,
...THIRD_PARTY_SCENE_LABELS,
...WECOM_BOT_ACTION_LABELS,
...GENERIC_STATUS_LABELS,
...PARAM_DESC_LABELS,
};
export function zhCode(value?: string | null, empty = '—'): string {
if (value == null || value === '') return empty;
return CODE_ZH[value] ?? value;
}
export function eventNameLabel(value?: string | null): string {
return zhLabel(EVENT_NAME_LABELS, value);
}
export function clientAppLabel(value?: string | null): string {
return zhLabel(CLIENT_APP_LABELS, value);
}
export function formatRef(refType?: string | null, refId?: string | null): string {
if (!refType && !refId) return '—';
const type = zhLabel(REF_TYPE_LABELS, refType, refType || '');
return refId ? `${type} #${refId}` : type;
}
export function userEventCategoryLabel(eventName: string, category?: string | null): string {
const key = category || resolveUserLogCategory(eventName);
if (key && USER_LOG_CATEGORY_LABELS[key]) return USER_LOG_CATEGORY_LABELS[key];
return '其他';
}
export function storeEventCategoryLabel(eventName: string, category?: string | null): string {
const key = category || resolveStoreLogCategory(eventName);
const labels = STORE_LOG_CATEGORY_LABELS as Record<string, string>;
if (key && labels[key]) return labels[key];
return '其他';
}
export function partnerEventCategoryLabel(eventName: string, category?: string | null): string {
const key = category || resolvePartnerLogCategory(eventName);
const labels = PARTNER_LOG_CATEGORY_LABELS as Record<string, string>;
if (key && labels[key]) return labels[key];
return '其他';
}
export function domainParamFieldLabel(desc?: string | null, fallbackIndex?: 1 | 2 | 3): string {
if (desc && PARAM_DESC_LABELS[desc]) return PARAM_DESC_LABELS[desc];
if (fallbackIndex) return `参数${fallbackIndex}`;
return '参数';
}
export function zhRemark(value?: string | null): string {
if (!value) return '—';
return value
.replace(/partnerAccountId=/g, '合伙人账号=')
.replace(/hqAccountId=/g, 'HQ账号=')
.replace(/deliveryMode=/g, '履约方式=')
.replace(/\bmode=/g, '履约方式=')
.replace(/customer=/g, '客户=')
.replace(/\bON_SITE_PICKUP\b/g, '现场提货')
.replace(/\bCROSS_CITY\b/g, '跨城')
.replace(/\bLOCAL\b/g, '同城');
}
export function domainParamValue(desc?: string | null, value?: string | null): string {
if (value == null || value === '') return '—';
if (desc === 'from_status' || desc === 'to_status') return zhLabel(ORDER_STATUS_LABELS, value);
if (desc === 'operator') return zhLabel(ORDER_STATUS_OPERATOR_LABELS, value);
if (desc === 'ledger_type') return zhLabel(LEDGER_TYPE_LABELS, value);
if (desc === 'action') return zhLabel(HQ_OPERATION_ACTION_LABELS, value);
if (desc === 'target_type') return zhLabel(REF_TYPE_LABELS, value);
return zhCode(value);
}
+5
View File
@@ -16,6 +16,7 @@ export const HQ_OPERATION_ACTION_OPTIONS = [
{ value: 'HQ_ACCOUNT_CREATE', label: '新增 HQ 管理员' }, { value: 'HQ_ACCOUNT_CREATE', label: '新增 HQ 管理员' },
{ value: 'HQ_ACCOUNT_UPDATE', label: '编辑 HQ 管理员' }, { value: 'HQ_ACCOUNT_UPDATE', label: '编辑 HQ 管理员' },
{ value: 'HQ_PERMISSION_UPDATE', label: '配置 HQ 权限' }, { value: 'HQ_PERMISSION_UPDATE', label: '配置 HQ 权限' },
{ value: 'USER_ASSOC_UPDATE', label: '修改用户关联合伙人' },
{ value: 'USER_DELETE', label: '删除用户' }, { value: 'USER_DELETE', label: '删除用户' },
{ value: 'USER_BATCH_DELETE', label: '批量删除用户' }, { value: 'USER_BATCH_DELETE', label: '批量删除用户' },
{ value: 'ORDER_SHIP', label: '订单发货' }, { value: 'ORDER_SHIP', label: '订单发货' },
@@ -60,6 +61,10 @@ export const HQ_OPERATION_ACTION_OPTIONS = [
{ value: 'PARTNER_BILL_BATCH_MARK_PAID', label: '批量合伙人账单结算' }, { value: 'PARTNER_BILL_BATCH_MARK_PAID', label: '批量合伙人账单结算' },
{ value: 'WINERY_BILL_CONFIRM', label: '酒厂对账单确认打款' }, { value: 'WINERY_BILL_CONFIRM', label: '酒厂对账单确认打款' },
{ value: 'WINERY_BILL_BATCH_CONFIRM', label: '批量酒厂对账单打款' }, { value: 'WINERY_BILL_BATCH_CONFIRM', label: '批量酒厂对账单打款' },
{ value: 'ACTIVITY_POSTER_CREATE', label: '新增活动图' },
{ value: 'ACTIVITY_POSTER_UPDATE', label: '编辑活动图' },
{ value: 'ACTIVITY_POSTER_UPDATE_STATUS', label: '活动图上下架' },
{ value: 'ACTIVITY_POSTER_DELETE', label: '删除活动图' },
] as const; ] as const;
export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = Object.fromEntries( export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = Object.fromEntries(
+14 -1
View File
@@ -55,7 +55,20 @@ export function applyColumnPrefs<T>(
const visible = new Set(visibleColumnKeys(defaultKeys, pref)); const visible = new Set(visibleColumnKeys(defaultKeys, pref));
const orderedKeys = mergeColumnOrder(defaultKeys, pref).filter((k) => visible.has(k)); const orderedKeys = mergeColumnOrder(defaultKeys, pref).filter((k) => visible.has(k));
const byKey = new Map(configurable.map((c) => [c.key, c.col])); const byKey = new Map(configurable.map((c) => [c.key, c.col]));
return [...orderedKeys.map((k) => byKey.get(k)!).filter(Boolean), ...actions.map((c) => c.col)]; return [
...orderedKeys
.map((k) => {
const col = byKey.get(k);
if (!col) return null;
const w = pref?.widths?.[k];
return w != null ? { ...col, width: w } : col;
})
.filter((c): c is ColumnType<T> => !!c),
...actions.map((c) => {
const w = pref?.widths?.[c.key];
return w != null ? { ...c.col, width: w } : c.col;
}),
];
} }
export type ListColumnSettingItem = { export type ListColumnSettingItem = {
@@ -0,0 +1,9 @@
/** 表单选填项常为 null,PUT 时去掉以免后端对 null 调 trim */
export function omitNullFields<T extends Record<string, unknown>>(input: T): Partial<T> {
const out: Partial<T> = {};
for (const [key, value] of Object.entries(input)) {
if (value === null || value === undefined) continue;
(out as Record<string, unknown>)[key] = value;
}
return out;
}
+87 -15
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'; import { useCallback, useMemo, useRef, useState } from 'react';
import { Button, message } from 'antd'; import { Button, message } from 'antd';
import { SettingOutlined } from '@ant-design/icons'; import { SettingOutlined } from '@ant-design/icons';
import type { ColumnsType, ColumnType } from 'antd/es/table'; import type { ColumnsType, ColumnType } from 'antd/es/table';
@@ -9,9 +9,11 @@ import {
ACTIONS_COLUMN_KEY, ACTIONS_COLUMN_KEY,
SERIAL_COLUMN_KEY, SERIAL_COLUMN_KEY,
applyColumnPrefs, applyColumnPrefs,
columnKey,
settingItems, settingItems,
type ListColumnSettingItem, type ListColumnSettingItem,
} from './list-column-prefs'; } from './list-column-prefs';
import { beginColumnResize, withResizeTitle } from './column-resize';
type Options = { type Options = {
page?: number; page?: number;
@@ -27,7 +29,13 @@ export function useAdminListColumns<T>(
const { prefs, save } = useListColumnPrefs(); const { prefs, save } = useListColumnPrefs();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [localWidths, setLocalWidths] = useState<Record<string, number>>({});
const pref = prefs[listKey]; const pref = prefs[listKey];
const prefRef = useRef(pref);
prefRef.current = pref;
const localWidthsRef = useRef(localWidths);
localWidthsRef.current = localWidths;
const itemsRef = useRef<ListColumnSettingItem[]>([]);
const configured = useMemo( const configured = useMemo(
() => applyColumnPrefs(allColumns as ColumnType<T>[], pref), () => applyColumnPrefs(allColumns as ColumnType<T>[], pref),
@@ -38,6 +46,7 @@ export function useAdminListColumns<T>(
() => settingItems(allColumns as ColumnType<T>[], pref), () => settingItems(allColumns as ColumnType<T>[], pref),
[allColumns, pref], [allColumns, pref],
); );
itemsRef.current = items;
const serialCol: ColumnType<T> = useMemo( const serialCol: ColumnType<T> = useMemo(
() => ({ () => ({
@@ -50,27 +59,30 @@ export function useAdminListColumns<T>(
[page, pageSize], [page, pageSize],
); );
const columns = useMemo<ColumnsType<T>>( const persistPref = useCallback(
() => [ async (next: { order: string[]; hidden: string[]; widths?: Record<string, number> } | null) => {
serialCol, if (!next) {
...configured.map((col) => setLocalWidths({});
col.title === '操作' || col.key === ACTIONS_COLUMN_KEY || col.key === 'actions' await save(listKey, null);
? { ...col, key: col.key ?? ACTIONS_COLUMN_KEY } return;
: col, }
), await save(listKey, next);
], },
[configured, serialCol], [listKey, save],
); );
async function persist(next: ListColumnSettingItem[] | null) { const persist = useCallback(
async (next: ListColumnSettingItem[] | null) => {
setSaving(true); setSaving(true);
try { try {
if (!next) { if (!next) {
await save(listKey, null); await persistPref(null);
} else { } else {
await save(listKey, { const widths = { ...(prefRef.current?.widths ?? {}), ...localWidthsRef.current };
await persistPref({
order: next.map((i) => i.key), order: next.map((i) => i.key),
hidden: next.filter((i) => !i.visible).map((i) => i.key), hidden: next.filter((i) => !i.visible).map((i) => i.key),
...(Object.keys(widths).length ? { widths } : {}),
}); });
} }
setOpen(false); setOpen(false);
@@ -80,12 +92,72 @@ export function useAdminListColumns<T>(
} finally { } finally {
setSaving(false); setSaving(false);
} }
},
[persistPref],
);
const persistWidth = useCallback(
async (key: string, width: number) => {
const current = prefRef.current;
const prevW = current?.widths?.[key];
if (prevW === width) return;
const order = current?.order?.length ? current.order : itemsRef.current.map((i) => i.key);
const hidden = current?.hidden ?? [];
const widths = { ...(current?.widths ?? {}), ...localWidthsRef.current, [key]: width };
try {
await persistPref({ order, hidden, widths });
} catch (e) {
message.error(e instanceof Error ? e.message : '列宽保存失败');
} }
},
[persistPref],
);
const columns = useMemo<ColumnsType<T>>(() => {
const merged: ColumnType<T>[] = [
serialCol,
...configured.map((col) =>
col.title === '操作' || col.key === ACTIONS_COLUMN_KEY || col.key === 'actions'
? { ...col, key: col.key ?? ACTIONS_COLUMN_KEY }
: col,
),
];
const widths = { ...(pref?.widths ?? {}), ...localWidths };
return merged.map((col, i) => {
const key = columnKey(col, i);
const width = widths[key] ?? (typeof col.width === 'number' ? col.width : undefined);
const prevHeader = col.onHeaderCell;
return {
...col,
key,
width,
title: withResizeTitle(col.title, (e) => {
const th = (e.currentTarget as HTMLElement).closest('th');
const startWidth = width ?? th?.getBoundingClientRect().width ?? 120;
beginColumnResize(
e,
startWidth,
(next) => setLocalWidths((prev) => ({ ...prev, [key]: next })),
(next) => void persistWidth(key, next),
);
}),
onHeaderCell: (column) => {
const extra = typeof prevHeader === 'function' ? prevHeader(column) : {};
return {
...extra,
className: [extra.className, 'admin-th-resizable'].filter(Boolean).join(' '),
};
},
};
});
}, [configured, serialCol, pref?.widths, localWidths, persistWidth]);
const settingsButton = ( const settingsButton = (
<Button icon={<SettingOutlined />} onClick={() => setOpen(true)}> <span className="admin-list-settings-slot">
<Button type="text" icon={<SettingOutlined />} className="admin-list-settings-btn" onClick={() => setOpen(true)}>
</Button> </Button>
</span>
); );
const settingsModal = ( const settingsModal = (
@@ -0,0 +1,242 @@
import { useState } from 'react';
import {
Button, Form, Image, Input, InputNumber, Modal, Popconfirm, Select, Space, Table, Tag, message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
ACTIVITY_POSTER_STATUS_LABELS,
DEFAULT_ACTIVITY_POSTER_QR_SLOT,
type ActivityPosterItem,
type ActivityPosterQrSlot,
type ActivityPosterStatus,
} from '@dukang/shared-types';
import { request } from '../lib/api';
import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import OssUpload from '../components/OssUpload';
import ActivityPosterQrSlotEditor from '../components/ActivityPosterQrSlotEditor';
type FormValues = {
title: string;
copyText?: string;
imageUrl: string;
qrXPct: number;
qrYPct: number;
qrSizePct: number;
sortOrder?: number;
status?: ActivityPosterStatus;
};
export default function ActivityPostersPage() {
const [form] = Form.useForm();
const [editForm] = Form.useForm<FormValues>();
const [filters, setFilters] = useState<Record<string, string>>({});
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<ActivityPosterItem>(
'/admin/activity-posters',
() => {
const qs = new URLSearchParams();
if (filters.status) qs.set('status', filters.status);
return qs;
},
[filters],
);
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<ActivityPosterItem | null>(null);
const imageUrl = Form.useWatch('imageUrl', editForm);
const qrXPct = Form.useWatch('qrXPct', editForm);
const qrYPct = Form.useWatch('qrYPct', editForm);
const qrSizePct = Form.useWatch('qrSizePct', editForm);
const slot: ActivityPosterQrSlot = {
qrXPct: qrXPct ?? DEFAULT_ACTIVITY_POSTER_QR_SLOT.qrXPct,
qrYPct: qrYPct ?? DEFAULT_ACTIVITY_POSTER_QR_SLOT.qrYPct,
qrSizePct: qrSizePct ?? DEFAULT_ACTIVITY_POSTER_QR_SLOT.qrSizePct,
};
function openCreate() {
setEditing(null);
editForm.setFieldsValue({
title: '',
copyText: '',
imageUrl: '',
...DEFAULT_ACTIVITY_POSTER_QR_SLOT,
sortOrder: 0,
status: 'ACTIVE',
});
setModalOpen(true);
}
function openEdit(row: ActivityPosterItem) {
setEditing(row);
editForm.setFieldsValue({
title: row.title,
copyText: row.copyText,
imageUrl: row.imageUrl,
qrXPct: row.qrXPct,
qrYPct: row.qrYPct,
qrSizePct: row.qrSizePct,
sortOrder: row.sortOrder,
status: row.status,
});
setModalOpen(true);
}
async function save() {
const v = await editForm.validateFields();
const body = JSON.stringify(v);
if (editing) {
await request(`/admin/activity-posters/${editing.id}`, { method: 'PUT', body });
message.success('已保存');
} else {
await request('/admin/activity-posters', { method: 'POST', body });
message.success('已创建');
}
setModalOpen(false);
void reload();
}
const baseColumns: ColumnsType<ActivityPosterItem> = [
{
title: '标题',
dataIndex: 'title',
width: 180,
render: (v, row) => <AdminPrimaryLink onClick={() => openEdit(row)}>{v}</AdminPrimaryLink>,
},
{
title: '封面',
dataIndex: 'imageUrl',
width: 90,
render: (url: string) => <Image src={url} width={56} height={56} style={{ objectFit: 'cover' }} />,
},
{
title: '文案',
dataIndex: 'copyText',
width: 240,
render: (v: string) => v || '—',
},
{ title: '排序', dataIndex: 'sortOrder', width: 70 },
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: ActivityPosterStatus) => (
<Tag color={s === 'ACTIVE' ? 'green' : 'default'}>{ACTIVITY_POSTER_STATUS_LABELS[s] || s}</Tag>
),
},
{ title: '更新', dataIndex: 'updatedAt', width: 160, render: fmtTime },
{
title: '操作',
width: 200,
render: (_, row) => (
<Space>
<Button type="link" size="small" onClick={() => openEdit(row)}></Button>
<Button
type="link"
size="small"
onClick={async () => {
const next = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE';
await request(`/admin/activity-posters/${row.id}/status`, {
method: 'PUT',
body: JSON.stringify({ status: next }),
});
message.success(next === 'ACTIVE' ? '已上架' : '已下架');
void reload();
}}
>
{row.status === 'ACTIVE' ? '下架' : '上架'}
</Button>
<Popconfirm
title="确认删除该活动图?"
onConfirm={async () => {
await request(`/admin/activity-posters/${row.id}`, { method: 'DELETE' });
message.success('已删除');
void reload();
}}
>
<Button type="link" size="small" danger></Button>
</Popconfirm>
</Space>
),
},
];
const { columns, settingsButton, settingsModal } = useAdminListColumns('activity-posters', baseColumns, {
page,
pageSize,
});
return (
<div>
{settingsModal}
<AdminListHeader
title="活动图"
settings={settingsButton}
actions={<Button type="primary" onClick={openCreate}></Button>}
/>
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="status" label="状态">
<Select
allowClear
style={{ width: 120 }}
options={Object.entries(ACTIVITY_POSTER_STATUS_LABELS).map(([value, label]) => ({ value, label }))}
/>
</Form.Item>
<Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item>
</Form>
<Table
rowKey="id"
className="admin-table-nowrap"
loading={loading}
columns={columns}
dataSource={data?.items ?? []}
scroll={{ x: 'max-content' }}
pagination={{
current: page,
pageSize,
total: data?.total ?? 0,
showSizeChanger: true,
onChange: (p, ps) => { setPage(p); setPageSize(ps); },
}}
/>
<Modal
title={editing ? '编辑活动图' : '新建活动图'}
open={modalOpen}
onCancel={() => setModalOpen(false)}
onOk={() => void save()}
width={720}
destroyOnClose
>
<Form form={editForm} layout="vertical">
<Form.Item name="title" label="标题" rules={[{ required: true, message: '请填写标题' }]}>
<Input maxLength={128} />
</Form.Item>
<Form.Item name="imageUrl" label="活动图" rules={[{ required: true, message: '请上传活动图' }]}>
<OssUpload bizType="ACTIVITY_POSTER" />
</Form.Item>
<Form.Item name="qrXPct" hidden><InputNumber /></Form.Item>
<Form.Item name="qrYPct" hidden><InputNumber /></Form.Item>
<Form.Item name="qrSizePct" hidden><InputNumber /></Form.Item>
<Form.Item label="二维码栏">
<ActivityPosterQrSlotEditor
imageUrl={imageUrl}
value={slot}
onChange={(next) => editForm.setFieldsValue(next)}
/>
</Form.Item>
<Form.Item name="copyText" label="推广文案">
<Input.TextArea rows={4} maxLength={4000} placeholder="合伙人可一键复制" />
</Form.Item>
<Form.Item name="sortOrder" label="排序" initialValue={0}>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="status" label="状态" initialValue="ACTIVE">
<Select options={Object.entries(ACTIVITY_POSTER_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
</Form.Item>
</Form>
</Modal>
</div>
);
}
+161 -26
View File
@@ -1,4 +1,5 @@
import { useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { import {
Button, Button,
Descriptions, Descriptions,
@@ -9,6 +10,7 @@ import {
Modal, Modal,
Popconfirm, Popconfirm,
Select, Select,
Space,
Table, Table,
Tag, Tag,
Typography, Typography,
@@ -17,11 +19,23 @@ import {
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import type { AdminBenefitGrantRequest } from '@dukang/shared-types'; import type { AdminBenefitGrantRequest } from '@dukang/shared-types';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants'; import { COUPON_STATUS_LABELS, DELIVERY_TYPE_LABELS, fmtTime } from '../lib/constants';
import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions'; import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type CouponOrder = {
id?: string;
orderNo?: string;
productName?: string | null;
productSpec?: string | null;
quantity?: number | null;
saleUnit?: string | null;
deliveryType?: string | null;
payAmount?: number | string | null;
};
type Row = { type Row = {
id: string; id: string;
@@ -32,10 +46,43 @@ type Row = {
status: string; status: string;
sourceProduct: string; sourceProduct: string;
createdAt: string; createdAt: string;
user?: { userNo: string; phone: string | null }; user?: { id?: string; userNo: string; phone: string | null };
order?: { orderNo: string } | null; order?: CouponOrder | null;
}; };
function saleUnitLabel(unit?: string | null) {
if (unit === 'BOX') return '箱';
if (unit === 'BOTTLE') return '瓶';
return '';
}
function formatPayAmount(v?: number | string | null) {
if (v == null || v === '') return '';
const n = Number(v);
return Number.isFinite(n) ? `¥${n.toFixed(2)}` : '';
}
/** 来源:有订单时展示商品名、规格、数量、配送方式、金额;手动发放沿用 sourceProduct */
function formatCouponSource(row: { sourceProduct?: string; order?: CouponOrder | null }) {
const order = row.order;
if (!order?.orderNo && !order?.productName) {
return row.sourceProduct || '—';
}
const unit = saleUnitLabel(order.saleUnit);
const qty =
order.quantity != null ? `${order.quantity}${unit}` : '';
const delivery = DELIVERY_TYPE_LABELS[order.deliveryType ?? ''] || order.deliveryType || '';
const amount = formatPayAmount(order.payAmount);
const parts = [
order.productName || row.sourceProduct,
order.productSpec,
qty,
delivery,
amount,
].filter((p) => p != null && String(p).trim() !== '');
return parts.join(' / ') || row.sourceProduct || '—';
}
type CouponRedeemRecord = { type CouponRedeemRecord = {
id: string; id: string;
redeemNo: string; redeemNo: string;
@@ -60,14 +107,20 @@ type CouponRedeemSummary = {
type CouponDetail = Row & { type CouponDetail = Row & {
redeemSummary?: CouponRedeemSummary | null; redeemSummary?: CouponRedeemSummary | null;
redeemRecords?: CouponRedeemRecord[]; redeemRecords?: CouponRedeemRecord[];
user?: { userNo?: string; phone?: string | null };
order?: { orderNo?: string } | null;
}; };
export default function BenefitCouponsPage() { export default function BenefitCouponsPage() {
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
const initialCouponNo = searchParams.get('couponNo')?.trim() || '';
const [form] = Form.useForm(); const [form] = Form.useForm();
const [grantForm] = Form.useForm<AdminBenefitGrantRequest>(); const [grantForm] = Form.useForm<AdminBenefitGrantRequest>();
const [filters, setFilters] = useState<Record<string, string>>({}); const [filters, setFilters] = useState<Record<string, string>>(() => {
const init: Record<string, string> = {};
if (initialCouponNo) init.couponNo = initialCouponNo;
return init;
});
const [grantOpen, setGrantOpen] = useState(false); const [grantOpen, setGrantOpen] = useState(false);
const [granting, setGranting] = useState(false); const [granting, setGranting] = useState(false);
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>( const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
@@ -86,6 +139,35 @@ export default function BenefitCouponsPage() {
const [redeemDetail, setRedeemDetail] = useState<Record<string, unknown> | null>(null); const [redeemDetail, setRedeemDetail] = useState<Record<string, unknown> | null>(null);
const [redeemDrawerOpen, setRedeemDrawerOpen] = useState(false); const [redeemDrawerOpen, setRedeemDrawerOpen] = useState(false);
const [redeemDetailLoading, setRedeemDetailLoading] = useState(false); const [redeemDetailLoading, setRedeemDetailLoading] = useState(false);
const deepLinkOpenedRef = useRef(false);
async function openCouponDetail(id: string) {
setDetail(await request<CouponDetail>(`/admin/benefit/coupons/${id}`));
setDrawerOpen(true);
}
useEffect(() => {
if (initialCouponNo) form.setFieldsValue({ couponNo: initialCouponNo });
}, [form, initialCouponNo]);
useEffect(() => {
const openCouponId = (location.state as { openCouponId?: string } | null)?.openCouponId;
if (openCouponId && !deepLinkOpenedRef.current) {
deepLinkOpenedRef.current = true;
void openCouponDetail(openCouponId).catch((e) => {
message.error(e instanceof Error ? e.message : '加载权益券失败');
});
return;
}
if (!initialCouponNo || deepLinkOpenedRef.current || loading) return;
const first = data?.items?.[0];
if (first && String(first.couponNo) === initialCouponNo) {
deepLinkOpenedRef.current = true;
void openCouponDetail(first.id).catch((e) => {
message.error(e instanceof Error ? e.message : '加载权益券失败');
});
}
}, [data, initialCouponNo, loading, location.state]);
async function openRedeemDetail(redeemId: string) { async function openRedeemDetail(redeemId: string) {
setRedeemDetailLoading(true); setRedeemDetailLoading(true);
@@ -102,20 +184,56 @@ export default function BenefitCouponsPage() {
} }
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '券号', dataIndex: 'couponNo', width: 200, ellipsis: false }, {
{ title: '用户', dataIndex: ['user', 'userNo'], width: 120, ellipsis: false }, title: '券号',
dataIndex: 'couponNo',
width: 200,
ellipsis: false,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openCouponDetail(row.id)}>
{v}
</AdminPrimaryLink>
),
},
{
title: '用户',
dataIndex: ['user', 'userNo'],
width: 120,
ellipsis: false,
render: (v: string | undefined, row) =>
row.user?.id ? (
<AdminPrimaryLink onClick={() => navigate('/users', { state: { openUserId: String(row.user!.id) } })}>
{v}
</AdminPrimaryLink>
) : (
v || '—'
),
},
{ title: '手机号', dataIndex: ['user', 'phone'], width: 120, render: (v) => v || '—' }, { title: '手机号', dataIndex: ['user', 'phone'], width: 120, render: (v) => v || '—' },
{ {
title: '订单', title: '订单',
dataIndex: ['order', 'orderNo'], dataIndex: ['order', 'orderNo'],
width: 180, width: 180,
ellipsis: false, ellipsis: false,
render: (v) => v || '—', render: (v: string | undefined) =>
v ? (
<AdminPrimaryLink onClick={() => navigate(`/orders?orderNo=${encodeURIComponent(v)}`)}>
{v}
</AdminPrimaryLink>
) : (
'—'
),
}, },
{ title: '总额', dataIndex: 'totalAmount', width: 80, render: (v) => `¥${v}` }, { title: '总额', dataIndex: 'totalAmount', width: 80, render: (v) => `¥${v}` },
{ title: '余额', dataIndex: 'balance', width: 80, render: (v) => `¥${v}` }, { title: '余额', dataIndex: 'balance', width: 80, render: (v) => `¥${v}` },
{ title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{COUPON_STATUS_LABELS[s] || s}</Tag> }, { title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{COUPON_STATUS_LABELS[s] || s}</Tag> },
{ title: '来源', dataIndex: 'sourceProduct' }, {
title: '来源',
dataIndex: 'sourceProduct',
width: 360,
ellipsis: false,
render: (_: string, row) => formatCouponSource(row),
},
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
title: '操作', title: '操作',
@@ -124,10 +242,7 @@ export default function BenefitCouponsPage() {
<Button <Button
type="link" type="link"
size="small" size="small"
onClick={async () => { onClick={() => void openCouponDetail(row.id)}
setDetail(await request(`/admin/benefit/coupons/${row.id}`));
setDrawerOpen(true);
}}
> >
</Button> </Button>
@@ -162,17 +277,15 @@ export default function BenefitCouponsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="好客权益券"
settings={settingsButton}
</Typography.Title> actions={
<Space>
{settingsButton}
<Button type="primary" onClick={() => setGrantOpen(true)}> <Button type="primary" onClick={() => setGrantOpen(true)}>
</Button> </Button>
</Space> }
</div> />
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="couponNo" label="券号"> <Form.Item name="couponNo" label="券号">
@@ -276,15 +389,37 @@ export default function BenefitCouponsPage() {
<> <>
<Descriptions column={1} bordered size="small"> <Descriptions column={1} bordered size="small">
<Descriptions.Item label="券号">{detail.couponNo}</Descriptions.Item> <Descriptions.Item label="券号">{detail.couponNo}</Descriptions.Item>
<Descriptions.Item label="用户">{detail.user?.userNo ?? '—'}</Descriptions.Item> <Descriptions.Item label="用户">
{detail.user?.id ? (
<AdminPrimaryLink
onClick={() => navigate('/users', { state: { openUserId: String(detail.user!.id) } })}
>
{detail.user?.userNo}
</AdminPrimaryLink>
) : (
(detail.user?.userNo ?? '—')
)}
</Descriptions.Item>
<Descriptions.Item label="手机号">{detail.user?.phone ?? '—'}</Descriptions.Item> <Descriptions.Item label="手机号">{detail.user?.phone ?? '—'}</Descriptions.Item>
<Descriptions.Item label="关联订单">{detail.order?.orderNo ?? '—'}</Descriptions.Item> <Descriptions.Item label="关联订单">
{detail.order?.orderNo ? (
<AdminPrimaryLink
onClick={() =>
navigate(`/orders?orderNo=${encodeURIComponent(detail.order!.orderNo!)}`)
}
>
{detail.order.orderNo}
</AdminPrimaryLink>
) : (
'—'
)}
</Descriptions.Item>
<Descriptions.Item label="总额">¥{Number(detail.totalAmount).toFixed(2)}</Descriptions.Item> <Descriptions.Item label="总额">¥{Number(detail.totalAmount).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="余额">¥{Number(detail.balance).toFixed(2)}</Descriptions.Item> <Descriptions.Item label="余额">¥{Number(detail.balance).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="状态"> <Descriptions.Item label="状态">
{COUPON_STATUS_LABELS[detail.status] || detail.status} {COUPON_STATUS_LABELS[detail.status] || detail.status}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="来源">{detail.sourceProduct}</Descriptions.Item> <Descriptions.Item label="来源">{formatCouponSource(detail)}</Descriptions.Item>
</Descriptions> </Descriptions>
<Typography.Title level={5} style={{ marginTop: 16, marginBottom: 8 }}> <Typography.Title level={5} style={{ marginTop: 16, marginBottom: 8 }}>
@@ -4,6 +4,7 @@ import type { ColumnsType } from 'antd/es/table';
import { LEDGER_TYPE_LABELS, fmtTime } from '../lib/constants'; import { LEDGER_TYPE_LABELS, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
type Row = { type Row = {
@@ -41,8 +42,7 @@ export default function BenefitLedgersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader title="权益流水" settings={settingsButton} />
{settingsButton}
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="userId" label="用户ID"><Input allowClear /></Form.Item> <Form.Item name="userId" label="用户ID"><Input allowClear /></Form.Item>
<Form.Item name="couponId" label="券ID"><Input allowClear /></Form.Item> <Form.Item name="couponId" label="券ID"><Input allowClear /></Form.Item>
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
import { request } from '../lib/api'; import { request } from '../lib/api';
import bgmSrc from '../assets/big-screen/dukang-bgm.mp3';
import sfxTier1 from '../assets/big-screen/celebrate-t1.mp3'; import sfxTier1 from '../assets/big-screen/celebrate-t1.mp3';
import sfxTier2 from '../assets/big-screen/celebrate-t2.mp3'; import sfxTier2 from '../assets/big-screen/celebrate-t2.mp3';
import sfxTier3 from '../assets/big-screen/celebrate-t3.mp3'; import sfxTier3 from '../assets/big-screen/celebrate-t3.mp3';
@@ -33,6 +34,50 @@ const CELEBRATE_SFX: Record<AmountTier, string> = {
/** 浏览器自动播放策略:需用户手势后才能出声 */ /** 浏览器自动播放策略:需用户手势后才能出声 */
let audioUnlocked = false; let audioUnlocked = false;
const sharedAudio = typeof Audio !== 'undefined' ? new Audio() : null; const sharedAudio = typeof Audio !== 'undefined' ? new Audio() : null;
const BGM_VOLUME = 0.32;
const BGM_DUCK_VOLUME = 0.08;
let bgmAudio: HTMLAudioElement | null = null;
let bgmDucked = false;
function getBgmAudio(): HTMLAudioElement | null {
if (typeof Audio === 'undefined') return null;
if (!bgmAudio) {
bgmAudio = new Audio(bgmSrc);
bgmAudio.loop = true;
bgmAudio.preload = 'auto';
bgmAudio.volume = BGM_VOLUME;
}
return bgmAudio;
}
function applyBgmVolume() {
if (!bgmAudio) return;
bgmAudio.volume = bgmDucked ? BGM_DUCK_VOLUME : BGM_VOLUME;
}
function duckBgm() {
bgmDucked = true;
applyBgmVolume();
}
function unduckBgm() {
bgmDucked = false;
applyBgmVolume();
}
function setBgmPlaying(on: boolean): Promise<boolean> {
const audio = getBgmAudio();
if (!audio) return Promise.resolve(false);
applyBgmVolume();
if (!on) {
audio.pause();
return Promise.resolve(false);
}
return audio
.play()
.then(() => true)
.catch(() => false);
}
function unlockCelebrateAudio() { function unlockCelebrateAudio() {
if (audioUnlocked || !sharedAudio) return; if (audioUnlocked || !sharedAudio) return;
@@ -53,6 +98,7 @@ function unlockCelebrateAudio() {
function playCelebrateSfx(tier: AmountTier): () => void { function playCelebrateSfx(tier: AmountTier): () => void {
if (!sharedAudio) return () => undefined; if (!sharedAudio) return () => undefined;
duckBgm();
try { try {
sharedAudio.pause(); sharedAudio.pause();
sharedAudio.currentTime = 0; sharedAudio.currentTime = 0;
@@ -72,6 +118,7 @@ function playCelebrateSfx(tier: AmountTier): () => void {
} catch { } catch {
/* ignore */ /* ignore */
} }
unduckBgm();
}; };
} }
@@ -341,10 +388,40 @@ function CelebrateFx({ order, onDone }: { order: BigScreenOrder; onDone: () => v
); );
} }
function BgmToggleButton({ on, onToggle }: { on: boolean; onToggle: () => void }) {
return (
<button
type="button"
className={`big-screen-bgm${on ? ' is-on' : ''}`}
onClick={onToggle}
aria-pressed={on}
aria-label={on ? '暂停背景音乐' : '播放背景音乐'}
>
<span className="big-screen-bgm-icon" aria-hidden>
{on ? (
<svg viewBox="0 0 24 24" width="16" height="16">
<path
fill="currentColor"
d="M9 18V6h2v12H9zm4 0V6h2v12h-2z"
/>
</svg>
) : (
<svg viewBox="0 0 24 24" width="16" height="16">
<path fill="currentColor" d="M8 5.14v13.72L19.06 12 8 5.14z" />
</svg>
)}
</span>
{on ? 'BGM 播放中' : '播放 BGM'}
</button>
);
}
export default function BigScreenPage() { export default function BigScreenPage() {
const [items, setItems] = useState<BigScreenOrder[]>([]); const [items, setItems] = useState<BigScreenOrder[]>([]);
const [loadError, setLoadError] = useState(''); const [loadError, setLoadError] = useState('');
const [paused, setPaused] = useState(false); const [paused, setPaused] = useState(false);
const [bgmOn, setBgmOn] = useState(false);
const bgmWantedRef = useRef(false);
const [celebrate, setCelebrate] = useState<BigScreenOrder | null>(null); const [celebrate, setCelebrate] = useState<BigScreenOrder | null>(null);
const seenIdsRef = useRef<Set<string> | null>(null); const seenIdsRef = useRef<Set<string> | null>(null);
const celebratedIdsRef = useRef<Set<string>>(new Set()); const celebratedIdsRef = useRef<Set<string>>(new Set());
@@ -416,6 +493,22 @@ export default function BigScreenPage() {
return () => clearInterval(id); return () => clearInterval(id);
}, [fetchData]); }, [fetchData]);
const toggleBgm = useCallback(() => {
unlockCelebrateAudio();
const next = !bgmWantedRef.current;
bgmWantedRef.current = next;
if (!next) {
void setBgmPlaying(false);
setBgmOn(false);
return;
}
setBgmOn(true);
void setBgmPlaying(true).then((playing) => {
if (!bgmWantedRef.current) return;
setBgmOn(playing);
});
}, []);
useEffect(() => { useEffect(() => {
unlockCelebrateAudio(); unlockCelebrateAudio();
const unlock = () => unlockCelebrateAudio(); const unlock = () => unlockCelebrateAudio();
@@ -424,6 +517,8 @@ export default function BigScreenPage() {
return () => { return () => {
window.removeEventListener('pointerdown', unlock); window.removeEventListener('pointerdown', unlock);
window.removeEventListener('keydown', unlock); window.removeEventListener('keydown', unlock);
bgmWantedRef.current = false;
void setBgmPlaying(false);
}; };
}, []); }, []);
@@ -480,6 +575,7 @@ export default function BigScreenPage() {
<span className="big-screen-subtitle">· </span> <span className="big-screen-subtitle">· </span>
</div> </div>
<div className="big-screen-live-wrap"> <div className="big-screen-live-wrap">
<BgmToggleButton on={bgmOn} onToggle={toggleBgm} />
<span className="big-screen-live-label"></span> <span className="big-screen-live-label"></span>
<span className="big-screen-live"> <span className="big-screen-live">
<span className="big-screen-live-dot" /> <span className="big-screen-live-dot" />
+38 -8
View File
@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom';
import { import {
Button, Button,
Descriptions, Descriptions,
Divider,
Drawer, Drawer,
Form, Form,
Input, Input,
@@ -25,6 +26,8 @@ import { useAdminList } from '../lib/useAdminList';
import CityPartnersPanel from '../components/CityPartnersPanel'; import CityPartnersPanel from '../components/CityPartnersPanel';
import ChinaProvinceCityCascader from '../components/ChinaProvinceCityCascader'; import ChinaProvinceCityCascader from '../components/ChinaProvinceCityCascader';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type WarehouseRow = { type WarehouseRow = {
@@ -227,7 +230,14 @@ export default function CitiesPage() {
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '编码', dataIndex: 'code', width: 90 }, { title: '编码', dataIndex: 'code', width: 90 },
{ title: '城市', dataIndex: 'name', width: 100 }, {
title: '城市',
dataIndex: 'name',
width: 100,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row)}>{v}</AdminPrimaryLink>
),
},
{ title: '省份', dataIndex: 'province', width: 90 }, { title: '省份', dataIndex: 'province', width: 90 },
{ title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{CITY_STATUS_LABELS[s] || s}</Tag> }, { title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{CITY_STATUS_LABELS[s] || s}</Tag> },
{ title: '合伙人', dataIndex: 'partnerBindingCount', width: 90 }, { title: '合伙人', dataIndex: 'partnerBindingCount', width: 90 },
@@ -318,11 +328,11 @@ export default function CitiesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="城市"
{settingsButton} settings={settingsButton}
<Button type="primary" onClick={openCreateModal}></Button> actions={<Button type="primary" onClick={openCreateModal}></Button>}
</Space> />
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="name" label="城市"><Input allowClear /></Form.Item> <Form.Item name="name" label="城市"><Input allowClear /></Form.Item>
<Form.Item name="code" label="编码"><Input allowClear /></Form.Item> <Form.Item name="code" label="编码"><Input allowClear /></Form.Item>
@@ -353,8 +363,28 @@ export default function CitiesPage() {
<Form.Item name="status" label="状态"> <Form.Item name="status" label="状态">
<Select options={Object.entries(CITY_STATUS_LABELS).map(([value, label]) => ({ value, label }))} /> <Select options={Object.entries(CITY_STATUS_LABELS).map(([value, label]) => ({ value, label }))} />
</Form.Item> </Form.Item>
<Form.Item name="localMinQty" label="同城起购"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item> <Divider orientation="left"></Divider>
<Form.Item name="crossMinQty" label="跨城起购"><InputNumber min={1} style={{ width: '100%' }} /></Form.Item> <Form.Item
name="pickupMinQty"
label="现场提货"
extra="按瓶当量;箱装 1 箱即可过。默认 2 瓶。"
>
<InputNumber min={1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item
name="localMinQty"
label="同城配送"
extra="按瓶当量;箱装 1 箱即可过。默认 2 瓶。"
>
<InputNumber min={1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item
name="crossMinQty"
label="跨城配送"
extra="按瓶当量。当前箱规 6 瓶/箱时,填 6 = 最少 1 箱。"
>
<InputNumber min={1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item <Form.Item
name="maxPartnerCommissionPercent" name="maxPartnerCommissionPercent"
label="合伙人佣金合计上限 %" label="合伙人佣金合计上限 %"
+49 -8
View File
@@ -31,12 +31,16 @@ import {
type PartnerPermissionKey, type PartnerPermissionKey,
} from '@dukang/shared-types'; } from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { omitNullFields } from '../lib/omit-null-fields';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region'; import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants'; import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect'; import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect';
import PartnerSubAccountList, { type PartnerSubAccountRow } from '../components/PartnerSubAccountList'; import PartnerSubAccountList, { type PartnerSubAccountRow } from '../components/PartnerSubAccountList';
import PartnerAssocPanel from '../components/PartnerAssocPanel';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type SubRow = PartnerSubAccountRow; type SubRow = PartnerSubAccountRow;
@@ -58,6 +62,7 @@ type Row = {
managedWarehouseName?: string | null; managedWarehouseName?: string | null;
maxPartnerCommissionRate?: number | null; maxPartnerCommissionRate?: number | null;
storeCount: number; storeCount: number;
assocUserCount?: number;
accountCount: number; accountCount: number;
subAccounts?: SubRow[]; subAccounts?: SubRow[];
createdAt: string; createdAt: string;
@@ -207,7 +212,7 @@ export default function CityPartnersPage() {
await request(`/admin/partners/${detail.id}`, { await request(`/admin/partners/${detail.id}`, {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ body: JSON.stringify({
...v, ...omitNullFields(v),
orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100, orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100,
redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100, redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100,
districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined, districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined,
@@ -272,7 +277,14 @@ export default function CityPartnersPage() {
render: (codes: string[] | null | undefined, row) => render: (codes: string[] | null | undefined, row) =>
row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes), row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes),
}, },
}, {
title: '公司名',
dataIndex: 'companyName',
width: 140,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openPartner(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '主账号姓名', title: '主账号姓名',
dataIndex: 'name', dataIndex: 'name',
@@ -323,6 +335,19 @@ export default function CityPartnersPage() {
</Link> </Link>
), ),
}, },
{
title: '关联用户',
dataIndex: 'assocUserCount',
width: 80,
render: (n: number, row) => (
<Link
to={`/users?assocPartnerAccountId=${encodeURIComponent(row.id)}`}
title={`查看「${row.companyName || row.phone}」关联用户`}
>
{n ?? 0}
</Link>
),
},
{ title: '子账号', dataIndex: 'accountCount', width: 70, render: (n) => Math.max(0, n - 1) }, { title: '子账号', dataIndex: 'accountCount', width: 70, render: (n) => Math.max(0, n - 1) },
{ title: '创建', dataIndex: 'createdAt', width: 150, render: fmtTime }, { title: '创建', dataIndex: 'createdAt', width: 150, render: fmtTime },
{ {
@@ -342,11 +367,12 @@ export default function CityPartnersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
return ( <AdminListHeader
<div> title="城市合伙人"
{settingsModal} settings={settingsButton}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> actions={
<Typography.Title level={4} style={{ margin: 0 }}> <>
<Link to="/users?assocPartnerAccountId=any"></Link>
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -364,7 +390,9 @@ export default function CityPartnersPage() {
> >
</Button> </Button>
> </>
}
/>
<Alert <Alert
type="info" type="info"
@@ -477,6 +505,14 @@ export default function CityPartnersPage() {
{detail.storeCount ?? 0} {detail.storeCount ?? 0}
</Link> </Link>
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="关联用户">
<Link
to={`/users?assocPartnerAccountId=${encodeURIComponent(detail.id)}`}
title="查看该城市合伙人关联用户"
>
{detail.assocUserCount ?? 0}
</Link>
</Descriptions.Item>
<Descriptions.Item label="管仓仓库" span={2}> <Descriptions.Item label="管仓仓库" span={2}>
{detail.managedWarehouseName ?? ( {detail.managedWarehouseName ?? (
<Typography.Text type="secondary"> <Typography.Text type="secondary">
@@ -561,6 +597,11 @@ export default function CityPartnersPage() {
/> />
), ),
}, },
{
key: 'assoc',
label: '关联码',
children: <PartnerAssocPanel partnerId={detail.id} />,
},
]} ]}
/> />
</> </>
@@ -14,7 +14,6 @@ import {
Switch, Switch,
Table, Table,
Tag, Tag,
Typography,
message, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
@@ -31,6 +30,8 @@ import { request, type Paginated } from '../lib/api';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants'; import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -232,7 +233,14 @@ export default function CityWarehousesPage() {
</span> </span>
), ),
}, },
{ title: '仓库', dataIndex: 'name', width: 140 }, {
title: '仓库',
dataIndex: 'name',
width: 140,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ title: '地址', dataIndex: 'address', width: 180 }, { title: '地址', dataIndex: 'address', width: 180 },
{ title: '联系人', dataIndex: 'contactName', width: 90 }, { title: '联系人', dataIndex: 'contactName', width: 90 },
{ title: '电话', dataIndex: 'contactPhone', width: 120 }, { title: '电话', dataIndex: 'contactPhone', width: 120 },
@@ -308,9 +316,10 @@ export default function CityWarehousesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="仓库"
{settingsButton} settings={settingsButton}
actions={
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -328,7 +337,8 @@ export default function CityWarehousesPage() {
> >
</Button> </Button>
</Space> }
/>
<Alert <Alert
type="info" type="info"
+225 -25
View File
@@ -1,14 +1,43 @@
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { import {
Button, Descriptions, Drawer, Form, Input, Space, Table, Typography, message, Button, Descriptions, Drawer, Form, Input, Space, Table, Typography, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import OrderTrackDrawer from '../components/OrderTrackDrawer'; import OrderTrackDrawer from '../components/OrderTrackDrawer';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { ORDER_STATUS_LABELS, fmtTime } from '../lib/constants'; import {
DELIVERY_PROVIDER_LABELS,
DELIVERY_TYPE_LABELS,
ORDER_STATUS_LABELS,
fmtTime,
} from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type DeliveryOrder = {
id: string;
orderNo: string;
status: string;
deliveryType: string;
productName: string;
productSpec?: string | null;
barcode69?: string | null;
quantity: number;
saleUnit?: string;
bottlesPerUnit?: number;
payAmount?: number;
receiverName: string;
receiverPhone: string;
receiverAddress?: string;
receiverProvince?: string;
receiverCity?: string;
receiverDistrict?: string;
user?: { id: string; userNo: string; phone: string | null; nickname: string | null };
imageResource?: { url: string } | null;
};
type Row = { type Row = {
id: string; id: string;
@@ -17,17 +46,34 @@ type Row = {
trackingNo: string | null; trackingNo: string | null;
providerOrderNo: string | null; providerOrderNo: string | null;
updatedAt: string; updatedAt: string;
order?: { logisticsFee?: number | null;
id: string; order?: DeliveryOrder;
orderNo: string;
status: string;
receiverName: string;
receiverPhone: string;
deliveryType: string;
};
}; };
function formatQty(order?: DeliveryOrder | null) {
if (!order || order.quantity == null) return '—';
const unit = order.saleUnit === 'BOX' ? '箱' : '瓶';
const bottles =
order.saleUnit === 'BOX' && order.bottlesPerUnit && order.bottlesPerUnit > 1
? `${order.quantity * order.bottlesPerUnit}瓶)`
: '';
return `${order.quantity}${unit}${bottles}`;
}
function formatAddress(order?: DeliveryOrder | null) {
if (!order) return '—';
if (order.deliveryType === 'ON_SITE_PICKUP') return '现场取货';
const region = [order.receiverProvince, order.receiverCity, order.receiverDistrict]
.filter(Boolean)
.join('');
const detail = (order.receiverAddress || '').trim();
if (!region) return detail || '—';
if (!detail || detail.startsWith(region)) return detail || region;
return `${region}${detail}`;
}
export default function DeliveriesPage() { export default function DeliveriesPage() {
const navigate = useNavigate();
const [form] = Form.useForm(); const [form] = Form.useForm();
const [editForm] = Form.useForm(); const [editForm] = Form.useForm();
const [filters, setFilters] = useState<Record<string, string>>({}); const [filters, setFilters] = useState<Record<string, string>>({});
@@ -61,25 +107,126 @@ export default function DeliveriesPage() {
setTrackOpen(true); setTrackOpen(true);
} }
async function openDetail(row: Row) {
const d = await request<Row>(`/admin/deliveries/${row.id}`);
setDetail(d);
editForm.setFieldsValue({
provider: d.provider,
trackingNo: d.trackingNo,
providerOrderNo: d.providerOrderNo,
});
setDrawerOpen(true);
}
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '订单号', dataIndex: ['order', 'orderNo'], width: 170 }, {
{ title: 'provider', dataIndex: 'provider', width: 90 }, title: '订单号',
dataIndex: ['order', 'orderNo'],
width: 170,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row)}>{v}</AdminPrimaryLink>
),
},
{
title: '用户',
key: 'user',
width: 140,
render: (_, row) => {
const user = row.order?.user;
if (!user) return '—';
const label = user.userNo || user.phone || '—';
return (
<div>
{user.id ? (
<AdminPrimaryLink
onClick={() => navigate('/users', { state: { openUserId: String(user.id) } })}
>
{label}
</AdminPrimaryLink>
) : (
label
)}
{user.phone && user.userNo ? (
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
{user.phone}
</Typography.Text>
) : null}
</div>
);
},
},
{
title: '商品',
key: 'product',
width: 200,
render: (_, row) => {
const order = row.order;
if (!order?.productName) return '—';
return (
<div>
<span>{order.productName}</span>
{order.productSpec ? (
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
{order.productSpec}
</Typography.Text>
) : null}
</div>
);
},
},
{
title: '数量',
key: 'quantity',
width: 90,
render: (_, row) => formatQty(row.order),
},
{
title: '配送方式',
dataIndex: ['order', 'deliveryType'],
width: 90,
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
},
{
title: '承运商',
dataIndex: 'provider',
width: 90,
render: (v: string) => DELIVERY_PROVIDER_LABELS[v] || v || '—',
},
{ title: '运单号', dataIndex: 'trackingNo', width: 140, render: (v) => v || '—' }, { title: '运单号', dataIndex: 'trackingNo', width: 140, render: (v) => v || '—' },
{
title: '运费',
dataIndex: 'logisticsFee',
width: 90,
render: (v: number | null | undefined) => (v == null ? '—' : `¥${Number(v).toFixed(2)}`),
},
{ title: '第三方单号', dataIndex: 'providerOrderNo', width: 140, render: (v) => v || '—' }, { title: '第三方单号', dataIndex: 'providerOrderNo', width: 140, render: (v) => v || '—' },
{ title: '订单状态', dataIndex: ['order', 'status'], width: 100, render: (s) => ORDER_STATUS_LABELS[s] || s }, {
title: '订单状态',
dataIndex: ['order', 'status'],
width: 100,
render: (s) => ORDER_STATUS_LABELS[s] || s,
},
{ title: '收货人', dataIndex: ['order', 'receiverName'], width: 90 }, { title: '收货人', dataIndex: ['order', 'receiverName'], width: 90 },
{
title: '收货电话',
dataIndex: ['order', 'receiverPhone'],
width: 120,
render: (v) => v || '—',
},
{
title: '配送地址',
key: 'address',
width: 280,
ellipsis: true,
render: (_, row) => formatAddress(row.order),
},
{ title: '更新', dataIndex: 'updatedAt', width: 160, render: fmtTime }, { title: '更新', dataIndex: 'updatedAt', width: 160, render: fmtTime },
{ {
title: '操作', width: 140, title: '操作', width: 140,
render: (_, row) => ( render: (_, row) => (
<Space size={0}> <Space size={0}>
<Button type="link" size="small" onClick={() => openTrack(row)}></Button> <Button type="link" size="small" onClick={() => openTrack(row)}></Button>
<Button type="link" size="small" onClick={async () => { <Button type="link" size="small" onClick={() => void openDetail(row)}></Button>
const d = await request<Row>(`/admin/deliveries/${row.id}`);
setDetail(d);
editForm.setFieldsValue({ provider: d.provider, trackingNo: d.trackingNo, providerOrderNo: d.providerOrderNo });
setDrawerOpen(true);
}}></Button>
</Space> </Space>
), ),
}, },
@@ -87,20 +234,21 @@ export default function DeliveriesPage() {
const { columns, settingsButton, settingsModal } = useAdminListColumns('deliveries', baseColumns, { page, pageSize }); const { columns, settingsButton, settingsModal } = useAdminListColumns('deliveries', baseColumns, { page, pageSize });
const order = detail?.order;
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}>/</Typography.Title> <AdminListHeader title="快递/配送单" settings={settingsButton} />
{settingsButton}
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="orderNo" label="订单号"><Input allowClear /></Form.Item> <Form.Item name="orderNo" label="订单号"><Input allowClear /></Form.Item>
<Form.Item name="provider" label="provider"><Input allowClear placeholder="MOCK" /></Form.Item> <Form.Item name="provider" label="承运商"><Input allowClear placeholder="XFX" /></Form.Item>
<Form.Item name="trackingNo" label="运单号"><Input allowClear /></Form.Item> <Form.Item name="trackingNo" label="运单号"><Input allowClear /></Form.Item>
<Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item> <Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item>
</Form> </Form>
<Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 'max-content' }} <Table rowKey="id" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 'max-content' }}
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} /> pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
<Drawer title="配送单编辑" width={480} open={drawerOpen} onClose={() => setDrawerOpen(false)} <Drawer title="配送单编辑" width={560} open={drawerOpen} onClose={() => setDrawerOpen(false)}
extra={ extra={
<Space> <Space>
<Button onClick={() => setDrawerOpen(false)}></Button> <Button onClick={() => setDrawerOpen(false)}></Button>
@@ -117,11 +265,63 @@ export default function DeliveriesPage() {
{detail && ( {detail && (
<> <>
<Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}> <Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}>
<Descriptions.Item label="订单">{detail.order?.orderNo}</Descriptions.Item> <Descriptions.Item label="订单">{order?.orderNo || '—'}</Descriptions.Item>
<Descriptions.Item label="收货">{detail.order?.receiverName} {detail.order?.receiverPhone}</Descriptions.Item> <Descriptions.Item label="用户">
{order?.user ? (
<Space size={8} wrap>
{order.user.id ? (
<AdminPrimaryLink
onClick={() => navigate('/users', { state: { openUserId: String(order.user!.id) } })}
>
{order.user.userNo}
</AdminPrimaryLink>
) : (
order.user.userNo || '—'
)}
<Typography.Text type="secondary">
{[order.user.nickname, order.user.phone].filter(Boolean).join(' / ') || ''}
</Typography.Text>
</Space>
) : '—'}
</Descriptions.Item>
<Descriptions.Item label="商品">
<Space align="start">
{order?.imageResource?.url ? (
<img
src={order.imageResource.url}
alt=""
style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 4 }}
/>
) : null}
<span>
{order?.productName || '—'}
{order?.productSpec ? (
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
{order.productSpec}
</Typography.Text>
) : null}
{order?.barcode69 ? (
<Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
{order.barcode69}
</Typography.Text>
) : null}
</span>
</Space>
</Descriptions.Item>
<Descriptions.Item label="数量">{formatQty(order)}</Descriptions.Item>
<Descriptions.Item label="配送方式">
{DELIVERY_TYPE_LABELS[order?.deliveryType ?? ''] || order?.deliveryType || '—'}
</Descriptions.Item>
<Descriptions.Item label="收货人">
{[order?.receiverName, order?.receiverPhone].filter(Boolean).join(' ') || '—'}
</Descriptions.Item>
<Descriptions.Item label="配送地址">{formatAddress(order)}</Descriptions.Item>
<Descriptions.Item label="运费">
{detail.logisticsFee == null ? '—' : `¥${Number(detail.logisticsFee).toFixed(2)}`}
</Descriptions.Item>
</Descriptions> </Descriptions>
<Form form={editForm} layout="vertical"> <Form form={editForm} layout="vertical">
<Form.Item name="provider" label="provider" rules={[{ required: true }]}><Input /></Form.Item> <Form.Item name="provider" label="承运商" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item name="providerOrderNo" label="第三方单号"><Input /></Form.Item> <Form.Item name="providerOrderNo" label="第三方单号"><Input /></Form.Item>
<Form.Item name="trackingNo" label="运单号"><Input /></Form.Item> <Form.Item name="trackingNo" label="运单号"><Input /></Form.Item>
</Form> </Form>
+53 -12
View File
@@ -31,6 +31,8 @@ import { downloadBase64File } from '../lib/exportExcel';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map((v) => ({ const TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map((v) => ({
@@ -69,11 +71,11 @@ export default function DevPlanTasksPage() {
const [batchForm] = Form.useForm<{ status?: DevPlanTaskStatusDto; versionId?: string }>(); const [batchForm] = Form.useForm<{ status?: DevPlanTaskStatusDto; versionId?: string }>();
useEffect(() => { useEffect(() => {
if (!batchEditOpen) return; if (!modalOpen && !batchEditOpen) return;
request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100') request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100')
.then((res) => setVersions(res.items ?? [])) .then((res) => setVersions(res.items ?? []))
.catch(() => setVersions([])); .catch(() => setVersions([]));
}, [batchEditOpen]); }, [modalOpen, batchEditOpen]);
useEffect(() => { useEffect(() => {
if (!modalOpen || editing) return; if (!modalOpen || editing) return;
@@ -106,6 +108,7 @@ export default function DevPlanTasksPage() {
content: row.content, content: row.content,
type: row.type, type: row.type,
status: row.status, status: row.status,
versionIds: row.versionIds?.length ? row.versionIds : row.versions?.map((v) => v.id) ?? [],
attachmentUrls: row.attachmentUrls?.length ? row.attachmentUrls : [''], attachmentUrls: row.attachmentUrls?.length ? row.attachmentUrls : [''],
}); });
setModalOpen(true); setModalOpen(true);
@@ -119,7 +122,11 @@ export default function DevPlanTasksPage() {
if (editing) { if (editing) {
await request(`/admin/dev-plan/tasks/${editing.id}`, { await request(`/admin/dev-plan/tasks/${editing.id}`, {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ ...values, attachmentUrls }), body: JSON.stringify({
...values,
attachmentUrls,
versionIds: values.versionIds ?? [],
}),
}); });
message.success('已更新'); message.success('已更新');
} else { } else {
@@ -243,7 +250,14 @@ export default function DevPlanTasksPage() {
} }
const baseColumns: ColumnsType<DevPlanTaskDto> = [ const baseColumns: ColumnsType<DevPlanTaskDto> = [
{ title: '任务号', dataIndex: 'taskNo', width: 160 }, {
title: '任务号',
dataIndex: 'taskNo',
width: 160,
render: (v, row) => (
<AdminPrimaryLink onClick={() => openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '类型', title: '类型',
dataIndex: 'type', dataIndex: 'type',
@@ -276,6 +290,21 @@ export default function DevPlanTasksPage() {
), ),
}, },
{ title: '来源工单', dataIndex: 'supportTicketNo', width: 140, render: (v) => v || '—' }, { title: '来源工单', dataIndex: 'supportTicketNo', width: 140, render: (v) => v || '—' },
{
title: '关联版本',
dataIndex: 'versions',
width: 140,
render: (_, row) =>
row.versions?.length ? (
<Space size={4} wrap>
{row.versions.map((v) => (
<Tag key={v.id}>{v.versionNo}</Tag>
))}
</Space>
) : (
'—'
),
},
{ title: '创建人', dataIndex: 'creatorName', width: 90 }, { title: '创建人', dataIndex: 'creatorName', width: 90 },
{ title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
@@ -301,12 +330,11 @@ export default function DevPlanTasksPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="开发计划 · 任务列表"
· settings={settingsButton}
</Typography.Title> actions={
{settingsButton} <>
<Space wrap>
<Select <Select
value={exportFormat} value={exportFormat}
style={{ width: 120 }} style={{ width: 120 }}
@@ -333,8 +361,9 @@ export default function DevPlanTasksPage() {
<Button type="primary" onClick={openCreate}> <Button type="primary" onClick={openCreate}>
</Button> </Button>
</Space> </>
</div> }
/>
<Form <Form
layout="inline" layout="inline"
@@ -396,9 +425,21 @@ export default function DevPlanTasksPage() {
<Select options={TYPE_OPTIONS} /> <Select options={TYPE_OPTIONS} />
</Form.Item> </Form.Item>
{editing ? ( {editing ? (
<>
<Form.Item name="status" label="状态" rules={[{ required: true }]}> <Form.Item name="status" label="状态" rules={[{ required: true }]}>
<Select options={STATUS_OPTIONS} /> <Select options={STATUS_OPTIONS} />
</Form.Item> </Form.Item>
<Form.Item name="versionIds" label="关联版本">
<Select
mode="multiple"
allowClear
showSearch
optionFilterProp="label"
placeholder="可选:关联版本"
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
/>
</Form.Item>
</>
) : ( ) : (
<Form.Item name="supportTicketId" label="绑定技术支持工单"> <Form.Item name="supportTicketId" label="绑定技术支持工单">
<Select <Select
@@ -9,7 +9,6 @@ import {
Space, Space,
Table, Table,
Tag, Tag,
Typography,
message, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
@@ -23,6 +22,8 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
@@ -122,7 +123,9 @@ export default function DevPlanVersionsPage() {
} }
const baseColumns: ColumnsType<DevPlanVersionDto> = [ const baseColumns: ColumnsType<DevPlanVersionDto> = [
{ title: '版本号', dataIndex: 'versionNo', width: 120 }, { title: '版本号', dataIndex: 'versionNo', width: 120, render: (v, row) => (
<AdminPrimaryLink onClick={() => void openEdit(row)}>{v}</AdminPrimaryLink>
) },
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
@@ -165,15 +168,15 @@ export default function DevPlanVersionsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="开发计划 · 版本列表"
· settings={settingsButton}
</Typography.Title> actions={
{settingsButton}
<Button type="primary" onClick={openCreate}> <Button type="primary" onClick={openCreate}>
</Button> </Button>
</div> }
/>
<Form <Form
layout="inline" layout="inline"
+46 -9
View File
@@ -4,7 +4,16 @@ import { Card, Descriptions, Drawer, Select, Space, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import {
DOMAIN_EVENT_TYPE_LABELS,
domainParamFieldLabel,
domainParamValue,
formatRef,
zhCode,
zhLabel,
} from '../lib/display-labels';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -14,8 +23,11 @@ type Row = {
refId: string; refId: string;
status?: string | null; status?: string | null;
param1?: string | null; param1?: string | null;
param1Desc?: string | null;
param2?: string | null; param2?: string | null;
param2Desc?: string | null;
param3?: string | null; param3?: string | null;
param3Desc?: string | null;
remark?: string | null; remark?: string | null;
createdAt: string; createdAt: string;
}; };
@@ -59,10 +71,28 @@ export default function DomainEventsPage() {
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '时间', dataIndex: 'createdAt', width: 170, render: (v) => fmtTime(v) }, { title: '时间', dataIndex: 'createdAt', width: 170, render: (v) => fmtTime(v) },
{ title: '类型', dataIndex: 'eventType', width: 130, render: (v) => <Tag>{v}</Tag> }, {
{ title: '关联', render: (_, r) => `${r.refType} #${r.refId}` }, title: '类型',
{ title: '状态', dataIndex: 'status', width: 100 }, dataIndex: 'eventType',
{ title: '摘要', render: (_, r) => r.param1 || r.remark || '—' }, width: 130,
render: (v, r) => (
<AdminPrimaryLink
onClick={async () => {
setDetail(await request<Row>(`/admin/logs/domain-events/${r.id}`));
}}
>
<Tag>{zhLabel(DOMAIN_EVENT_TYPE_LABELS, v)}</Tag>
</AdminPrimaryLink>
),
},
{ title: '关联', render: (_, r) => formatRef(r.refType, r.refId) },
{ title: '状态', dataIndex: 'status', width: 100, render: (v) => zhCode(v) },
{
title: '摘要',
render: (_, r) => domainParamValue(r.param1Desc, r.param1) !== '—'
? domainParamValue(r.param1Desc, r.param1)
: (r.remark || '—'),
},
{ {
title: '操作', title: '操作',
width: 80, width: 80,
@@ -119,11 +149,18 @@ export default function DomainEventsPage() {
{detail && ( {detail && (
<Descriptions column={1} size="small"> <Descriptions column={1} size="small">
<Descriptions.Item label="ID">{detail.id}</Descriptions.Item> <Descriptions.Item label="ID">{detail.id}</Descriptions.Item>
<Descriptions.Item label="类型">{detail.eventType}</Descriptions.Item> <Descriptions.Item label="类型">{zhLabel(DOMAIN_EVENT_TYPE_LABELS, detail.eventType)}</Descriptions.Item>
<Descriptions.Item label="关联">{`${detail.refType} #${detail.refId}`}</Descriptions.Item> <Descriptions.Item label="关联">{formatRef(detail.refType, detail.refId)}</Descriptions.Item>
<Descriptions.Item label="param1">{detail.param1}</Descriptions.Item> <Descriptions.Item label="状态">{zhCode(detail.status)}</Descriptions.Item>
<Descriptions.Item label="param2">{detail.param2}</Descriptions.Item> <Descriptions.Item label={domainParamFieldLabel(detail.param1Desc, 1)}>
<Descriptions.Item label="param3">{detail.param3}</Descriptions.Item> {domainParamValue(detail.param1Desc, detail.param1)}
</Descriptions.Item>
<Descriptions.Item label={domainParamFieldLabel(detail.param2Desc, 2)}>
{domainParamValue(detail.param2Desc, detail.param2)}
</Descriptions.Item>
<Descriptions.Item label={domainParamFieldLabel(detail.param3Desc, 3)}>
{domainParamValue(detail.param3Desc, detail.param3)}
</Descriptions.Item>
<Descriptions.Item label="备注">{detail.remark}</Descriptions.Item> <Descriptions.Item label="备注">{detail.remark}</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item> <Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
</Descriptions> </Descriptions>
@@ -7,11 +7,11 @@ import {
Input, Input,
InputNumber, InputNumber,
Modal, Modal,
Popconfirm,
Select, Select,
Space, Space,
Table, Table,
Tag, Tag,
Typography,
message, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
@@ -29,6 +29,8 @@ import {
import { request } from '../lib/api'; import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const TYPE_OPTIONS = Object.entries(FULFILLMENT_PROVIDER_TYPE_LABELS).map(([value, label]) => ({ const TYPE_OPTIONS = Object.entries(FULFILLMENT_PROVIDER_TYPE_LABELS).map(([value, label]) => ({
@@ -67,7 +69,10 @@ export default function FulfillmentProvidersPage() {
setLoading(true); setLoading(true);
try { try {
const res = await request<FulfillmentProviderDto[]>('/admin/fulfillment-providers'); const res = await request<FulfillmentProviderDto[]>('/admin/fulfillment-providers');
setRows(res); setRows(Array.isArray(res) ? res : []);
} catch (e) {
setRows([]);
message.error(e instanceof Error ? e.message : '加载承运商失败');
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -93,6 +98,7 @@ export default function FulfillmentProvidersPage() {
extraBottleFee: DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee, extraBottleFee: DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
boxBottles: DEFAULT_XFX_LOGISTICS_PRICING.boxBottles, boxBottles: DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
boxFee: DEFAULT_XFX_LOGISTICS_PRICING.boxFee, boxFee: DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
deliveryHintHtml: '',
}); });
setOpen(true); setOpen(true);
} }
@@ -121,6 +127,7 @@ export default function FulfillmentProvidersPage() {
extraBottleFee: pricing?.extraBottleFee ?? DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee, extraBottleFee: pricing?.extraBottleFee ?? DEFAULT_XFX_LOGISTICS_PRICING.extraBottleFee,
boxBottles: pricing?.boxBottles ?? DEFAULT_XFX_LOGISTICS_PRICING.boxBottles, boxBottles: pricing?.boxBottles ?? DEFAULT_XFX_LOGISTICS_PRICING.boxBottles,
boxFee: pricing?.boxFee ?? DEFAULT_XFX_LOGISTICS_PRICING.boxFee, boxFee: pricing?.boxFee ?? DEFAULT_XFX_LOGISTICS_PRICING.boxFee,
deliveryHintHtml: row.deliveryHintHtml || '',
}); });
setOpen(true); setOpen(true);
} }
@@ -143,6 +150,7 @@ export default function FulfillmentProvidersPage() {
boxBottles: v.boxBottles != null ? Number(v.boxBottles) : undefined, boxBottles: v.boxBottles != null ? Number(v.boxBottles) : undefined,
boxFee: v.boxFee != null ? Number(v.boxFee) : undefined, boxFee: v.boxFee != null ? Number(v.boxFee) : undefined,
}, },
deliveryHintHtml: v.deliveryHintHtml?.trim() || null,
}; };
if (isXfxProviderCode(String(v.code)) && v.type === FulfillmentProviderType.API) { if (isXfxProviderCode(String(v.code)) && v.type === FulfillmentProviderType.API) {
@@ -175,9 +183,25 @@ export default function FulfillmentProvidersPage() {
void load(); void load();
} }
async function remove(row: FulfillmentProviderDto) {
try {
await request(`/admin/fulfillment-providers/${row.id}`, { method: 'DELETE' });
message.success('已删除');
void load();
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败');
}
}
const baseColumns: ColumnsType<FulfillmentProviderDto> = [ const baseColumns: ColumnsType<FulfillmentProviderDto> = [
{ title: '编码', dataIndex: 'code', width: 100 }, { title: '编码', dataIndex: 'code', width: 100 },
{ title: '名称', dataIndex: 'name' }, {
title: '名称',
dataIndex: 'name',
render: (v, row) => (
<AdminPrimaryLink onClick={() => openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '类型', title: '类型',
dataIndex: 'type', dataIndex: 'type',
@@ -223,11 +247,23 @@ export default function FulfillmentProvidersPage() {
{ title: '更新时间', dataIndex: 'updatedAt', width: 170, render: fmtTime }, { title: '更新时间', dataIndex: 'updatedAt', width: 170, render: fmtTime },
{ {
title: '操作', title: '操作',
width: 80, width: 140,
render: (_, row) => ( render: (_, row) => (
<Space size={0}>
<Button type="link" size="small" onClick={() => openEdit(row)}> <Button type="link" size="small" onClick={() => openEdit(row)}>
</Button> </Button>
<Popconfirm
title={`确认删除承运商「${row.name}」?`}
okText="删除"
okButtonProps={{ danger: true }}
onConfirm={() => void remove(row)}
>
<Button type="link" size="small" danger>
</Button>
</Popconfirm>
</Space>
), ),
}, },
]; ];
@@ -240,20 +276,16 @@ export default function FulfillmentProvidersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<div> title="仓配管理"
<Typography.Title level={4} style={{ margin: 0 }}> description="注册承运商接口凭证,并配置物流对账用的银行账户、结算方式与计价标准"
settings={settingsButton}
</Typography.Title> actions={
{settingsButton}
<Typography.Text type="secondary">
</Typography.Text>
</div>
<Button type="primary" onClick={openCreate}> <Button type="primary" onClick={openCreate}>
</Button> </Button>
</Space> }
/>
<Alert <Alert
type="info" type="info"
@@ -285,6 +317,17 @@ export default function FulfillmentProvidersPage() {
<Form.Item name="status" label="状态" rules={[{ required: true }]}> <Form.Item name="status" label="状态" rules={[{ required: true }]}>
<Select options={STATUS_OPTIONS} /> <Select options={STATUS_OPTIONS} />
</Form.Item> </Form.Item>
<Form.Item
name="deliveryHintHtml"
label="配送信息提示"
extra="C 端同城送展示。支持 HTMLspan/p/br/b/strong/i/em/fontstyle 可用 color、font-weight、font-size、font-style。回车换行会原样显示。空则回退「同城配送,预计24小时内送到」。"
>
<Input.TextArea
rows={3}
maxLength={2000}
placeholder='<span style="color:#A61D24;font-weight:700;font-size:13px">同城配送,预计24小时内送到</span>'
/>
</Form.Item>
<Divider orientation="left"></Divider> <Divider orientation="left"></Divider>
<Form.Item name="settlementMethod" label="结算方式" rules={[{ required: true }]}> <Form.Item name="settlementMethod" label="结算方式" rules={[{ required: true }]}>
@@ -306,6 +349,7 @@ export default function FulfillmentProvidersPage() {
<Form.Item <Form.Item
name="baseBottles" name="baseBottles"
label="起送瓶数" label="起送瓶数"
extra="物流计价起步瓶数,不影响用户起购(起购在城市管理)"
rules={[{ required: true }]} rules={[{ required: true }]}
style={{ marginBottom: 12 }} style={{ marginBottom: 12 }}
> >
+35 -7
View File
@@ -8,6 +8,8 @@ import { request, type HqProfile, type Paginated } from '../lib/api';
import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants'; import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -69,7 +71,31 @@ export default function HqAccountsPage() {
const cityOptions = cities.map((c) => ({ value: c.id, label: c.name })); const cityOptions = cities.map((c) => ({ value: c.id, label: c.name }));
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '姓名', dataIndex: 'name' }, {
title: '姓名',
dataIndex: 'name',
render: (v, row) =>
isSuperAdmin ? (
<AdminPrimaryLink
onClick={() => {
setDetail(row);
editForm.setFieldsValue({
name: row.name,
phone: row.phone,
loginName: row.loginName,
adminRole: row.adminRole,
status: row.status,
cityIds: row.cityIds ?? [],
});
setDrawerOpen(true);
}}
>
{v}
</AdminPrimaryLink>
) : (
v
),
},
{ title: '用户名', dataIndex: 'loginName', width: 120, render: (v) => v || '—' }, { title: '用户名', dataIndex: 'loginName', width: 120, render: (v) => v || '—' },
{ title: '手机', dataIndex: 'phone', width: 130 }, { title: '手机', dataIndex: 'phone', width: 130 },
{ {
@@ -120,10 +146,11 @@ export default function HqAccountsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}>HQ </Typography.Title> title="HQ 账户"
{settingsButton} settings={settingsButton}
{isSuperAdmin && ( actions={
isSuperAdmin ? (
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -134,8 +161,9 @@ export default function HqAccountsPage() {
> >
</Button> </Button>
)} ) : null
</Space> }
/>
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="phone" label="手机"><Input allowClear /></Form.Item> <Form.Item name="phone" label="手机"><Input allowClear /></Form.Item>
<Form.Item name="adminRole" label="角色"> <Form.Item name="adminRole" label="角色">
+24 -11
View File
@@ -7,9 +7,12 @@ import { useSearchParams } from 'react-router-dom';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { AdminCellLine } from '../components/AdminCellLine'; import { AdminCellLine } from '../components/AdminCellLine';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { formatRef, zhCode } from '../lib/display-labels';
import { HQ_OPERATION_ACTION_OPTIONS, resolveHqOperationLabel } from '../lib/hq-log'; import { HQ_OPERATION_ACTION_OPTIONS, resolveHqOperationLabel } from '../lib/hq-log';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -70,9 +73,19 @@ export default function HqLogsPage() {
title: '行为', title: '行为',
dataIndex: 'actionLabel', dataIndex: 'actionLabel',
width: 160, width: 160,
width: 160, render: (v, r) => (
<AdminPrimaryLink
onClick={async () => {
const res = await request<Row>(`/admin/logs/hq/${r.id}`);
setDetail(res);
setDrawerOpen(true);
}}
>
<Tag color="blue">{v || resolveHqOperationLabel(r.action)}</Tag>
</AdminPrimaryLink>
),
}, },
}, { title: '对象类型', dataIndex: 'refType', width: 120, render: (v) => zhCode(v) },
{ title: '对象 ID', dataIndex: 'refId', width: 100, render: (v) => v || '—' }, { title: '对象 ID', dataIndex: 'refId', width: 100, render: (v) => v || '—' },
{ {
title: '操作', title: '操作',
@@ -98,11 +111,11 @@ export default function HqLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
{settingsModal} <AdminListHeader
<Typography.Title level={4}>HQ </Typography.Title> title="HQ 操作日志"
{settingsButton} settings={settingsButton}
<Typography.Paragraph type="secondary"> description="记录总部后台写操作(开城、订单、用户、权限、合伙人等),仅追加不删除。"
/>
<Form <Form
form={form} form={form}
@@ -131,7 +144,7 @@ export default function HqLogsPage() {
/> />
</Form.Item> </Form.Item>
<Form.Item name="refType" label="对象类型"> <Form.Item name="refType" label="对象类型">
<Form.Item name="refType" label="对象类型"> <Input allowClear placeholder="对象编码" style={{ width: 140 }} />
</Form.Item> </Form.Item>
<Form.Item> <Form.Item>
<Space> <Space>
@@ -180,12 +193,12 @@ export default function HqLogsPage() {
secondary={[detail.hqPhone, detail.hqAccountId ? `ID:${detail.hqAccountId}` : ''].filter(Boolean).join(' ') || null} secondary={[detail.hqPhone, detail.hqAccountId ? `ID:${detail.hqAccountId}` : ''].filter(Boolean).join(' ') || null}
/> />
</Descriptions.Item> </Descriptions.Item>
</Descriptions.Item> <Descriptions.Item label="角色">{zhCode(detail.hqRole)}</Descriptions.Item>
<Descriptions.Item label="行为"> <Descriptions.Item label="行为">
{detail.actionLabel || resolveHqOperationLabel(detail.action)} {detail.actionLabel || resolveHqOperationLabel(detail.action)}
</Descriptions.Item> </Descriptions.Item>
</Descriptions.Item> <Descriptions.Item label="对象">{formatRef(detail.refType, detail.refId)}</Descriptions.Item>
<Descriptions.Item label="对象">{detail.refType} / {detail.refId}</Descriptions.Item> <Descriptions.Item label="状态">{zhCode(detail.status)}</Descriptions.Item>
<Descriptions.Item label="备注">{detail.remark || '—'}</Descriptions.Item> <Descriptions.Item label="备注">{detail.remark || '—'}</Descriptions.Item>
</Descriptions> </Descriptions>
<Typography.Title level={5} style={{ marginTop: 16 }}>/</Typography.Title> <Typography.Title level={5} style={{ marginTop: 16 }}>/</Typography.Title>
@@ -244,7 +244,7 @@ export default function HqPermissionsPage() {
<Typography.Title level={4}></Typography.Title> <Typography.Title level={4}></Typography.Title>
<Typography.Paragraph type="secondary"> <Typography.Paragraph type="secondary">
= =
// //
/ /
// //
</Typography.Paragraph> </Typography.Paragraph>
@@ -274,7 +274,7 @@ export default function HqPermissionsPage() {
<Alert <Alert
type="info" type="info"
showIcon showIcon
message="超级管理员基础权限固定(不含危险操作)。删除用户/订单/城市请到「按用户分配」为具体账号勾选。" message="超级管理员基础权限固定(不含危险操作)。删除用户/订单/城市、修改用户关联合伙人请到「按用户分配」为具体账号勾选。"
/> />
) : ( ) : (
<> <>
+15 -15
View File
@@ -11,7 +11,6 @@ import {
Space, Space,
Table, Table,
Tag, Tag,
Typography,
Upload, Upload,
message, message,
} from 'antd'; } from 'antd';
@@ -31,6 +30,8 @@ import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { uploadFileToOss } from '../lib/upload'; import { uploadFileToOss } from '../lib/upload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -204,7 +205,13 @@ export default function InvoicesPage() {
? INVOICE_CATEGORY_LABELS[r.invoiceCategory] ?? r.invoiceCategory ? INVOICE_CATEGORY_LABELS[r.invoiceCategory] ?? r.invoiceCategory
: '—', : '—',
}, },
{ title: '名称', dataIndex: 'titleName' }, {
title: '名称',
dataIndex: 'titleName',
render: (v, row) => (
<AdminPrimaryLink onClick={() => openDetail(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '状态', title: '状态',
width: 110, width: 110,
@@ -234,18 +241,10 @@ export default function InvoicesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div <AdminListHeader
style={{ title="发票管理"
display: 'flex', settings={settingsButton}
justifyContent: 'space-between', actions={
alignItems: 'center',
marginBottom: 16,
}}
>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
{settingsButton}
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -259,7 +258,8 @@ export default function InvoicesPage() {
> >
</Button> </Button>
</div> }
/>
<Form <Form
form={filterForm} form={filterForm}
layout="inline" layout="inline"
+14 -10
View File
@@ -26,6 +26,8 @@ import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { uploadFileToOss } from '../lib/upload'; import { uploadFileToOss } from '../lib/upload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type FormValues = { type FormValues = {
@@ -127,7 +129,13 @@ export default function KnowledgeBasesPage() {
}; };
const baseColumns: ColumnsType<KnowledgeBaseDto> = [ const baseColumns: ColumnsType<KnowledgeBaseDto> = [
{ title: '名称', dataIndex: 'name' }, {
title: '名称',
dataIndex: 'name',
render: (v, row) => (
<AdminPrimaryLink onClick={() => openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ title: '说明', dataIndex: 'description' }, { title: '说明', dataIndex: 'description' },
{ title: '文档数', dataIndex: 'documentCount', width: 90 }, { title: '文档数', dataIndex: 'documentCount', width: 90 },
{ {
@@ -257,15 +265,11 @@ export default function KnowledgeBasesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16 }} wrap> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="知识库"
settings={settingsButton}
</Typography.Title> description="支持粘贴文本或上传 .txt/.md;可绑定到企微机器人供 AI 检索"
{settingsButton} />
<Typography.Text type="secondary">
.txt/.md AI
</Typography.Text>
</Space>
<Form <Form
form={filterForm} form={filterForm}
+14 -10
View File
@@ -26,6 +26,8 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type FormValues = { type FormValues = {
@@ -156,7 +158,13 @@ export default function LlmConfigsPage() {
}; };
const baseColumns: ColumnsType<LlmApiConfigDto> = [ const baseColumns: ColumnsType<LlmApiConfigDto> = [
{ title: '名称', dataIndex: 'name' }, {
title: '名称',
dataIndex: 'name',
render: (v, row) => (
<AdminPrimaryLink onClick={() => openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '提供商', title: '提供商',
dataIndex: 'provider', dataIndex: 'provider',
@@ -264,15 +272,11 @@ export default function LlmConfigsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16 }} wrap> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="语言模型配置"
settings={settingsButton}
</Typography.Title> description="非超管仅可见自己创建的配置,且创建后只能改是否生效"
{settingsButton} />
<Typography.Text type="secondary">
</Typography.Text>
</Space>
<Form <Form
form={filterForm} form={filterForm}
+15 -10
View File
@@ -30,6 +30,8 @@ import { downloadExcelCsv } from '../lib/exportExcel';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type BillRow = { type BillRow = {
id: string; id: string;
@@ -246,7 +248,14 @@ export default function LogisticsBillsPage() {
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.logisticsAmount), 0); const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.logisticsAmount), 0);
const billColumns: ColumnsType<BillRow> = [ const billColumns: ColumnsType<BillRow> = [
{ title: '账单号', dataIndex: 'billNo', width: 170 }, {
title: '账单号',
dataIndex: 'billNo',
width: 170,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '承运商', title: '承运商',
width: 140, width: 140,
@@ -397,15 +406,11 @@ export default function LogisticsBillsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="物流对账"
settings={settingsButton}
</Typography.Title> description="按快递承运商汇总月度物流费;计价与银行账户在「仓配管理」配置。前期充值扣款,后期可切挂账月结。"
{settingsButton} />
<Typography.Text type="secondary">
</Typography.Text>
</Space>
<Tabs <Tabs
items={[ items={[
+349 -114
View File
@@ -1,10 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom'; import { Link, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { import {
Alert, Alert,
Button, Button,
Checkbox, Checkbox,
Col,
Collapse, Collapse,
DatePicker, DatePicker,
Descriptions, Descriptions,
@@ -14,7 +13,6 @@ import {
InputNumber, InputNumber,
Modal, Modal,
Radio, Radio,
Row,
Select, Select,
Space, Space,
Table, Table,
@@ -24,18 +22,23 @@ import {
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import dayjs, { type Dayjs } from 'dayjs'; import dayjs, { type Dayjs } from 'dayjs';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { ORDER_TYPE_LABELS } from '@dukang/shared-types'; import { ORDER_TYPE_LABELS } from '@dukang/shared-types';
import { request, type AdminOrderItem, type AdminOrderRow, type HqProfile, type Paginated } from '../lib/api'; import { request, type AdminOrderItem, type AdminOrderRow, type HqProfile, type Paginated } from '../lib/api';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import { downloadBase64File } from '../lib/exportExcel'; import { downloadBase64File } from '../lib/exportExcel';
import { import {
ADMIN_OPTIONS_PAGE_SIZE, ADMIN_OPTIONS_PAGE_SIZE,
DELIVERY_PROVIDER_LABELS, DELIVERY_PROVIDER_LABELS,
DELIVERY_TYPE_LABELS,
ORDER_STATUS_COLORS, ORDER_STATUS_COLORS,
ORDER_STATUS_LABELS, ORDER_STATUS_LABELS,
ORDER_STATUS_OPERATOR_LABELS, ORDER_STATUS_OPERATOR_LABELS,
fmtTime, fmtTime,
} from '../lib/constants'; } from '../lib/constants';
import { zhRemark } from '../lib/display-labels';
import { FULFILLMENT_HOLD_REASON_LABELS } from '@dukang/shared-types'; import { FULFILLMENT_HOLD_REASON_LABELS } from '@dukang/shared-types';
import ProxyOrderModal from '../components/ProxyOrderModal'; import ProxyOrderModal from '../components/ProxyOrderModal';
import OrderTrackDrawer from '../components/OrderTrackDrawer'; import OrderTrackDrawer from '../components/OrderTrackDrawer';
@@ -54,6 +57,7 @@ type ShipDefaults = {
}; };
type CityOption = { id: string; name: string; code: string }; type CityOption = { id: string; name: string; code: string };
type PartnerOption = { id: string; companyName?: string | null; name?: string; phone?: string };
type WarehouseOption = { type WarehouseOption = {
id: string; id: string;
@@ -90,6 +94,20 @@ type OrderRedeemSummary = {
redeemRecordSum: number; redeemRecordSum: number;
}; };
type AssocPartnerBrief = {
id: string;
name: string;
companyName?: string | null;
phone?: string | null;
orderCommissionRate?: number | null;
};
function formatAssocPartner(p?: AssocPartnerBrief | null) {
if (!p) return '—';
const title = p.companyName || p.name;
return [title, p.phone].filter(Boolean).join(' / ') || '—';
}
type OrderDetail = AdminOrderRow & { type OrderDetail = AdminOrderRow & {
receiverAddress?: string; receiverAddress?: string;
receiverProvince?: string; receiverProvince?: string;
@@ -133,6 +151,11 @@ type OrderDetail = AdminOrderRow & {
lng?: number | null; lng?: number | null;
lat?: number | null; lat?: number | null;
} | null; } | null;
assocPartnerAtPay?: AssocPartnerBrief | null;
orderCommissionRateAtPay?: number | null;
user?: AdminOrderRow['user'] & {
assocPartner?: AssocPartnerBrief | null;
};
}; };
type ShipMode = 'WAREHOUSE' | 'EXPRESS'; type ShipMode = 'WAREHOUSE' | 'EXPRESS';
@@ -142,13 +165,16 @@ type OrderExportFormat = 'xlsx' | 'pdf';
type OrderExportFilters = { type OrderExportFilters = {
orderNo?: string; orderNo?: string;
status?: string; status?: string | string[];
orderType?: string; orderType?: string;
cityId?: string; cityId?: string;
receiverPhone?: string; receiverPhone?: string;
userKeyword?: string;
productKeyword?: string;
fulfillmentHold?: boolean; fulfillmentHold?: boolean;
excludeTest?: boolean;
deliveryType?: string; deliveryType?: string;
promoCodeId?: string;
assocPartnerAccountId?: string;
dateRange?: [Dayjs, Dayjs]; dateRange?: [Dayjs, Dayjs];
}; };
@@ -208,6 +234,17 @@ const DATE_PRESETS: Array<{ key: 'day' | 'week' | 'month' | 'quarter' | 'year';
{ key: 'year', label: '当年' }, { key: 'year', label: '当年' },
]; ];
const FILTERS_COLLAPSED_KEY = 'admin-orders-filters-collapsed';
function formatUserWithRemark(user?: {
userNo?: string;
hqRemark?: string | null;
} | null) {
const userNo = user?.userNo || '—';
const remark = user?.hqRemark?.trim();
return remark ? `${userNo}${remark}` : userNo;
}
function formatBenefitBrief(row: AdminOrderRow) { function formatBenefitBrief(row: AdminOrderRow) {
const coupon = row.benefitCoupon; const coupon = row.benefitCoupon;
if (coupon) { if (coupon) {
@@ -217,6 +254,12 @@ function formatBenefitBrief(row: AdminOrderRow) {
return '—'; return '—';
} }
function selectedStatuses(status: unknown): string[] {
if (Array.isArray(status)) return status.filter((s): s is string => Boolean(s));
if (typeof status === 'string' && status) return [status];
return [];
}
function buildExportPayload( function buildExportPayload(
scope: OrderExportScope, scope: OrderExportScope,
format: OrderExportFormat, format: OrderExportFormat,
@@ -229,13 +272,17 @@ function buildExportPayload(
return payload; return payload;
} }
if (filters.orderNo) payload.orderNo = filters.orderNo; if (filters.orderNo) payload.orderNo = filters.orderNo;
if (filters.status) payload.status = filters.status; const statuses = selectedStatuses(filters.status);
if (statuses.length) payload.status = statuses;
if (filters.orderType) payload.orderType = filters.orderType; if (filters.orderType) payload.orderType = filters.orderType;
if (filters.cityId) payload.cityId = filters.cityId; if (filters.cityId) payload.cityId = filters.cityId;
if (filters.receiverPhone) payload.receiverPhone = filters.receiverPhone; if (filters.receiverPhone) payload.receiverPhone = filters.receiverPhone;
if (filters.userKeyword) payload.userKeyword = filters.userKeyword;
if (filters.productKeyword) payload.productKeyword = filters.productKeyword;
if (filters.deliveryType) payload.deliveryType = filters.deliveryType; if (filters.deliveryType) payload.deliveryType = filters.deliveryType;
if (filters.fulfillmentHold) payload.fulfillmentHold = true; if (filters.fulfillmentHold) payload.fulfillmentHold = true;
if (filters.excludeTest) payload.excludeTest = true; if (filters.promoCodeId) payload.promoCodeId = filters.promoCodeId;
if (filters.assocPartnerAccountId) payload.assocPartnerAccountId = filters.assocPartnerAccountId;
if (filters.dateRange?.[0]) payload.createdFrom = filters.dateRange[0].format('YYYY-MM-DD'); if (filters.dateRange?.[0]) payload.createdFrom = filters.dateRange[0].format('YYYY-MM-DD');
if (filters.dateRange?.[1]) payload.createdTo = filters.dateRange[1].format('YYYY-MM-DD'); if (filters.dateRange?.[1]) payload.createdTo = filters.dateRange[1].format('YYYY-MM-DD');
return payload; return payload;
@@ -273,8 +320,16 @@ function warehouseToDefaults(wh: WarehouseOption, base?: ShipDefaults | null): S
} }
export default function OrdersPage() { export default function OrdersPage() {
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const initialOrderNo = searchParams.get('orderNo')?.trim() || ''; const initialOrderNo = searchParams.get('orderNo')?.trim() || '';
const initialPromoCodeId = searchParams.get('promoCodeId')?.trim() || '';
const initialStatusParam = searchParams.getAll('status').join(',');
const initialStatuses = useMemo(
() => initialStatusParam.split(',').map((s) => s.trim()).filter(Boolean),
[initialStatusParam],
);
const [form] = Form.useForm(); const [form] = Form.useForm();
const [shipForm] = Form.useForm(); const [shipForm] = Form.useForm();
const [logisticsForm] = Form.useForm(); const [logisticsForm] = Form.useForm();
@@ -297,6 +352,7 @@ export default function OrdersPage() {
const [shipping, setShipping] = useState(false); const [shipping, setShipping] = useState(false);
const [logisticsShipping, setLogisticsShipping] = useState(false); const [logisticsShipping, setLogisticsShipping] = useState(false);
const [cities, setCities] = useState<CityOption[]>([]); const [cities, setCities] = useState<CityOption[]>([]);
const [partners, setPartners] = useState<PartnerOption[]>([]);
const [shipModalOpen, setShipModalOpen] = useState(false); const [shipModalOpen, setShipModalOpen] = useState(false);
const [shipTarget, setShipTarget] = useState<OrderDetail | null>(null); const [shipTarget, setShipTarget] = useState<OrderDetail | null>(null);
const [shipMode, setShipMode] = useState<ShipMode>('EXPRESS'); const [shipMode, setShipMode] = useState<ShipMode>('EXPRESS');
@@ -305,6 +361,13 @@ export default function OrdersPage() {
const [trackOpen, setTrackOpen] = useState(false); const [trackOpen, setTrackOpen] = useState(false);
const [exporting, setExporting] = useState(false); const [exporting, setExporting] = useState(false);
const [exportFormat, setExportFormat] = useState<OrderExportFormat>('xlsx'); const [exportFormat, setExportFormat] = useState<OrderExportFormat>('xlsx');
const [filtersCollapsed, setFiltersCollapsed] = useState(() => {
try {
return localStorage.getItem(FILTERS_COLLAPSED_KEY) === '1';
} catch {
return false;
}
});
const canDeleteOrders = (profile?.permissionKeys ?? []).includes('orders_delete'); const canDeleteOrders = (profile?.permissionKeys ?? []).includes('orders_delete');
const canProxyOrder = (profile?.permissionKeys ?? []).includes('orders'); const canProxyOrder = (profile?.permissionKeys ?? []).includes('orders');
const canExportOrders = (profile?.permissionKeys ?? []).includes('orders'); const canExportOrders = (profile?.permissionKeys ?? []).includes('orders');
@@ -324,6 +387,20 @@ export default function OrdersPage() {
} }
}, [form, initialOrderNo]); }, [form, initialOrderNo]);
useEffect(() => {
if (initialStatuses.length) {
form.setFieldsValue({ status: initialStatuses });
}
}, [form, initialStatuses]);
useEffect(() => {
const openOrderId = (location.state as { openOrderId?: string } | null)?.openOrderId;
if (openOrderId) {
void openDetail(openOrderId);
navigate(`${location.pathname}${location.search}`, { replace: true, state: null });
}
}, [location.state, location.pathname, location.search, navigate]);
useEffect(() => { useEffect(() => {
if (!initialOrderNo || deepLinkOpenedRef.current || loading) return; if (!initialOrderNo || deepLinkOpenedRef.current || loading) return;
const first = data?.items?.[0]; const first = data?.items?.[0];
@@ -354,13 +431,18 @@ export default function OrdersPage() {
const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) }); const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
if (initialOrderNo) qs.set('orderNo', initialOrderNo); if (initialOrderNo) qs.set('orderNo', initialOrderNo);
if (values.orderNo) qs.set('orderNo', values.orderNo); if (values.orderNo) qs.set('orderNo', values.orderNo);
if (values.status) qs.set('status', values.status); const statuses = selectedStatuses(values.status);
const statusList = statuses.length ? statuses : initialStatuses;
for (const status of statusList) qs.append('status', status);
if (values.orderType) qs.set('orderType', values.orderType); if (values.orderType) qs.set('orderType', values.orderType);
if (values.cityId) qs.set('cityId', values.cityId); if (values.cityId) qs.set('cityId', values.cityId);
if (values.receiverPhone) qs.set('receiverPhone', values.receiverPhone); if (values.receiverPhone) qs.set('receiverPhone', values.receiverPhone);
if (values.userKeyword) qs.set('userKeyword', values.userKeyword);
if (values.productKeyword) qs.set('productKeyword', values.productKeyword);
if (values.fulfillmentHold) qs.set('fulfillmentHold', 'true'); if (values.fulfillmentHold) qs.set('fulfillmentHold', 'true');
if (values.excludeTest) qs.set('excludeTest', 'true');
if (values.deliveryType) qs.set('deliveryType', values.deliveryType); if (values.deliveryType) qs.set('deliveryType', values.deliveryType);
if (values.assocPartnerAccountId) qs.set('assocPartnerAccountId', values.assocPartnerAccountId);
if (initialPromoCodeId) qs.set('promoCodeId', initialPromoCodeId);
if (values.dateRange?.[0]) qs.set('createdFrom', values.dateRange[0].format('YYYY-MM-DD')); if (values.dateRange?.[0]) qs.set('createdFrom', values.dateRange[0].format('YYYY-MM-DD'));
if (values.dateRange?.[1]) qs.set('createdTo', values.dateRange[1].format('YYYY-MM-DD')); if (values.dateRange?.[1]) qs.set('createdTo', values.dateRange[1].format('YYYY-MM-DD'));
const res = await request<Paginated<AdminOrderRow>>(`/admin/orders?${qs}`); const res = await request<Paginated<AdminOrderRow>>(`/admin/orders?${qs}`);
@@ -368,7 +450,7 @@ export default function OrdersPage() {
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [form, page, pageSize, initialOrderNo]); }, [form, page, pageSize, initialOrderNo, initialPromoCodeId, initialStatuses]);
useEffect(() => { useEffect(() => {
void load(); void load();
@@ -379,6 +461,9 @@ export default function OrdersPage() {
void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`) void request<Paginated<CityOption>>(`/admin/cities?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
.then((res) => setCities(res.items ?? [])) .then((res) => setCities(res.items ?? []))
.catch(() => {}); .catch(() => {});
void request<Paginated<PartnerOption>>(`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
.then((res) => setPartners(res.items ?? []))
.catch(() => setPartners([]));
}, []); }, []);
function applyShipDefaults(defaults: ShipDefaults, warehouseId?: string | null) { function applyShipDefaults(defaults: ShipDefaults, warehouseId?: string | null) {
@@ -577,7 +662,16 @@ export default function OrdersPage() {
} }
setExporting(true); setExporting(true);
try { try {
const payload = buildExportPayload(scope, exportFormat, values, selectedRowKeys); const payload = buildExportPayload(
scope,
exportFormat,
{
...values,
promoCodeId: initialPromoCodeId || values.promoCodeId,
status: selectedStatuses(values.status).length ? values.status : initialStatuses,
},
selectedRowKeys,
);
const result = await request<OrderExportResult>('/admin/orders/export', { const result = await request<OrderExportResult>('/admin/orders/export', {
method: 'POST', method: 'POST',
body: JSON.stringify(payload), body: JSON.stringify(payload),
@@ -592,64 +686,106 @@ export default function OrdersPage() {
} }
const baseColumns: ColumnsType<AdminOrderRow> = [ const baseColumns: ColumnsType<AdminOrderRow> = [
{
title: '订单号',
dataIndex: 'orderNo',
width: 180,
render: (v, row) => (
<Space size={4}>
<AdminPrimaryLink onClick={() => openDetail(row.id)}>{v}</AdminPrimaryLink>
{row.isTest ? <Tag color="orange"></Tag> : null}
</Space>
),
},
{
title: '用户',
key: 'user',
width: 200,
render: (_, row) =>
row.user?.id ? (
<AdminPrimaryLink onClick={() => navigate(`/users?userId=${encodeURIComponent(String(row.user!.id))}`)}>
{formatUserWithRemark(row.user)}
</AdminPrimaryLink>
) : (
formatUserWithRemark(row.user)
),
},
{ {
title: '商品', title: '商品',
width: 240, key: 'productName',
width: 180,
render: (_, row) => ( render: (_, row) => (
<div>
<Space size={4} wrap> <Space size={4} wrap>
<span>{row.productName || '—'}</span> <span>{row.productName || '—'}</span>
{row.isTest ? <Tag color="orange"></Tag> : null}
{row.fulfillmentHold ? <Tag color="orange"></Tag> : null} {row.fulfillmentHold ? <Tag color="orange"></Tag> : null}
{row.orderType === 'PROXY' || row.isProxyOrder ? ( {row.orderType === 'PROXY' || row.isProxyOrder ? (
<Tag color="purple"></Tag> <Tag color="purple"></Tag>
) : null} ) : null}
</Space> </Space>
<div>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{[row.productSpec, row.quantity != null ? `×${row.quantity}` : null]
.filter(Boolean)
.join(' ')}
</Typography.Text>
</div>
</div>
), ),
}, },
{ {
title: '状态 / 实付', title: '规格',
width: 130, dataIndex: 'productSpec',
render: (_, row) => ( width: 140,
<div> render: (v: string | undefined) => v || '—',
<Tag color={ORDER_STATUS_COLORS[row.status] || 'default'}> },
{ORDER_STATUS_LABELS[row.status] || row.status} {
</Tag> title: '数量',
<div>¥{row.payAmount}</div> dataIndex: 'quantity',
</div> width: 80,
render: (v: number | undefined, row) =>
v == null ? '—' : `${v}${row.saleUnit === 'BOX' ? '箱' : '瓶'}`,
},
{
title: '配送方式',
dataIndex: 'deliveryType',
width: 100,
render: (v: string | undefined) => DELIVERY_TYPE_LABELS[v ?? ''] || v || '—',
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (s: string) => (
<Tag color={ORDER_STATUS_COLORS[s] || 'default'}>{ORDER_STATUS_LABELS[s] || s}</Tag>
), ),
}, },
{
title: '实付',
dataIndex: 'payAmount',
width: 90,
render: (v: number) => `¥${v}`,
},
{
title: '运费',
key: 'logisticsFee',
width: 90,
render: (_, row) =>
row.delivery?.logisticsFee == null ? '—' : `¥${Number(row.delivery.logisticsFee).toFixed(2)}`,
},
{ {
title: '好客权益', title: '好客权益',
width: 200, width: 200,
render: (_, row) => formatBenefitBrief(row), render: (_, row) => formatBenefitBrief(row),
}, },
{ {
title: '收货信息', title: '收货',
width: 240, dataIndex: 'receiverName',
render: (_, row) => { width: 90,
const address = formatReceiverAddress(row); render: (v: string | undefined) => v || '—',
return (
<div>
<div>
{row.receiverName || '—'} {row.receiverPhone || ''}
</div>
{address ? (
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{address}
</Typography.Text>
) : null}
</div>
);
}, },
{
title: '电话',
dataIndex: 'receiverPhone',
width: 120,
render: (v: string | undefined) => v || '—',
},
{
title: '地址',
key: 'receiverAddress',
width: 260,
render: (_, row) => formatReceiverAddress(row) || '—',
}, },
{ {
title: '下单时间', title: '下单时间',
@@ -695,18 +831,20 @@ export default function OrdersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 20, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="订单监控"
<Space size={12}> settings={settingsButton}
{settingsButton} actions={
<>
<Button onClick={() => window.open('/orders/big-screen', 'dukang-big-screen')}></Button> <Button onClick={() => window.open('/orders/big-screen', 'dukang-big-screen')}></Button>
{canProxyOrder ? ( {canProxyOrder ? (
<Button type="primary" onClick={() => setProxyOpen(true)}> <Button type="primary" onClick={() => setProxyOpen(true)}>
</Button> </Button>
) : null} ) : null}
</Space> </>
</Space> }
/>
{!canDeleteOrders && profile ? ( {!canDeleteOrders && profile ? (
<Alert <Alert
@@ -722,15 +860,117 @@ export default function OrdersPage() {
/> />
) : null} ) : null}
{initialPromoCodeId ? (
<Alert
type="info"
showIcon
closable
style={{ marginBottom: 16 }}
message={
initialStatuses.includes('COMPLETED') && initialStatuses.length === 1
? '已按推广码筛选已完成订单'
: '已按推广码筛选订单'
}
action={
<Button size="small" onClick={() => navigate('/orders')}>
</Button>
}
onClose={() => navigate('/orders')}
/>
) : null}
<Form form={form} layout="vertical" onFinish={() => { setPage(1); void load(); }}> <Form form={form} layout="vertical" onFinish={() => { setPage(1); void load(); }}>
<Row gutter={[16, 8]}> <div className="admin-orders-filter-row">
<Col xs={24} md={14} lg={12}> <Form.Item name="cityId" label="城市" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Form.Item label="下单日期" style={{ marginBottom: 12 }}> <Select
<Space direction="vertical" size={8} style={{ width: '100%' }}> allowClear
<Form.Item name="dateRange" noStyle> showSearch
<DatePicker.RangePicker allowClear style={{ width: '100%' }} /> optionFilterProp="label"
placeholder="全部"
options={cities.map((c) => ({ value: c.id, label: c.name }))}
/>
</Form.Item> </Form.Item>
<Form.Item name="receiverPhone" label="手机号" className="admin-orders-filter-item admin-orders-filter-item--md">
<Input allowClear placeholder="手机号" />
</Form.Item>
<Form.Item name="userKeyword" label="用户" className="admin-orders-filter-item admin-orders-filter-item--search">
<Input allowClear placeholder="编号/昵称/备注/手机" />
</Form.Item>
<Form.Item name="productKeyword" label="商品" className="admin-orders-filter-item admin-orders-filter-item--search">
<Input allowClear placeholder="名称/规格" />
</Form.Item>
<Form.Item name="status" label="状态" className="admin-orders-filter-item admin-orders-filter-item--status">
<Select
mode="multiple"
allowClear
maxTagCount="responsive"
placeholder="全部"
options={Object.entries(ORDER_STATUS_LABELS).map(([value, label]) => ({ value, label }))}
/>
</Form.Item>
<Form.Item name="orderType" label="类型" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Select allowClear placeholder="全部" options={ORDER_TYPE_OPTIONS} />
</Form.Item>
<Form.Item name="deliveryType" label="配送" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Select allowClear placeholder="全部" options={DELIVERY_TYPE_OPTIONS} />
</Form.Item>
<Form.Item
name="assocPartnerAccountId"
label="关联合伙人"
className="admin-orders-filter-item admin-orders-filter-item--status"
>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="全部"
options={[
{ value: 'none', label: '未关联' },
...partners.map((p) => ({
value: p.id,
label: formatAssocPartner({
id: p.id,
name: p.name || p.id,
companyName: p.companyName,
phone: p.phone,
}),
})),
]}
/>
</Form.Item>
<Form.Item label=" " colon={false} className="admin-orders-filter-item admin-orders-filter-actions">
<Space size={8} wrap> <Space size={8} wrap>
<Button type="primary" htmlType="submit"></Button>
<Button
type="link"
icon={filtersCollapsed ? <DownOutlined /> : <UpOutlined />}
onClick={() => {
setFiltersCollapsed((prev) => {
const next = !prev;
try {
localStorage.setItem(FILTERS_COLLAPSED_KEY, next ? '1' : '0');
} catch {
/* ignore */
}
return next;
});
}}
>
{filtersCollapsed ? '展开' : '收起'}
</Button>
</Space>
</Form.Item>
</div>
{!filtersCollapsed ? (
<>
<div className="admin-orders-filter-row">
<Form.Item label="下单日期" className="admin-orders-filter-item admin-orders-filter-item--date">
<Space size={8} wrap>
<Form.Item name="dateRange" noStyle>
<DatePicker.RangePicker allowClear className="admin-orders-date-picker" />
</Form.Item>
{DATE_PRESETS.map((preset) => ( {DATE_PRESETS.map((preset) => (
<Button <Button
key={preset.key} key={preset.key}
@@ -741,59 +981,10 @@ export default function OrdersPage() {
</Button> </Button>
))} ))}
</Space> </Space>
</Space>
</Form.Item> </Form.Item>
</Col> </div>
<Col xs={12} sm={6} md={5} lg={3}>
<Form.Item name="status" label="状态" style={{ marginBottom: 12 }}>
<Select
allowClear
placeholder="全部"
options={Object.entries(ORDER_STATUS_LABELS).map(([value, label]) => ({ value, label }))}
/>
</Form.Item>
</Col>
<Col xs={12} sm={6} md={5} lg={3}>
<Form.Item name="orderType" label="类型" style={{ marginBottom: 12 }}>
<Select allowClear placeholder="全部" options={ORDER_TYPE_OPTIONS} />
</Form.Item>
</Col>
<Col xs={12} sm={6} md={5} lg={3}>
<Form.Item name="deliveryType" label="配送" style={{ marginBottom: 12 }}>
<Select allowClear placeholder="全部" options={DELIVERY_TYPE_OPTIONS} />
</Form.Item>
</Col>
<Col xs={12} sm={6} md={5} lg={3}>
<Form.Item name="cityId" label="城市" style={{ marginBottom: 12 }}>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="全部"
options={cities.map((c) => ({ value: c.id, label: c.name }))}
/>
</Form.Item>
</Col>
<Col xs={12} sm={8} md={6} lg={6}>
<Form.Item name="receiverPhone" label="收货手机" style={{ marginBottom: 12 }}>
<Input allowClear placeholder="手机号" />
</Form.Item>
</Col>
<Col xs={12} sm={8} md={8} lg={8}>
<Form.Item label=" " colon={false} style={{ marginBottom: 12 }}>
<Space size={16} wrap>
<Form.Item name="fulfillmentHold" valuePropName="checked" noStyle>
<Checkbox></Checkbox>
</Form.Item>
<Form.Item name="excludeTest" valuePropName="checked" noStyle>
<Checkbox></Checkbox>
</Form.Item>
</Space>
</Form.Item>
</Col>
</Row>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '8px 0 16px', gap: 12, flexWrap: 'wrap' }}> <div className="admin-orders-filter-row admin-orders-filter-row--tools">
{canExportOrders ? ( {canExportOrders ? (
<Space size={12} wrap> <Space size={12} wrap>
<Radio.Group <Radio.Group
@@ -818,8 +1009,19 @@ export default function OrdersPage() {
</Space> </Space>
) : <span />} ) : <span />}
<Space size={12} wrap> <Space size={12} wrap>
<Button type="primary" htmlType="submit"></Button> <Form.Item name="fulfillmentHold" valuePropName="checked" noStyle>
<Button onClick={() => { form.resetFields(); setPage(1); void load(); }}></Button> <Checkbox></Checkbox>
</Form.Item>
<Button
onClick={() => {
form.resetFields();
setPage(1);
if (initialPromoCodeId || initialOrderNo || initialStatuses.length) navigate('/orders');
else void load();
}}
>
</Button>
{canDeleteOrders ? ( {canDeleteOrders ? (
<Button <Button
danger danger
@@ -831,6 +1033,8 @@ export default function OrdersPage() {
) : null} ) : null}
</Space> </Space>
</div> </div>
</>
) : null}
</Form> </Form>
<Table <Table
@@ -929,7 +1133,33 @@ export default function OrdersPage() {
{[detail.proxyPartnerName, detail.proxyPartnerPhone].filter(Boolean).join(' / ') || '—'} {[detail.proxyPartnerName, detail.proxyPartnerPhone].filter(Boolean).join(' / ') || '—'}
</Descriptions.Item> </Descriptions.Item>
) : null} ) : null}
<Descriptions.Item label="用户">{detail.user?.userNo} / {detail.user?.nickname}</Descriptions.Item> <Descriptions.Item label="关联合伙人(本单佣金)">
{detail.assocPartnerAtPay
? `${formatAssocPartner(detail.assocPartnerAtPay)}${
detail.assocPartnerAtPay.orderCommissionRate != null
? ` · 费率 ${(Number(detail.assocPartnerAtPay.orderCommissionRate) * 100).toFixed(2)}%`
: ''
}`
: '—'}
</Descriptions.Item>
{detail.user?.assocPartner &&
detail.user.assocPartner.id !== detail.assocPartnerAtPay?.id ? (
<Descriptions.Item label="用户当前关联">
{formatAssocPartner(detail.user.assocPartner)}
</Descriptions.Item>
) : null}
<Descriptions.Item label="用户">
{detail.user?.id ? (
<AdminPrimaryLink
onClick={() => navigate(`/users?userId=${encodeURIComponent(String(detail.user!.id))}`)}
>
{formatUserWithRemark(detail.user)}
</AdminPrimaryLink>
) : (
formatUserWithRemark(detail.user)
)}
{detail.user?.nickname ? ` / ${detail.user.nickname}` : ''}
</Descriptions.Item>
<Descriptions.Item label="商品额">¥{detail.productAmount}</Descriptions.Item> <Descriptions.Item label="商品额">¥{detail.productAmount}</Descriptions.Item>
<Descriptions.Item label="实付">¥{detail.payAmount}</Descriptions.Item> <Descriptions.Item label="实付">¥{detail.payAmount}</Descriptions.Item>
<Descriptions.Item label="好客权益">¥{detail.benefitAmount}</Descriptions.Item> <Descriptions.Item label="好客权益">¥{detail.benefitAmount}</Descriptions.Item>
@@ -1108,6 +1338,11 @@ export default function OrdersPage() {
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="运单号">{detail.delivery.trackingNo || '—'}</Descriptions.Item> <Descriptions.Item label="运单号">{detail.delivery.trackingNo || '—'}</Descriptions.Item>
<Descriptions.Item label="三方单号">{detail.delivery.providerOrderNo || '—'}</Descriptions.Item> <Descriptions.Item label="三方单号">{detail.delivery.providerOrderNo || '—'}</Descriptions.Item>
<Descriptions.Item label="运费">
{detail.delivery.logisticsFee == null
? '—'
: `¥${Number(detail.delivery.logisticsFee).toFixed(2)}`}
</Descriptions.Item>
{detail.delivery.manualQueryUrl && ( {detail.delivery.manualQueryUrl && (
<Descriptions.Item label="查询链接"> <Descriptions.Item label="查询链接">
<a href={detail.delivery.manualQueryUrl} target="_blank" rel="noreferrer"> <a href={detail.delivery.manualQueryUrl} target="_blank" rel="noreferrer">
@@ -1148,7 +1383,7 @@ export default function OrdersPage() {
{ {
title: '备注', title: '备注',
dataIndex: 'remark', dataIndex: 'remark',
render: (v) => v || '—', render: (v) => zhRemark(v),
}, },
{ {
title: '时间', title: '时间',
@@ -5,9 +5,11 @@ import {
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { PARTNER_PERMISSION_KEYS, PARTNER_PERMISSION_LABELS, PARTNER_STAFF_ROLE_LABELS, type PartnerPermissionKey } from '@dukang/shared-types'; import { PARTNER_PERMISSION_KEYS, PARTNER_PERMISSION_LABELS, PARTNER_STAFF_ROLE_LABELS, type PartnerPermissionKey } from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { AdminCellLine } from '../components/AdminCellLine'; import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, ORDER_STATUS_LABELS, PARTNER_BILL_STATUS_LABELS, fmtTime } from '../lib/constants'; import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, ORDER_STATUS_LABELS, PARTNER_BILL_STATUS_LABELS, fmtTime } from '../lib/constants';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import PartnerAssocPanel from '../components/PartnerAssocPanel';
type PartnerOption = { id: string; companyName: string }; type PartnerOption = { id: string; companyName: string };
@@ -176,14 +178,13 @@ export default function PartnerAccountsPage() {
title: '姓名 / 类型', title: '姓名 / 类型',
width: 200, width: 200,
render: (_, row) => ( render: (_, row) => (
<AdminCellLine <span className="admin-cell-line">
primary={row.name} <AdminPrimaryLink onClick={() => void openAccount(row.id)}>{row.name}</AdminPrimaryLink>
secondary={ <span className="admin-cell-line-secondary">
row.parentAccountId {' · '}
? `子账号 · ${staffRoleLabel(row.staffRole)}` {row.parentAccountId ? `子账号 · ${staffRoleLabel(row.staffRole)}` : '主账号'}
: '主账号' </span>
} </span>
/>
), ),
}, },
{ title: '手机', dataIndex: 'phone', width: 120 }, { title: '手机', dataIndex: 'phone', width: 120 },
@@ -262,15 +263,11 @@ export default function PartnerAccountsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<div> title="合伙人子账号"
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> settings={settingsButton}
{settingsButton} description="主账号在「开城合伙人」创建;此处仅管理子账号树与权限"
<Typography.Text type="secondary"> />
</Typography.Text>
</div>
</Space>
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
@@ -417,6 +414,13 @@ export default function PartnerAccountsPage() {
dataSource={detail.orders ?? []} pagination={false} scroll={{ x: 'max-content' }} /> dataSource={detail.orders ?? []} pagination={false} scroll={{ x: 'max-content' }} />
), ),
}, },
...(!detail.parentAccountId
? [{
key: 'assoc',
label: '关联码',
children: <PartnerAssocPanel partnerId={detail.id} />,
}]
: []),
]} /> ]} />
)} )}
</Drawer> </Drawer>
+110 -11
View File
@@ -12,6 +12,7 @@ import {
Space, Space,
Statistic, Statistic,
Table, Table,
Tabs,
Tag, Tag,
Typography, Typography,
message, message,
@@ -23,8 +24,23 @@ import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { downloadExcelCsv } from '../lib/exportExcel'; import { downloadExcelCsv } from '../lib/exportExcel';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type BillItemRow = {
id: string;
kind: 'ORDER' | 'REDEEM';
refId: string;
refNo: string;
title?: string | null;
extra?: string | null;
baseAmount: number;
rate: number;
commission: number;
occurredAt: string;
};
type Row = { type Row = {
id: string; id: string;
billNo: string; billNo: string;
@@ -37,6 +53,8 @@ type Row = {
rejectReason?: string | null; rejectReason?: string | null;
paymentRef?: string | null; paymentRef?: string | null;
paidAt?: string | null; paidAt?: string | null;
orderItems?: BillItemRow[];
redeemItems?: BillItemRow[];
partner?: { partner?: {
companyName?: string; companyName?: string;
phone?: string; phone?: string;
@@ -247,7 +265,14 @@ export default function PartnerBillsPage() {
const payAmount = canPay.reduce((s, r) => s + Number(r.totalAmount), 0); const payAmount = canPay.reduce((s, r) => s + Number(r.totalAmount), 0);
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '账单号', dataIndex: 'billNo', width: 180 }, {
title: '账单号',
dataIndex: 'billNo',
width: 180,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '合伙人', title: '合伙人',
width: 160, width: 160,
@@ -341,15 +366,11 @@ export default function PartnerBillsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
return ( <AdminListHeader
<div> title="合伙人账单"
{settingsModal} settings={settingsButton}
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}> description="每月 1 日 8:00 自动生成上月账单(待审核)→ 发送合伙人确认 → 未打款 → 已打款"
<Typography.Title level={4} style={{ margin: 0 }}> />
</Typography.Title>
{settingsButton}
<Typography.Text type="secondary">
{summary && ( {summary && (
<Card size="small" style={{ marginBottom: 16 }}> <Card size="small" style={{ marginBottom: 16 }}>
@@ -526,7 +547,7 @@ export default function PartnerBillsPage() {
title="合伙人账单明细" title="合伙人账单明细"
open={drawerOpen} open={drawerOpen}
onClose={() => setDrawerOpen(false)} onClose={() => setDrawerOpen(false)}
title="合伙人账单明细" width={720}
> >
{detail && ( {detail && (
<> <>
@@ -557,6 +578,84 @@ export default function PartnerBillsPage() {
{detail.paymentRef ? String(detail.paymentRef) : '—'} {detail.paymentRef ? String(detail.paymentRef) : '—'}
</Descriptions.Item> </Descriptions.Item>
</Descriptions> </Descriptions>
<Tabs
style={{ marginTop: 16 }}
items={[
{
key: 'orders',
label: `酒订单 (${detail.orderItems?.length ?? 0})`,
children: (
<>
<Table
rowKey="id"
size="small"
pagination={false}
dataSource={detail.orderItems ?? []}
columns={[
{ title: '订单号', dataIndex: 'refNo', width: 160 },
{ title: '商品', dataIndex: 'title' },
{ title: '数量', dataIndex: 'extra', width: 70 },
{
title: '实付',
dataIndex: 'baseAmount',
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '费率',
dataIndex: 'rate',
render: (v: number) => `${(Number(v) * 100).toFixed(2)}%`,
},
{
title: '佣金',
dataIndex: 'commission',
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
]}
/>
<Typography.Paragraph style={{ textAlign: 'right', marginTop: 8 }}>
¥{Number(detail.orderCommission).toFixed(2)}
</Typography.Paragraph>
</>
),
},
{
key: 'redeems',
label: `核销订单 (${detail.redeemItems?.length ?? 0})`,
children: (
<>
<Table
rowKey="id"
size="small"
pagination={false}
dataSource={detail.redeemItems ?? []}
columns={[
{ title: '核销单号', dataIndex: 'refNo', width: 160 },
{ title: '门店', dataIndex: 'title' },
{
title: '核销额',
dataIndex: 'baseAmount',
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '费率',
dataIndex: 'rate',
render: (v: number) => `${(Number(v) * 100).toFixed(2)}%`,
},
{
title: '佣金',
dataIndex: 'commission',
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
]}
/>
<Typography.Paragraph style={{ textAlign: 'right', marginTop: 8 }}>
¥{Number(detail.redeemCommission).toFixed(2)}
</Typography.Paragraph>
</>
),
},
]}
/>
<Typography.Title level={5} style={{ marginTop: 16 }}> <Typography.Title level={5} style={{ marginTop: 16 }}>
</Typography.Title> </Typography.Title>
+37 -17
View File
@@ -4,17 +4,18 @@ import type { ColumnsType } from 'antd/es/table';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
import { import {
PARTNER_LOG_CATEGORY_OPTIONS, PARTNER_LOG_CATEGORY_OPTIONS,
PARTNER_LOG_CATEGORY_LABELS,
PARTNER_STAFF_ROLE_LABELS, PARTNER_STAFF_ROLE_LABELS,
resolvePartnerLogCategory,
type PartnerLogCategory, type PartnerLogCategory,
type PartnerStaffRole, type PartnerStaffRole,
} from '@dukang/shared-types'; } from '@dukang/shared-types';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { AdminCellLine } from '../components/AdminCellLine'; import { AdminCellLine } from '../components/AdminCellLine';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { clientAppLabel, eventNameLabel, formatRef, partnerEventCategoryLabel } from '../lib/display-labels';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -105,14 +106,28 @@ export default function PartnerLogsPage() {
dataIndex: 'category', dataIndex: 'category',
width: 100, width: 100,
render: (v: PartnerLogCategory | null, r) => ( render: (v: PartnerLogCategory | null, r) => (
width: 100, <Tag>{partnerEventCategoryLabel(r.eventName, v)}</Tag>
),
},
{
title: '事件',
dataIndex: 'eventName',
width: 180,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
setDetail(await request(`/admin/logs/partners/${row.id}`));
setDrawerOpen(true);
}}
>
{eventNameLabel(v)}
</AdminPrimaryLink>
), ),
}, },
),
{ {
title: '关联', title: '关联',
width: 120, width: 120,
title: '关联', render: (_, r) => formatRef(r.refType, r.refId),
}, },
{ {
title: '摘要', title: '摘要',
@@ -141,10 +156,7 @@ export default function PartnerLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
return ( <AdminListHeader title="合伙人日志" settings={settingsButton} />
<div>
{settingsModal}
<Typography.Title level={4} style={{ marginBottom: 16 }}>
<Segmented <Segmented
options={PARTNER_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))} options={PARTNER_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))}
value={category} value={category}
@@ -175,11 +187,11 @@ export default function PartnerLogsPage() {
<Form.Item name="companyName" label="公司"> <Form.Item name="companyName" label="公司">
<Input placeholder="合伙人公司" allowClear style={{ width: 140 }} /> <Input placeholder="合伙人公司" allowClear style={{ width: 140 }} />
</Form.Item> </Form.Item>
<Form.Item name="companyName" label="公司"> <Form.Item name="partnerId" label="合伙人 ID">
<Input placeholder="合伙人公司" allowClear style={{ width: 140 }} /> <Input placeholder="合伙人 ID" allowClear style={{ width: 120 }} />
</Form.Item> </Form.Item>
<Form.Item name="partnerId" label="合伙人ID"> <Form.Item name="eventName" label="事件编码">
<Input placeholder="partnerId" allowClear style={{ width: 120 }} /> <Input placeholder="事件编码" allowClear style={{ width: 160 }} />
</Form.Item> </Form.Item>
<Form.Item> <Form.Item>
<Space> <Space>
@@ -224,11 +236,19 @@ export default function PartnerLogsPage() {
<Drawer title="日志详情" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}> <Drawer title="日志详情" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}>
{detail && ( {detail && (
<Descriptions column={1} bordered size="small"> <Descriptions column={1} bordered size="small">
<Drawer title="日志详情" open={drawerOpen} onClose={() => setDrawerOpen(false)} width={520}> <Descriptions.Item label="ID">{String(detail.id ?? '—')}</Descriptions.Item>
{detail && ( <Descriptions.Item label="合伙人">{String(detail.companyName || detail.partnerId || '—')}</Descriptions.Item>
<Descriptions column={1} bordered size="small"> <Descriptions.Item label="账号">{String(detail.accountName || detail.accountPhone || '—')}</Descriptions.Item>
<Descriptions.Item label="分类">{partnerEventCategoryLabel(String(detail.eventName ?? ''), detail.category ? String(detail.category) : null)}</Descriptions.Item>
<Descriptions.Item label="事件">{eventNameLabel(String(detail.eventName ?? ''))}</Descriptions.Item>
<Descriptions.Item label="端">{clientAppLabel(detail.clientApp ? String(detail.clientApp) : null)}</Descriptions.Item>
<Descriptions.Item label="关联">{formatRef(detail.refType ? String(detail.refType) : null, detail.refId ? String(detail.refId) : null)}</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(detail.createdAt ? String(detail.createdAt) : null)}</Descriptions.Item>
<Descriptions.Item label="参数">
<pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
{JSON.stringify(detail.extraJson ?? {}, null, 2)}
</pre>
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item key={k} label={k}>
</Descriptions> </Descriptions>
)} )}
</Drawer> </Drawer>
+23 -6
View File
@@ -23,11 +23,15 @@ import {
type PartnerPermissionKey, type PartnerPermissionKey,
} from '@dukang/shared-types'; } from '@dukang/shared-types';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { omitNullFields } from '../lib/omit-null-fields';
import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region'; import { districtCodeLabel, formatDistrictLabels } from '../lib/china-region';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants'; import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect'; import CityDistrictMultiSelect from '../components/CityDistrictMultiSelect';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import PartnerAssocPanel from '../components/PartnerAssocPanel';
type Row = { type Row = {
@@ -160,7 +164,7 @@ export default function PartnersPage() {
try { try {
const v = await editForm.validateFields(); const v = await editForm.validateFields();
const body = { const body = {
...v, ...omitNullFields(v),
orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100, orderCommissionRate: Number(v.orderCommissionRate ?? 0) / 100,
redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100, redeemCommissionRate: Number(v.redeemCommissionRate ?? 3) / 100,
districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined, districtCodes: editScopeType === CityPartnerScopeType.DISTRICT ? flattenDistrictCodes(v.districtCodes) : undefined,
@@ -184,7 +188,13 @@ export default function PartnersPage() {
render: (codes: string[] | null | undefined, row) => render: (codes: string[] | null | undefined, row) =>
row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes), row.scopeType === CityPartnerScopeType.CITY_WIDE ? '全城' : formatDistrictLabels(codes),
}, },
}, {
title: '公司名',
dataIndex: 'companyName',
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openPartner(row.id)}>{v}</AdminPrimaryLink>
),
},
{ title: '主账号', dataIndex: 'phone', width: 130 }, { title: '主账号', dataIndex: 'phone', width: 130 },
{ {
title: '管辖', title: '管辖',
@@ -211,13 +221,15 @@ export default function PartnersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
{settingsModal} <AdminListHeader
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> title="开城合伙人"
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> settings={settingsButton}
actions={
<Button type="primary" onClick={() => { setCreateOpen(true); createForm.resetFields(); setCreateScopeType(CityPartnerScopeType.CITY_WIDE); }}> <Button type="primary" onClick={() => { setCreateOpen(true); createForm.resetFields(); setCreateScopeType(CityPartnerScopeType.CITY_WIDE); }}>
</Button> </Button>
</Button> }
/>
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="companyName" label="公司"><Input allowClear /></Form.Item> <Form.Item name="companyName" label="公司"><Input allowClear /></Form.Item>
<Form.Item name="contactPhone" label="电话"><Input allowClear /></Form.Item> <Form.Item name="contactPhone" label="电话"><Input allowClear /></Form.Item>
@@ -310,6 +322,11 @@ export default function PartnersPage() {
</> </>
), ),
}, },
{
key: 'assoc',
label: '关联码',
children: <PartnerAssocPanel partnerId={detail.id} />,
},
]} ]}
/> />
)} )}
+11 -3
View File
@@ -24,6 +24,8 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const STATUS_COLOR: Record<RedeemPendingStatus, string> = { const STATUS_COLOR: Record<RedeemPendingStatus, string> = {
@@ -97,7 +99,14 @@ export default function PendingRedeemPage() {
} }
const baseColumns: ColumnsType<RedeemPendingItem> = [ const baseColumns: ColumnsType<RedeemPendingItem> = [
{ title: '待处理单号', dataIndex: 'pendingNo', width: 170 }, {
title: '待处理单号',
dataIndex: 'pendingNo',
width: 170,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '核销码 ID', title: '核销码 ID',
dataIndex: 'redeemToken', dataIndex: 'redeemToken',
@@ -138,8 +147,7 @@ export default function PendingRedeemPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
{settingsModal} <AdminListHeader title="待处理核销(弱网兜底)" settings={settingsButton} />
<Typography.Title level={4}></Typography.Title>
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
@@ -14,6 +14,7 @@ import DetailImageUrlList from '../components/DetailImageUrlList';
import type { ProductDetailTemplateDto } from '../lib/product-detail-templates'; import type { ProductDetailTemplateDto } from '../lib/product-detail-templates';
import { TEMPLATE_MAX_DETAIL_IMAGES } from '../lib/product-detail-templates'; import { TEMPLATE_MAX_DETAIL_IMAGES } from '../lib/product-detail-templates';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = ProductDetailTemplateDto; type Row = ProductDetailTemplateDto;
@@ -140,7 +141,23 @@ export default function ProductDetailTemplatesPage() {
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '编码', dataIndex: 'code', width: 120 }, { title: '编码', dataIndex: 'code', width: 120 },
{ title: '名称', dataIndex: 'name', width: 120 }, {
title: '名称',
dataIndex: 'name',
width: 120,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
const d = await request<Record<string, unknown>>(`/admin/product-detail-templates/${row.id}`);
setDetail(d);
editForm.setFieldsValue(mapToForm(d));
setDrawerOpen(true);
}}
>
{v}
</AdminPrimaryLink>
),
},
{ title: '说明', dataIndex: 'description', width: 200 }, { title: '说明', dataIndex: 'description', width: 200 },
{ title: '香型', dataIndex: 'aromaType', width: 90, render: (v) => (v ? AROMA_TYPE_LABELS[v] || v : '—') }, { title: '香型', dataIndex: 'aromaType', width: 90, render: (v) => (v ? AROMA_TYPE_LABELS[v] || v : '—') },
{ title: '详情图', dataIndex: 'detailImageUrls', width: 80, render: (v: string[] | undefined) => v?.length ?? 0 }, { title: '详情图', dataIndex: 'detailImageUrls', width: 80, render: (v: string[] | undefined) => v?.length ?? 0 },
+16 -6
View File
@@ -15,6 +15,8 @@ import ProductDetailTemplatePicker from '../components/ProductDetailTemplatePick
import ProductSpecsEditor from '../components/ProductSpecsEditor'; import ProductSpecsEditor from '../components/ProductSpecsEditor';
import type { FormInstance } from 'antd/es/form'; import type { FormInstance } from 'antd/es/form';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type ProductDetailContentDto = { type ProductDetailContentDto = {
@@ -391,7 +393,14 @@ export default function ProductsPage() {
const baseColumns: ColumnsType<Row> = useMemo(() => [ const baseColumns: ColumnsType<Row> = useMemo(() => [
{ title: '香型', dataIndex: 'aromaType', width: 80, render: (v) => AROMA_TYPE_LABELS[v] || v }, { title: '香型', dataIndex: 'aromaType', width: 80, render: (v) => AROMA_TYPE_LABELS[v] || v },
{ title: '品名', dataIndex: 'name', width: 200 }, { title: '品名', dataIndex: 'name', width: 200, render: (v, row) => (
<AdminPrimaryLink onClick={async () => {
const d = await request<Record<string, unknown>>(`/admin/products/${row.id}`);
setDetail(d);
editForm.setFieldsValue(mapDetailToForm(d));
setDrawerOpen(true);
}}>{v}</AdminPrimaryLink>
) },
{ {
title: '累计销售', title: '累计销售',
dataIndex: 'soldBottles', dataIndex: 'soldBottles',
@@ -502,11 +511,11 @@ export default function ProductsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="商品管理"
{settingsButton} settings={settingsButton}
<Button type="primary" onClick={() => setCreateOpen(true)}></Button> actions={<Button type="primary" onClick={() => setCreateOpen(true)}></Button>}
</Space> />
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="name" label="名称"> <Form.Item name="name" label="名称">
<Input allowClear placeholder="名称 / SKU / 69 码" style={{ width: 200 }} /> <Input allowClear placeholder="名称 / SKU / 69 码" style={{ width: 200 }} />
@@ -601,6 +610,7 @@ export default function ProductsPage() {
label: '规格与 SKU', label: '规格与 SKU',
children: ( children: (
<ProductSpecsEditor <ProductSpecsEditor
key={String(detail.id)}
productId={String(detail.id)} productId={String(detail.id)}
initialAttrs={(detail.specAttrs as never) ?? []} initialAttrs={(detail.specAttrs as never) ?? []}
initialSkus={(detail.skus as never) ?? []} initialSkus={(detail.skus as never) ?? []}
+37 -36
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { import {
Button, Form, Input, Modal, Select, Space, Table, Tag, Typography, message, Button, Form, Input, Modal, Select, Space, Table, Tag, Tooltip, Typography, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { import {
@@ -15,27 +15,14 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = PromoCodeItem; type Row = PromoCodeItem;
type SceneOption = { value: PromoCodeScene; label: string }; type SceneOption = { value: PromoCodeScene; label: string };
async function downloadQrcode(url: string, filename: string) {
try {
const res = await fetch(url);
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
a.download = filename;
a.click();
URL.revokeObjectURL(objectUrl);
} catch {
window.open(url, '_blank');
}
}
export default function PromoCodesPage() { export default function PromoCodesPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const [filterForm] = Form.useForm(); const [filterForm] = Form.useForm();
@@ -77,7 +64,14 @@ export default function PromoCodesPage() {
}, []); }, []);
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '名称', dataIndex: 'name', width: 160 }, {
title: '名称',
dataIndex: 'name',
width: 160,
render: (v, row) => (
<AdminPrimaryLink onClick={() => navigate(`/promo-codes/${row.id}`)}>{v}</AdminPrimaryLink>
),
},
{ title: '码值', dataIndex: 'code', width: 110 }, { title: '码值', dataIndex: 'code', width: 110 },
{ {
title: '场景', title: '场景',
@@ -95,8 +89,26 @@ export default function PromoCodesPage() {
</Tag> </Tag>
), ),
}, },
{ title: '扫码', dataIndex: 'scanCount', width: 70 }, {
{ title: '订单', dataIndex: 'orderCount', width: 70 }, title: '扫码',
dataIndex: 'scanCount',
width: 70,
render: (v: number, row) => (
<AdminPrimaryLink onClick={() => navigate(`/promo-codes/${row.id}?eventType=SCAN`)}>
{v}
</AdminPrimaryLink>
),
},
{
title: <Tooltip title="仅统计已完成订单"></Tooltip>,
dataIndex: 'orderCount',
width: 70,
render: (v: number, row) => (
<AdminPrimaryLink onClick={() => navigate(`/orders?promoCodeId=${row.id}&status=COMPLETED`)}>
{v}
</AdminPrimaryLink>
),
},
{ {
title: '转化率', title: '转化率',
width: 90, width: 90,
@@ -110,24 +122,13 @@ export default function PromoCodesPage() {
{ title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '创建', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
title: '操作', title: '操作',
width: 220, width: 140,
fixed: 'right', fixed: 'right',
render: (_, row) => ( render: (_, row) => (
<Space size="small" wrap> <Space size="small" wrap>
<Button type="link" size="small" onClick={() => navigate(`/promo-codes/${row.id}`)}> <Button type="link" size="small" onClick={() => navigate(`/promo-codes/${row.id}`)}>
</Button> </Button>
<Button
type="link"
size="small"
disabled={!row.qrcodeUrl}
onClick={() => {
if (!row.qrcodeUrl) return;
void downloadQrcode(row.qrcodeUrl, `${row.code}-wxacode.png`);
}}
>
</Button>
<Button type="link" size="small" onClick={() => navigate(`/promo-codes/${row.id}/users`)}> <Button type="link" size="small" onClick={() => navigate(`/promo-codes/${row.id}/users`)}>
</Button> </Button>
@@ -167,11 +168,11 @@ export default function PromoCodesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}>广</Typography.Title> title="推广码管理"
{settingsButton} settings={settingsButton}
<Button type="primary" onClick={() => setCreateOpen(true)}>广</Button> actions={<Button type="primary" onClick={() => setCreateOpen(true)}>广</Button>}
</div> />
<Form <Form
form={filterForm} form={filterForm}
+63 -14
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Checkbox, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd'; import { Button, Checkbox, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types'; import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
@@ -8,6 +8,8 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -18,17 +20,28 @@ type Row = {
channel?: RedeemChannel; channel?: RedeemChannel;
createdAt: string; createdAt: string;
isTest?: boolean; isTest?: boolean;
user?: { userNo: string; phone: string | null; nickname?: string | null }; user?: {
id?: string;
userNo: string;
phone: string | null;
nickname?: string | null;
hqRemark?: string | null;
};
store?: { name: string; cityName: string }; store?: { name: string; cityName: string };
coupon?: { couponNo: string }; coupon?: { id?: string; couponNo: string };
}; };
function maskPhone(phone: string | null | undefined) { function formatNicknameWithRemark(user?: {
if (!phone || phone.length < 7) return phone ?? '—'; nickname?: string | null;
return `${phone.slice(0, 3)}****${phone.slice(-4)}`; hqRemark?: string | null;
} | null) {
const name = user?.nickname?.trim() || '—';
const remark = user?.hqRemark?.trim();
return remark ? `${name}${remark}` : name;
} }
export default function RedeemRecordsPage() { export default function RedeemRecordsPage() {
const navigate = useNavigate();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const initialRedeemNo = searchParams.get('redeemNo')?.trim() || ''; const initialRedeemNo = searchParams.get('redeemNo')?.trim() || '';
const [form] = Form.useForm(); const [form] = Form.useForm();
@@ -84,7 +97,7 @@ export default function RedeemRecordsPage() {
width: 200, width: 200,
render: (v, row) => ( render: (v, row) => (
<span> <span>
{v} <AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
{row.isTest ? ( {row.isTest ? (
<Tag color="orange" style={{ marginLeft: 6 }}> <Tag color="orange" style={{ marginLeft: 6 }}>
@@ -106,23 +119,60 @@ export default function RedeemRecordsPage() {
); );
}, },
}, },
{ title: '用户编号', dataIndex: ['user', 'userNo'], width: 110 }, { title: '用户编号', dataIndex: ['user', 'userNo'], width: 110, render: (v: string | undefined, row) =>
row.user?.id ? (
<AdminPrimaryLink
onClick={() => navigate('/users', { state: { openUserId: String(row.user!.id) } })}
>
{v || '—'}
</AdminPrimaryLink>
) : (
v || '—'
),
},
{ {
title: '用户昵称', title: '用户昵称',
dataIndex: ['user', 'nickname'], dataIndex: ['user', 'nickname'],
width: 100, width: 160,
render: (v: string | null | undefined) => v || '—', render: (_: string | null | undefined, row) =>
row.user?.id ? (
<AdminPrimaryLink
onClick={() => navigate('/users', { state: { openUserId: String(row.user!.id) } })}
>
{formatNicknameWithRemark(row.user)}
</AdminPrimaryLink>
) : (
formatNicknameWithRemark(row.user)
),
}, },
{ {
title: '用户手机', title: '用户手机',
dataIndex: ['user', 'phone'], dataIndex: ['user', 'phone'],
width: 120, width: 120,
render: (v: string | null | undefined) => maskPhone(v), render: (v: string | null | undefined) => v || '—',
}, },
{ title: '门店', dataIndex: ['store', 'name'] }, { title: '门店', dataIndex: ['store', 'name'] },
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` }, { title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` }, { title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
{ title: '券号', dataIndex: ['coupon', 'couponNo'], width: 160 }, {
title: '券号',
dataIndex: ['coupon', 'couponNo'],
width: 160,
render: (v: string | undefined, row) =>
v ? (
<AdminPrimaryLink
onClick={() =>
navigate(`/benefit/coupons?couponNo=${encodeURIComponent(v)}`, {
state: row.coupon?.id ? { openCouponId: String(row.coupon.id) } : undefined,
})
}
>
{v}
</AdminPrimaryLink>
) : (
'—'
),
},
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
title: '操作', title: '操作',
@@ -140,8 +190,7 @@ export default function RedeemRecordsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader title="核销记录" settings={settingsButton} />
{settingsButton}
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
+6 -9
View File
@@ -13,6 +13,7 @@ import {
} from '../lib/constants'; } from '../lib/constants';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
type Row = { type Row = {
@@ -121,15 +122,11 @@ export default function ResourcesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}> title="OSS 资源库"
OSS settings={settingsButton}
</Typography.Title> actions={<Button type="primary" onClick={() => setCreateOpen(true)}></Button>}
{settingsButton} />
<Button type="primary" onClick={() => setCreateOpen(true)}>
</Button>
</Space>
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
+17 -10
View File
@@ -7,6 +7,8 @@ import { request, type Paginated } from '../lib/api';
import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, STORE_STATUS_LABELS, fmtTime } from '../lib/constants'; import { ACCOUNT_STATUS_LABELS, ADMIN_OPTIONS_PAGE_SIZE, STORE_STATUS_LABELS, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type StoreBrief = { id: string; name: string; status: string; cityName?: string }; type StoreBrief = { id: string; name: string; status: string; cityName?: string };
@@ -83,7 +85,14 @@ export default function StoreAccountsPage() {
width: 120, width: 120,
render: (v, row) => ( render: (v, row) => (
<Space size={4}> <Space size={4}>
<span>{v}</span> <AdminPrimaryLink
onClick={async () => {
setDetail(await request(`/admin/store-accounts/${row.id}`));
setDrawerOpen(true);
}}
>
{v}
</AdminPrimaryLink>
{row.isTest ? <Tag color="orange"></Tag> : null} {row.isTest ? <Tag color="orange"></Tag> : null}
</Space> </Space>
), ),
@@ -145,14 +154,11 @@ export default function StoreAccountsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Space direction="vertical" size={0}> title="门店账户"
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> settings={settingsButton}
{settingsButton} description="主账号可绑定多家门店;收款信息挂在主账号;「新建账户」用于补录无主账号门店"
<Typography.Text type="secondary"> actions={
</Typography.Text>
</Space>
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -162,7 +168,8 @@ export default function StoreAccountsPage() {
> >
</Button> </Button>
</Space> }
/>
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
+133 -84
View File
@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams, useNavigate } from 'react-router-dom';
import { import {
Button, Button,
Card, Card,
@@ -14,9 +14,11 @@ import {
Statistic, Statistic,
Table, Table,
Tag, Tag,
Tooltip,
Typography, Typography,
message, message,
} from 'antd'; } from 'antd';
import { FinancePayProofModal, PaymentProofGallery } from '../components/FinancePayProof';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import type { Dayjs } from 'dayjs'; import type { Dayjs } from 'dayjs';
import { import {
@@ -31,6 +33,8 @@ import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { downloadExcelCsv } from '../lib/exportExcel'; import { downloadExcelCsv } from '../lib/exportExcel';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -73,6 +77,7 @@ const KIND_COLORS: Record<StoreSettlementKind, string> = {
}; };
export default function StoreBillsPage() { export default function StoreBillsPage() {
const navigate = useNavigate();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : ''; const initialKind = searchParams.get('kind') === 'WITHDRAW' ? 'WITHDRAW' : '';
const initialStoreId = searchParams.get('storeId') || ''; const initialStoreId = searchParams.get('storeId') || '';
@@ -109,6 +114,13 @@ export default function StoreBillsPage() {
pendingCount: number; pendingCount: number;
overdueCount: number; overdueCount: number;
} | null>(null); } | null>(null);
const [payModal, setPayModal] = useState<{
ids: string[];
amountHint?: number;
} | null>(null);
const [paySubmitting, setPaySubmitting] = useState(false);
const [withdrawApproveId, setWithdrawApproveId] = useState<string | null>(null);
const [withdrawSubmitting, setWithdrawSubmitting] = useState(false);
useEffect(() => { useEffect(() => {
form.setFieldsValue({ form.setFieldsValue({
@@ -130,77 +142,11 @@ export default function StoreBillsPage() {
}, []); }, []);
function confirmPay(ids: string[], amountHint?: number) { function confirmPay(ids: string[], amountHint?: number) {
let paymentRef = ''; setPayModal({ ids, amountHint });
Modal.confirm({
title: '确认打款?',
content: (
<div>
<div>
{ids.length} T+1
{amountHint != null ? `,合计约 ¥${amountHint.toFixed(2)}` : ''}
</div>
<Input
placeholder="打款凭证号(可选)"
style={{ marginTop: 8 }}
onChange={(e) => {
paymentRef = e.target.value;
}}
/>
</div>
),
okText: '确认打款',
cancelText: '取消',
onOk: async () => {
const body = JSON.stringify({ paymentRef: paymentRef.trim() || undefined });
if (ids.length === 1) {
await request(`/admin/store-bills/${ids[0]}/confirm`, { method: 'POST', body });
} else {
setBatchLoading(true);
try {
await request('/admin/store-bills/batch-confirm', {
method: 'POST',
body: JSON.stringify({ ids }),
});
} finally {
setBatchLoading(false);
}
}
message.success('已确认打款');
setSelectedKeys([]);
reload();
},
});
} }
function approveWithdraw(id: string) { function approveWithdraw(id: string) {
let paymentRef = ''; setWithdrawApproveId(id);
Modal.confirm({
title: '审核通过并标记已结算?',
content: (
<Input
placeholder="打款凭证号(可选)"
onChange={(e) => {
paymentRef = e.target.value;
}}
/>
),
okText: '通过并结算',
cancelText: '取消',
onOk: async () => {
await request(`/admin/store-withdrawals/${id}/approve`, {
method: 'POST',
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
});
message.success('已通过并标记已结算');
setDrawerOpen(false);
reload();
void request<{ pendingCount: number; overdueCount: number }>(
'/admin/store-withdrawals/overdue-summary',
)
.then(setOverdueSummary)
.catch(() => {});
},
});
} }
function rejectWithdraw(id: string) { function rejectWithdraw(id: string) {
@@ -286,13 +232,17 @@ export default function StoreBillsPage() {
width: 180, width: 180,
render: (v, row) => ( render: (v, row) => (
<Space> <Space>
<Space> <AdminPrimaryLink onClick={() => void openDetail(row)}>{v}</AdminPrimaryLink>
{row.overdue ? <Tag color="magenta"></Tag> : null} {row.overdue ? <Tag color="magenta"></Tag> : null}
</Space> </Space>
), ),
}, },
{ {
{ title: (
<Tooltip title="T+1 为出账日(昨日 00:00–今日 00:00 窗口中的今天,不是该账单里最后一笔核销时间);手动提现为申请时间">
</Tooltip>
),
dataIndex: 'date', dataIndex: 'date',
width: 160, width: 160,
render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)), render: (v, row) => (row.kind === 'T1_BILL' ? String(v || '').slice(0, 10) : fmtTime(v)),
@@ -380,21 +330,24 @@ export default function StoreBillsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
return ( <AdminListHeader
<div> title="门店账单"
{settingsModal} settings={settingsButton}
<Space direction="vertical" size={0} style={{ marginBottom: 16 }}> description={
<Typography.Title level={4} style={{ margin: 0 }}> <>
T+1 沿 T+1 沿
= T+1 = = T+1 =
<Typography.Text type="secondary"> T+1 00:00 00:00
{overdueSummary && overdueSummary.overdueCount > 0 ? ( {overdueSummary && overdueSummary.overdueCount > 0 ? (
<div>
<Typography.Text type="danger"> <Typography.Text type="danger">
{overdueSummary.overdueCount} {overdueSummary.pendingCount} {overdueSummary.overdueCount} {overdueSummary.pendingCount}
</Typography.Text> </Typography.Text>
</div>
) : null} ) : null}
{overdueSummary.overdueCount} {overdueSummary.pendingCount} </>
}
/>
{summary && ( {summary && (
<Card size="small" style={{ marginBottom: 16 }}> <Card size="small" style={{ marginBottom: 16 }}>
@@ -465,7 +418,7 @@ export default function StoreBillsPage() {
}))} }))}
/> />
</Form.Item> </Form.Item>
}))} <Form.Item name="range" label="出账日">
<DatePicker.RangePicker /> <DatePicker.RangePicker />
</Form.Item> </Form.Item>
<Form.Item> <Form.Item>
@@ -539,7 +492,7 @@ export default function StoreBillsPage() {
<> <>
<Descriptions column={1} size="small" bordered> <Descriptions column={1} size="small" bordered>
<Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item> <Descriptions.Item label="账单号">{String(detail.billNo)}</Descriptions.Item>
<> <Descriptions.Item label="出账日">
{String(detail.billDate || '').slice(0, 10)} {String(detail.billDate || '').slice(0, 10)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="应付"> <Descriptions.Item label="应付">
@@ -554,6 +507,9 @@ export default function StoreBillsPage() {
<Descriptions.Item label="打款凭证"> <Descriptions.Item label="打款凭证">
{detail.paymentRef ? String(detail.paymentRef) : '—'} {detail.paymentRef ? String(detail.paymentRef) : '—'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="凭证照片">
<PaymentProofGallery urls={detail.paymentProofUrls} />
</Descriptions.Item>
</Descriptions> </Descriptions>
{(detail.storeAccount as { {(detail.storeAccount as {
bankAccountName?: string; bankAccountName?: string;
@@ -588,8 +544,22 @@ export default function StoreBillsPage() {
columns={[ columns={[
{ {
title: '核销单号', title: '核销单号',
columns={[ render: (_, r) => {
{ const redeemNo = String(
(r.redeemRecord as { redeemNo?: string } | undefined)?.redeemNo || '',
);
return redeemNo ? (
<AdminPrimaryLink
onClick={() =>
navigate(`/redeem-records?redeemNo=${encodeURIComponent(redeemNo)}`)
}
>
{redeemNo}
</AdminPrimaryLink>
) : (
'—'
);
},
}, },
{ {
title: '金额', title: '金额',
@@ -624,6 +594,9 @@ export default function StoreBillsPage() {
<Descriptions.Item label="打款凭证"> <Descriptions.Item label="打款凭证">
{detail.paymentRef ? String(detail.paymentRef) : '—'} {detail.paymentRef ? String(detail.paymentRef) : '—'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="凭证照片">
<PaymentProofGallery urls={detail.paymentProofUrls} />
</Descriptions.Item>
</Descriptions> </Descriptions>
{storeAccount ? ( {storeAccount ? (
<> <>
@@ -658,7 +631,18 @@ export default function StoreBillsPage() {
const payout = r.storePayout as const payout = r.storePayout as
| { redeemRecord?: { redeemNo?: string }; payoutAmount?: number } | { redeemRecord?: { redeemNo?: string }; payoutAmount?: number }
| undefined; | undefined;
const payout = r.storePayout as const redeemNo = payout?.redeemRecord?.redeemNo || '';
return redeemNo ? (
<AdminPrimaryLink
onClick={() =>
navigate(`/redeem-records?redeemNo=${encodeURIComponent(redeemNo)}`)
}
>
{redeemNo}
</AdminPrimaryLink>
) : (
'—'
);
}, },
}, },
{ {
@@ -683,6 +667,71 @@ export default function StoreBillsPage() {
</> </>
)} )}
</Drawer> </Drawer>
<FinancePayProofModal
open={!!payModal}
title="确认打款?"
hint={`将确认 ${payModal?.ids.length ?? 0} 笔 T+1 门店对账单${
payModal?.amountHint != null ? `,合计约 ¥${payModal.amountHint.toFixed(2)}` : ''
}。此操作不可撤销。`}
okText="确认打款"
confirmLoading={paySubmitting}
onCancel={() => setPayModal(null)}
onOk={async (payload) => {
if (!payModal) return;
const { ids } = payModal;
setPaySubmitting(true);
if (ids.length > 1) setBatchLoading(true);
try {
const body = JSON.stringify({
...payload,
...(ids.length > 1 ? { ids } : {}),
});
if (ids.length === 1) {
await request(`/admin/store-bills/${ids[0]}/confirm`, { method: 'POST', body });
} else {
await request('/admin/store-bills/batch-confirm', { method: 'POST', body });
}
message.success('已确认打款');
setPayModal(null);
setSelectedKeys([]);
reload();
} finally {
setPaySubmitting(false);
setBatchLoading(false);
}
}}
/>
<FinancePayProofModal
open={!!withdrawApproveId}
title="审核通过并标记已结算?"
hint="通过后将标记该提现为已结算,此操作不可撤销。"
okText="通过并结算"
confirmLoading={withdrawSubmitting}
onCancel={() => setWithdrawApproveId(null)}
onOk={async (payload) => {
if (!withdrawApproveId) return;
setWithdrawSubmitting(true);
try {
await request(`/admin/store-withdrawals/${withdrawApproveId}/approve`, {
method: 'POST',
body: JSON.stringify(payload),
});
message.success('已通过并标记已结算');
setWithdrawApproveId(null);
setDrawerOpen(false);
reload();
void request<{ pendingCount: number; overdueCount: number }>(
'/admin/store-withdrawals/overdue-summary',
)
.then(setOverdueSummary)
.catch(() => {});
} finally {
setWithdrawSubmitting(false);
}
}}
/>
</div> </div>
); );
} }
@@ -5,6 +5,8 @@ import {
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { request, type HqProfile } from '../lib/api'; import { request, type HqProfile } from '../lib/api';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type CategoryNode = { type CategoryNode = {
@@ -130,7 +132,7 @@ export default function StoreCategoriesPage() {
render: (name, row) => ( render: (name, row) => (
<span style={{ paddingLeft: row.level === 2 ? 24 : 0 }}> <span style={{ paddingLeft: row.level === 2 ? 24 : 0 }}>
{row.level === 2 ? `${row.parentName || ''} / ` : ''} {row.level === 2 ? `${row.parentName || ''} / ` : ''}
{name} <AdminPrimaryLink onClick={() => openEdit(row)}>{name}</AdminPrimaryLink>
</span> </span>
), ),
}, },
@@ -157,9 +159,20 @@ export default function StoreCategoriesPage() {
<Popconfirm <Popconfirm
title={row.level === 1 ? '删除一级分类?若有门店占用将改为停用' : '删除该分类?若有门店占用将改为停用'} title={row.level === 1 ? '删除一级分类?若有门店占用将改为停用' : '删除该分类?若有门店占用将改为停用'}
onConfirm={async () => { onConfirm={async () => {
await request(`/admin/store-categories/${row.id}`, { method: 'DELETE' }); try {
message.success('已处理'); const res = await request<{ deleted?: boolean; softDisabled?: boolean }>(
`/admin/store-categories/${row.id}`,
{ method: 'DELETE' },
);
if (res.softDisabled) {
message.success('该分类已有门店占用,已改为停用');
} else {
message.success('已删除');
}
void reload(); void reload();
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败');
}
}} }}
> >
<Button type="link" size="small" danger></Button> <Button type="link" size="small" danger></Button>
@@ -178,13 +191,12 @@ export default function StoreCategoriesPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Space direction="vertical" size={0}> title="门店分类"
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> settings={settingsButton}
{settingsButton} description="两级分类:一级(餐饮/住宿/娱乐)→ 二级业态,供合伙人开店选择"
<Typography.Text type="secondary">/宿/ </Typography.Text> actions={
</Space> <>
<Space>
{canDelete ? ( {canDelete ? (
<Button <Button
onClick={async () => { onClick={async () => {
@@ -197,8 +209,9 @@ export default function StoreCategoriesPage() {
</Button> </Button>
) : null} ) : null}
<Button type="primary" onClick={() => openCreate()}></Button> <Button type="primary" onClick={() => openCreate()}></Button>
</Space> </>
</Space> }
/>
<Table <Table
rowKey="id" rowKey="id"
+32 -15
View File
@@ -4,15 +4,16 @@ import type { ColumnsType } from 'antd/es/table';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
import { import {
STORE_LOG_CATEGORY_OPTIONS, STORE_LOG_CATEGORY_OPTIONS,
STORE_LOG_CATEGORY_LABELS,
resolveStoreLogCategory,
type StoreLogCategory, type StoreLogCategory,
} from '../lib/store-log'; } from '../lib/store-log';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { AdminCellLine } from '../components/AdminCellLine'; import { AdminCellLine } from '../components/AdminCellLine';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { clientAppLabel, eventNameLabel, formatRef, storeEventCategoryLabel } from '../lib/display-labels';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -100,17 +101,33 @@ export default function StoreLogsPage() {
{ {
title: '分类', dataIndex: 'category', width: 100, title: '分类', dataIndex: 'category', width: 100,
render: (v: StoreLogCategory | null, r) => ( render: (v: StoreLogCategory | null, r) => (
<Tag>{STORE_LOG_CATEGORY_LABELS[v ?? ''] || resolveStoreLogCategory(r.eventName) || '其他'}</Tag> <Tag>{storeEventCategoryLabel(r.eventName, v)}</Tag>
),
},
{
title: '事件',
dataIndex: 'eventName',
width: 160,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
const parsed = parseCompositeId(row.id);
if (!parsed) return;
setDetail(await request(`/admin/logs/stores/${parsed.source}/${parsed.rawId}`));
setDrawerOpen(true);
}}
>
{eventNameLabel(v)}
</AdminPrimaryLink>
), ),
}, },
{ title: '事件', dataIndex: 'eventName', width: 160 },
{ {
title: '来源', dataIndex: 'source', width: 100, title: '来源', dataIndex: 'source', width: 100,
render: (v: Row['source']) => SOURCE_LABELS[v] || v, render: (v: Row['source']) => SOURCE_LABELS[v] || v,
}, },
{ {
title: '关联', width: 120, title: '关联', width: 120,
render: (_, r) => (r.refType && r.refId ? `${r.refType}#${r.refId}` : '—'), render: (_, r) => formatRef(r.refType, r.refId),
}, },
{ {
title: '摘要', title: '摘要',
@@ -134,11 +151,11 @@ export default function StoreLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader
{settingsButton} title="商户日志"
<Typography.Paragraph type="secondary" style={{ marginTop: -8 }}> settings={settingsButton}
/ description="门店登录、微信授权、核销、打款与营业状态等操作记录;历史核销/打款数据来自业务表归档。"
</Typography.Paragraph> />
<Segmented <Segmented
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
options={STORE_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))} options={STORE_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))}
@@ -166,7 +183,7 @@ export default function StoreLogsPage() {
<Form.Item name="storeName" label="门店名称"><Input allowClear style={{ width: 140 }} /></Form.Item> <Form.Item name="storeName" label="门店名称"><Input allowClear style={{ width: 140 }} /></Form.Item>
<Form.Item name="storeAccountId" label="账号ID"><Input allowClear style={{ width: 120 }} /></Form.Item> <Form.Item name="storeAccountId" label="账号ID"><Input allowClear style={{ width: 120 }} /></Form.Item>
<Form.Item name="phone" label="手机号"><Input allowClear style={{ width: 130 }} /></Form.Item> <Form.Item name="phone" label="手机号"><Input allowClear style={{ width: 130 }} /></Form.Item>
<Form.Item name="eventName" label="事件"><Input allowClear style={{ width: 160 }} placeholder="store_login_success" /></Form.Item> <Form.Item name="eventName" label="事件编码"><Input allowClear style={{ width: 160 }} placeholder="事件编码" /></Form.Item>
<Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item> <Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item>
<Form.Item><Button onClick={() => { form.resetFields(); setFilters({}); setCategory(''); setSearchParams({}); setPage(1); }}></Button></Form.Item> <Form.Item><Button onClick={() => { form.resetFields(); setFilters({}); setCategory(''); setSearchParams({}); setPage(1); }}></Button></Form.Item>
</Form> </Form>
@@ -180,12 +197,12 @@ export default function StoreLogsPage() {
<Descriptions.Item label="账号">{String(detail.accountName || detail.storeAccountId || '系统/HQ')}</Descriptions.Item> <Descriptions.Item label="账号">{String(detail.accountName || detail.storeAccountId || '系统/HQ')}</Descriptions.Item>
<Descriptions.Item label="手机">{String(detail.accountPhone || '—')}</Descriptions.Item> <Descriptions.Item label="手机">{String(detail.accountPhone || '—')}</Descriptions.Item>
<Descriptions.Item label="分类"> <Descriptions.Item label="分类">
{(STORE_LOG_CATEGORY_LABELS as Record<string, string>)[String(detail.category ?? '')] || String(detail.category || '—')} {storeEventCategoryLabel(String(detail.eventName ?? ''), detail.category ? String(detail.category) : null)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="事件">{String(detail.eventName)}</Descriptions.Item> <Descriptions.Item label="事件">{eventNameLabel(String(detail.eventName ?? ''))}</Descriptions.Item>
<Descriptions.Item label="来源">{SOURCE_LABELS[String(detail.source) as Row['source']] || String(detail.source || '—')}</Descriptions.Item> <Descriptions.Item label="来源">{SOURCE_LABELS[String(detail.source) as Row['source']] || String(detail.source || '—')}</Descriptions.Item>
<Descriptions.Item label="客户端">{String(detail.clientApp || '—')}</Descriptions.Item> <Descriptions.Item label="端">{clientAppLabel(detail.clientApp ? String(detail.clientApp) : null)}</Descriptions.Item>
<Descriptions.Item label="关联">{detail.refType ? `${String(detail.refType)}#${String(detail.refId)}` : '—'}</Descriptions.Item> <Descriptions.Item label="关联">{formatRef(detail.refType ? String(detail.refType) : null, detail.refId ? String(detail.refId) : null)}</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item> <Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
<Descriptions.Item label="参数"> <Descriptions.Item label="参数">
<pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}> <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
+23 -6
View File
@@ -8,6 +8,8 @@ import { ADMIN_OPTIONS_PAGE_SIZE, MEDIA_TYPE_LABELS, fmtTime } from '../lib/cons
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -43,7 +45,22 @@ export default function StoreMediaPage() {
} }
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '门店', dataIndex: ['store', 'name'], width: 140 }, {
title: '门店',
dataIndex: ['store', 'name'],
width: 140,
render: (v, row) => (
<AdminPrimaryLink
onClick={() => {
setEditing(row);
editForm.setFieldsValue(row);
setEditOpen(true);
}}
>
{v}
</AdminPrimaryLink>
),
},
{ title: '类型', dataIndex: 'mediaType', width: 80, render: (t) => <Tag>{MEDIA_TYPE_LABELS[t] || t}</Tag> }, { title: '类型', dataIndex: 'mediaType', width: 80, render: (t) => <Tag>{MEDIA_TYPE_LABELS[t] || t}</Tag> },
{ {
title: '预览', dataIndex: 'url', width: 100, title: '预览', dataIndex: 'url', width: 100,
@@ -80,11 +97,11 @@ export default function StoreMediaPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="门店资源"
{settingsButton} settings={settingsButton}
<Button type="primary" onClick={() => { void loadStores(); setCreateOpen(true); }}></Button> actions={<Button type="primary" onClick={() => { void loadStores(); setCreateOpen(true); }}></Button>}
</Space> />
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item> <Form.Item name="storeId" label="门店ID"><Input allowClear /></Form.Item>
<Form.Item name="mediaType" label="类型"> <Form.Item name="mediaType" label="类型">
@@ -33,6 +33,8 @@ import { notifyPackageAuditChanged } from '../lib/admin-events';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import StorePackageAuditPanel from '../components/StorePackageAuditPanel'; import StorePackageAuditPanel from '../components/StorePackageAuditPanel';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const HQ_PACKAGE_STATUS_LABELS: Record<StorePackageChangeStatus, string> = { const HQ_PACKAGE_STATUS_LABELS: Record<StorePackageChangeStatus, string> = {
PENDING: '待审核', PENDING: '待审核',
@@ -199,7 +201,15 @@ function InfoChangeAuditPanel({
} }
const columns: ColumnsType<StoreInfoChangeRequestDto> = [ const columns: ColumnsType<StoreInfoChangeRequestDto> = [
{ title: '门店', dataIndex: 'storeName', render: (_, row) => row.storeName || row.storeId }, {
title: '门店',
dataIndex: 'storeName',
render: (_, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>
{row.storeName || row.storeId}
</AdminPrimaryLink>
),
},
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
@@ -471,7 +481,15 @@ export default function StorePackageAuditsPage() {
} }
const baseColumns: ColumnsType<StorePackageChangeRequestDto> = [ const baseColumns: ColumnsType<StorePackageChangeRequestDto> = [
{ title: '门店', dataIndex: 'storeName', render: (_, row) => row.storeName || row.storeId }, {
title: '门店',
dataIndex: 'storeName',
render: (_, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>
{row.storeName || row.storeId}
</AdminPrimaryLink>
),
},
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
@@ -528,8 +546,7 @@ export default function StorePackageAuditsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader title="审核通知" settings={settingsButton} />
{settingsButton}
<Tabs <Tabs
activeKey={activeTab} activeKey={activeTab}
onChange={setActiveTab} onChange={setActiveTab}
@@ -6,12 +6,14 @@ import { fmtTime, ADMIN_OPTIONS_PAGE_SIZE } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
type Row = { type Row = {
id: string; id: string;
serviceScore: number; serviceScore: number;
envScore: number; envScore: number;
comment?: string | null;
createdAt: string; createdAt: string;
redeemNo: string; redeemNo: string;
redeemAmount: number; redeemAmount: number;
@@ -61,6 +63,12 @@ export default function StoreRatingsPage() {
{ title: '核销额', dataIndex: 'redeemAmount', width: 90, render: (v) => `¥${v}` }, { title: '核销额', dataIndex: 'redeemAmount', width: 90, render: (v) => `¥${v}` },
{ title: '服务分', dataIndex: 'serviceScore', width: 80 }, { title: '服务分', dataIndex: 'serviceScore', width: 80 },
{ title: '环境分', dataIndex: 'envScore', width: 80 }, { title: '环境分', dataIndex: 'envScore', width: 80 },
{
title: '评语',
dataIndex: 'comment',
ellipsis: true,
render: (v: string | null) => v || '—',
},
{ title: '评价时间', dataIndex: 'createdAt', width: 170, render: fmtTime }, { title: '评价时间', dataIndex: 'createdAt', width: 170, render: fmtTime },
]; ];
@@ -69,10 +77,7 @@ export default function StoreRatingsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4} style={{ marginTop: 0 }}> <AdminListHeader title="门店评价" settings={settingsButton} />
</Typography.Title>
{settingsButton}
<Form <Form
form={form} form={form}
layout="inline" layout="inline"
@@ -21,6 +21,9 @@ import { request, type Paginated } from '../lib/api';
import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants'; import { ADMIN_OPTIONS_PAGE_SIZE, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import { FinancePayProofModal, PaymentProofGallery } from '../components/FinancePayProof';
type Row = { type Row = {
@@ -68,6 +71,8 @@ export default function StoreWithdrawalsPage() {
pendingCount: number; pendingCount: number;
overdueCount: number; overdueCount: number;
} | null>(null); } | null>(null);
const [approveId, setApproveId] = useState<string | null>(null);
const [approveSubmitting, setApproveSubmitting] = useState(false);
useEffect(() => { useEffect(() => {
void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`) void request<Paginated<StoreOption>>(`/admin/stores?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
@@ -87,34 +92,7 @@ export default function StoreWithdrawalsPage() {
} }
function approve(id: string) { function approve(id: string) {
let paymentRef = ''; setApproveId(id);
Modal.confirm({
title: '审核通过并标记已结算?',
content: (
<Input
placeholder="打款凭证号(可选)"
onChange={(e) => {
paymentRef = e.target.value;
}}
/>
),
okText: '通过并结算',
cancelText: '取消',
onOk: async () => {
await request(`/admin/store-withdrawals/${id}/approve`, {
method: 'POST',
body: JSON.stringify({ paymentRef: paymentRef.trim() || undefined }),
});
message.success('已通过并标记已结算');
setDrawerOpen(false);
reload();
void request<{ pendingCount: number; overdueCount: number }>(
'/admin/store-withdrawals/overdue-summary',
)
.then(setOverdueSummary)
.catch(() => {});
},
});
} }
function reject(id: string) { function reject(id: string) {
@@ -156,7 +134,7 @@ export default function StoreWithdrawalsPage() {
width: 180, width: 180,
render: (v, row) => ( render: (v, row) => (
<Space> <Space>
<Typography.Link onClick={() => void openDetail(row.id)}>{v}</Typography.Link> <AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
{row.overdue ? <Tag color="magenta"></Tag> : null} {row.overdue ? <Tag color="magenta"></Tag> : null}
</Space> </Space>
), ),
@@ -236,10 +214,7 @@ export default function StoreWithdrawalsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4} style={{ marginTop: 0 }}> <AdminListHeader title="门店提现审" settings={settingsButton} />
</Typography.Title>
{settingsButton}
{overdueSummary ? ( {overdueSummary ? (
<Typography.Paragraph type="secondary"> <Typography.Paragraph type="secondary">
{overdueSummary.pendingCount} {overdueSummary.pendingCount}
@@ -357,6 +332,9 @@ export default function StoreWithdrawalsPage() {
{detail.paymentRef ? ( {detail.paymentRef ? (
<Descriptions.Item label="打款凭证">{String(detail.paymentRef)}</Descriptions.Item> <Descriptions.Item label="打款凭证">{String(detail.paymentRef)}</Descriptions.Item>
) : null} ) : null}
<Descriptions.Item label="凭证照片">
<PaymentProofGallery urls={detail.paymentProofUrls} />
</Descriptions.Item>
<Descriptions.Item label="收款户名"> <Descriptions.Item label="收款户名">
{storeAccount?.bankAccountName || '—'} {storeAccount?.bankAccountName || '—'}
</Descriptions.Item> </Descriptions.Item>
@@ -395,6 +373,36 @@ export default function StoreWithdrawalsPage() {
</> </>
) : null} ) : null}
</Drawer> </Drawer>
<FinancePayProofModal
open={!!approveId}
title="审核通过并标记已结算?"
hint="通过后将标记该提现为已结算,此操作不可撤销。"
okText="通过并结算"
confirmLoading={approveSubmitting}
onCancel={() => setApproveId(null)}
onOk={async (payload) => {
if (!approveId) return;
setApproveSubmitting(true);
try {
await request(`/admin/store-withdrawals/${approveId}/approve`, {
method: 'POST',
body: JSON.stringify(payload),
});
message.success('已通过并标记已结算');
setApproveId(null);
setDrawerOpen(false);
reload();
void request<{ pendingCount: number; overdueCount: number }>(
'/admin/store-withdrawals/overdue-summary',
)
.then(setOverdueSummary)
.catch(() => {});
} finally {
setApproveSubmitting(false);
}
}}
/>
</div> </div>
); );
} }
+10 -10
View File
@@ -40,6 +40,8 @@ import {
} from '../lib/storeCreate'; } from '../lib/storeCreate';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import { resolveRegionBinding } from '../lib/china-region'; import { resolveRegionBinding } from '../lib/china-region';
import ChinaRegionCascader from '../components/ChinaRegionCascader'; import ChinaRegionCascader from '../components/ChinaRegionCascader';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
@@ -739,7 +741,7 @@ export default function StoresPage() {
const name = v || '—'; const name = v || '—';
return ( return (
<Space size={4} wrap={false}> <Space size={4} wrap={false}>
<span>{name}</span> <AdminPrimaryLink onClick={() => void openStoreDetail(row)}>{name === '—' ? '' : name}</AdminPrimaryLink>
{row.isTest ? <Tag color="orange"></Tag> : null} {row.isTest ? <Tag color="orange"></Tag> : null}
</Space> </Space>
); );
@@ -872,16 +874,14 @@ export default function StoresPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Space direction="vertical" size={0}> title="门店"
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> settings={settingsButton}
<Typography.Text type="secondary"> {data?.total ?? 0} </Typography.Text> description={`${data?.total ?? 0} 家门店(含合伙人录入)`}
</Space> actions={
<Space>
{settingsButton}
<Button type="primary" onClick={openCreateModal}></Button> <Button type="primary" onClick={openCreateModal}></Button>
</Space> }
</Space> />
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="name" label="名称"><Input allowClear /></Form.Item> <Form.Item name="name" label="名称"><Input allowClear /></Form.Item>
<Form.Item name="phone" label="电话"><Input allowClear /></Form.Item> <Form.Item name="phone" label="电话"><Input allowClear /></Form.Item>
+17 -16
View File
@@ -47,6 +47,8 @@ import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const DISPATCH_WECOM_STORAGE_KEY = 'support_ticket_dispatch_wecom'; const DISPATCH_WECOM_STORAGE_KEY = 'support_ticket_dispatch_wecom';
@@ -505,7 +507,13 @@ export default function SupportTicketsPage() {
</Space> </Space>
), ),
}, },
{ title: '标题', dataIndex: 'title' }, {
title: '标题',
dataIndex: 'title',
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(String(row.id))}>{v}</AdminPrimaryLink>
),
},
{ title: '创建人', dataIndex: 'creatorName', width: 100 }, { title: '创建人', dataIndex: 'creatorName', width: 100 },
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
@@ -553,19 +561,11 @@ export default function SupportTicketsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div <AdminListHeader
style={{ title="技术支持"
display: 'flex', settings={settingsButton}
justifyContent: 'space-between', actions={
alignItems: 'center', <>
marginBottom: 16,
}}
>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
{settingsButton}
<Space>
{isSuperAdmin ? ( {isSuperAdmin ? (
<> <>
<Button <Button
@@ -595,8 +595,9 @@ export default function SupportTicketsPage() {
<Button type="primary" onClick={() => setCreateOpen(true)}> <Button type="primary" onClick={() => setCreateOpen(true)}>
</Button> </Button>
</Space> </>
</div> }
/>
<Form <Form
layout="inline" layout="inline"
+19 -5
View File
@@ -21,6 +21,8 @@ import type { ColumnsType } from 'antd/es/table';
import { request, type Paginated } from '../lib/api'; import { request, type Paginated } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
const MOCK_KEYS = ['MOCK_SMS', 'MOCK_WECHAT', 'MOCK_PAY'] as const; const MOCK_KEYS = ['MOCK_SMS', 'MOCK_WECHAT', 'MOCK_PAY'] as const;
@@ -254,7 +256,22 @@ export default function TestWhitelistPage() {
} }
const phoneColumns: ColumnsType<PhoneRow> = [ const phoneColumns: ColumnsType<PhoneRow> = [
{ title: '手机号', dataIndex: 'phone', width: 140 }, {
title: '手机号',
dataIndex: 'phone',
width: 140,
render: (v, row) => (
<AdminPrimaryLink
onClick={() => {
setEditRow(row);
editForm.setFieldsValue({ note: row.note ?? '' });
setEditOpen(true);
}}
>
{v}
</AdminPrimaryLink>
),
},
{ {
title: '备注', title: '备注',
dataIndex: 'note', dataIndex: 'note',
@@ -394,10 +411,7 @@ export default function TestWhitelistPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4} style={{ marginTop: 0 }}> <AdminListHeader title="白名单管理" settings={settingsButton} />
</Typography.Title>
{settingsButton}
<Card size="small" loading={mockLoading} style={{ marginBottom: 16 }}> <Card size="small" loading={mockLoading} style={{ marginBottom: 16 }}>
<Typography.Text type="secondary" style={{ display: 'block', marginBottom: 12 }}> <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
+45 -21
View File
@@ -3,8 +3,17 @@ import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typograp
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import {
THIRD_PARTY_PROVIDER_LABELS,
THIRD_PARTY_SCENE_LABELS,
THIRD_PARTY_STATUS_LABELS,
formatRef,
zhLabel,
} from '../lib/display-labels';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -24,14 +33,14 @@ type Row = {
}; };
const PROVIDER_OPTIONS = [ const PROVIDER_OPTIONS = [
{ value: 'WECHAT_AUTH', label: 'WECHAT_AUTH' }, { value: 'WECHAT_AUTH', label: '微信授权' },
{ value: 'WECHAT_PAY', label: 'WECHAT_PAY' }, { value: 'WECHAT_PAY', label: '微信支付' },
{ value: 'WECHAT_MAP', label: 'WECHAT_MAP' }, { value: 'WECHAT_MAP', label: '微信/腾讯地图' },
{ value: 'ALIYUN_OSS', label: 'ALIYUN_OSS' }, { value: 'ALIYUN_OSS', label: '阿里云 OSS' },
{ value: 'ALIYUN_SMS', label: 'ALIYUN_SMS' }, { value: 'ALIYUN_SMS', label: '阿里云短信' },
{ value: 'MOCK_SMS', label: 'MOCK_SMS' }, { value: 'MOCK_SMS', label: 'Mock 短信' },
{ value: 'XFX', label: '小飞侠 (XFX)' }, { value: 'XFX', label: '小飞侠' },
{ value: 'LOGISTICS', label: 'LOGISTICS' }, { value: 'LOGISTICS', label: '物流快递' },
]; ];
const STATUS_COLOR: Record<string, string> = { const STATUS_COLOR: Record<string, string> = {
@@ -73,18 +82,18 @@ export default function ThirdPartyLogsPage() {
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ title: 'Provider', dataIndex: 'provider', width: 120 }, { title: '渠道', dataIndex: 'provider', width: 120, render: (v: string) => zhLabel(THIRD_PARTY_PROVIDER_LABELS, v) },
{ title: '场景', dataIndex: 'scene', width: 120 }, { title: '场景', dataIndex: 'scene', width: 140, render: (v: string) => zhLabel(THIRD_PARTY_SCENE_LABELS, v) },
{ {
title: '关联', title: '关联',
width: 120, width: 120,
render: (_, r) => (r.refType && r.refId ? `${r.refType}#${r.refId}` : '—'), render: (_, r) => formatRef(r.refType, r.refId),
}, },
{ {
title: '状态', title: '状态',
dataIndex: 'status', dataIndex: 'status',
width: 90, width: 90,
render: (v: string) => <Tag color={STATUS_COLOR[v] ?? 'default'}>{v}</Tag>, render: (v: string) => <Tag color={STATUS_COLOR[v] ?? 'default'}>{zhLabel(THIRD_PARTY_STATUS_LABELS, v)}</Tag>,
}, },
{ {
title: '错误信息', title: '错误信息',
@@ -95,7 +104,21 @@ export default function ThirdPartyLogsPage() {
title: '请求摘要', title: '请求摘要',
render: (_, r) => summarizeJson(r.requestBody), render: (_, r) => summarizeJson(r.requestBody),
}, },
{ title: '外部单号', dataIndex: 'externalNo', width: 140, render: (v) => v || '—' }, {
title: '外部单号',
dataIndex: 'externalNo',
width: 140,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
setDetail(await request(`/common/third-party-logs/${row.id}`));
setDrawerOpen(true);
}}
>
{v}
</AdminPrimaryLink>
),
},
{ {
title: '操作', title: '操作',
width: 80, width: 80,
@@ -122,8 +145,7 @@ export default function ThirdPartyLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader title="第三方日志" settings={settingsButton} />
{settingsButton}
<Form <Form
layout="inline" layout="inline"
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
@@ -132,11 +154,11 @@ export default function ThirdPartyLogsPage() {
setPage(1); setPage(1);
}} }}
> >
<Form.Item name="provider" label="Provider"> <Form.Item name="provider" label="渠道">
<Select allowClear placeholder="全部" style={{ width: 160 }} options={PROVIDER_OPTIONS} /> <Select allowClear placeholder="全部" style={{ width: 160 }} options={PROVIDER_OPTIONS} />
</Form.Item> </Form.Item>
<Form.Item name="scene" label="场景"> <Form.Item name="scene" label="场景">
<Input allowClear placeholder="JSSDK_CONFIG / LOGIN" style={{ width: 160 }} /> <Input allowClear placeholder="场景编码" style={{ width: 160 }} />
</Form.Item> </Form.Item>
<Form.Item name="refId" label="关联ID"> <Form.Item name="refId" label="关联ID">
<Input allowClear style={{ width: 120 }} /> <Input allowClear style={{ width: 120 }} />
@@ -166,13 +188,15 @@ export default function ThirdPartyLogsPage() {
{detail && ( {detail && (
<Descriptions column={1} bordered size="small"> <Descriptions column={1} bordered size="small">
<Descriptions.Item label="ID">{String(detail.id)}</Descriptions.Item> <Descriptions.Item label="ID">{String(detail.id)}</Descriptions.Item>
<Descriptions.Item label="Provider">{String(detail.provider)}</Descriptions.Item> <Descriptions.Item label="渠道">{zhLabel(THIRD_PARTY_PROVIDER_LABELS, String(detail.provider))}</Descriptions.Item>
<Descriptions.Item label="场景">{String(detail.scene)}</Descriptions.Item> <Descriptions.Item label="场景">{zhLabel(THIRD_PARTY_SCENE_LABELS, String(detail.scene))}</Descriptions.Item>
<Descriptions.Item label="状态"> <Descriptions.Item label="状态">
<Tag color={STATUS_COLOR[String(detail.status)] ?? 'default'}>{String(detail.status)}</Tag> <Tag color={STATUS_COLOR[String(detail.status)] ?? 'default'}>
{zhLabel(THIRD_PARTY_STATUS_LABELS, String(detail.status))}
</Tag>
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="关联"> <Descriptions.Item label="关联">
{detail.refType ? `${String(detail.refType)}#${String(detail.refId)}` : '—'} {formatRef(detail.refType ? String(detail.refType) : null, detail.refId ? String(detail.refId) : null)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="外部单号">{String(detail.externalNo ?? '—')}</Descriptions.Item> <Descriptions.Item label="外部单号">{String(detail.externalNo ?? '—')}</Descriptions.Item>
<Descriptions.Item label="金额">{detail.amount != null ? String(detail.amount) : '—'}</Descriptions.Item> <Descriptions.Item label="金额">{detail.amount != null ? String(detail.amount) : '—'}</Descriptions.Item>
+16 -1
View File
@@ -26,6 +26,7 @@ import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -118,7 +119,21 @@ export default function TicketsPage() {
} }
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '工单号', dataIndex: 'ticketNo', width: 180 }, {
title: '工单号',
dataIndex: 'ticketNo',
width: 180,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
setDetail(await request(`/admin/tickets/${row.id}`));
setDrawerOpen(true);
}}
>
{v}
</AdminPrimaryLink>
),
},
{ {
title: '类型', title: '类型',
dataIndex: 'ticketType', dataIndex: 'ticketType',
+30 -13
View File
@@ -1,13 +1,16 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Button, Descriptions, Drawer, Form, Input, Segmented, Space, Table, Tag, Typography } from 'antd'; import { Button, Descriptions, Drawer, Form, Input, Segmented, Space, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { USER_LOG_CATEGORY_OPTIONS, resolveUserLogCategory, USER_LOG_CATEGORY_LABELS, type UserLogCategory } from '../lib/user-log'; import { USER_LOG_CATEGORY_OPTIONS, type UserLogCategory } from '../lib/user-log';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { AdminCellLine } from '../components/AdminCellLine'; import { AdminCellLine } from '../components/AdminCellLine';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { clientAppLabel, eventNameLabel, formatRef, userEventCategoryLabel } from '../lib/display-labels';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -25,8 +28,6 @@ type Row = {
createdAt: string; createdAt: string;
}; };
const CATEGORY_LABELS = USER_LOG_CATEGORY_LABELS;
function summarizeExtra(json: Record<string, unknown> | null) { function summarizeExtra(json: Record<string, unknown> | null) {
if (!json) return '—'; if (!json) return '—';
const text = JSON.stringify(json); const text = JSON.stringify(json);
@@ -77,13 +78,30 @@ export default function UserLogsPage() {
{ {
title: '分类', dataIndex: 'category', width: 100, title: '分类', dataIndex: 'category', width: 100,
render: (v: UserLogCategory | null, r) => ( render: (v: UserLogCategory | null, r) => (
<Tag>{CATEGORY_LABELS[v ?? ''] || resolveUserLogCategory(r.eventName) || '其他'}</Tag> <Tag>{userEventCategoryLabel(r.eventName, v)}</Tag>
), ),
}, },
{ title: '事件', dataIndex: 'eventName', width: 160 }, {
title: '事件',
dataIndex: 'eventName',
width: 160,
render: (v, row) => (
<AdminPrimaryLink
onClick={async () => {
setDetail(await request(`/admin/logs/users/${row.id}`));
setDrawerOpen(true);
}}
>
{eventNameLabel(v)}
</AdminPrimaryLink>
),
},
{
title: '端', dataIndex: 'clientApp', width: 110, render: (v) => clientAppLabel(v),
},
{ {
title: '关联', width: 120, title: '关联', width: 120,
render: (_, r) => (r.refType && r.refId ? `${r.refType}#${r.refId}` : '—'), render: (_, r) => formatRef(r.refType, r.refId),
}, },
{ {
title: '摘要', title: '摘要',
@@ -105,8 +123,7 @@ export default function UserLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader title="用户日志" settings={settingsButton} />
{settingsButton}
<Segmented <Segmented
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
options={USER_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))} options={USER_LOG_CATEGORY_OPTIONS.map((o) => ({ value: o.value, label: o.label }))}
@@ -133,7 +150,7 @@ export default function UserLogsPage() {
<Form.Item name="userId" label="用户ID"><Input allowClear style={{ width: 120 }} /></Form.Item> <Form.Item name="userId" label="用户ID"><Input allowClear style={{ width: 120 }} /></Form.Item>
<Form.Item name="phone" label="手机号"><Input allowClear style={{ width: 130 }} /></Form.Item> <Form.Item name="phone" label="手机号"><Input allowClear style={{ width: 130 }} /></Form.Item>
<Form.Item name="userNo" label="用户编号"><Input allowClear style={{ width: 120 }} /></Form.Item> <Form.Item name="userNo" label="用户编号"><Input allowClear style={{ width: 120 }} /></Form.Item>
<Form.Item name="eventName" label="事件"><Input allowClear style={{ width: 160 }} placeholder="pay_success" /></Form.Item> <Form.Item name="eventName" label="事件编码"><Input allowClear style={{ width: 160 }} placeholder="事件编码" /></Form.Item>
<Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item> <Form.Item><Button type="primary" htmlType="submit"></Button></Form.Item>
<Form.Item><Button onClick={() => { form.resetFields(); setFilters({}); setCategory(''); setSearchParams({}); setPage(1); }}></Button></Form.Item> <Form.Item><Button onClick={() => { form.resetFields(); setFilters({}); setCategory(''); setSearchParams({}); setPage(1); }}></Button></Form.Item>
</Form> </Form>
@@ -145,10 +162,10 @@ export default function UserLogsPage() {
<Descriptions.Item label="ID">{String(detail.id)}</Descriptions.Item> <Descriptions.Item label="ID">{String(detail.id)}</Descriptions.Item>
<Descriptions.Item label="用户">{String(detail.nickname || detail.userNo || detail.userId || '—')}</Descriptions.Item> <Descriptions.Item label="用户">{String(detail.nickname || detail.userNo || detail.userId || '—')}</Descriptions.Item>
<Descriptions.Item label="手机">{String(detail.phone || '—')}</Descriptions.Item> <Descriptions.Item label="手机">{String(detail.phone || '—')}</Descriptions.Item>
<Descriptions.Item label="分类">{CATEGORY_LABELS[String(detail.category ?? '')] || String(detail.category || '—')}</Descriptions.Item> <Descriptions.Item label="分类">{userEventCategoryLabel(String(detail.eventName ?? ''), detail.category ? String(detail.category) : null)}</Descriptions.Item>
<Descriptions.Item label="事件">{String(detail.eventName)}</Descriptions.Item> <Descriptions.Item label="事件">{eventNameLabel(String(detail.eventName ?? ''))}</Descriptions.Item>
<Descriptions.Item label="客户端">{String(detail.clientApp || '—')}</Descriptions.Item> <Descriptions.Item label="端">{clientAppLabel(detail.clientApp ? String(detail.clientApp) : null)}</Descriptions.Item>
<Descriptions.Item label="关联">{detail.refType ? `${String(detail.refType)}#${String(detail.refId)}` : '—'}</Descriptions.Item> <Descriptions.Item label="关联">{formatRef(detail.refType ? String(detail.refType) : null, detail.refId ? String(detail.refId) : null)}</Descriptions.Item>
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item> <Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
<Descriptions.Item label="参数"> <Descriptions.Item label="参数">
<pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}> <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
+242 -43
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom'; import { Link, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { import {
Alert, Alert,
Button, Button,
@@ -17,10 +17,14 @@ import {
message, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { USER_SOURCE_TYPE_LABELS, resolveUserLogCategory, type UserSourceType } from '@dukang/shared-types'; import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { USER_SOURCE_TYPE_LABELS, type UserSourceType } from '@dukang/shared-types';
import { request, type AdminUserRow, type HqProfile, type Paginated } from '../lib/api'; import { request, type AdminUserRow, type HqProfile, type Paginated } from '../lib/api';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { ORDER_STATUS_LABELS, fmtTime, maskPhone } from '../lib/constants'; import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
import { ADMIN_OPTIONS_PAGE_SIZE, ORDER_STATUS_LABELS, fmtTime, maskPhone } from '../lib/constants';
import { clientAppLabel, eventNameLabel, userEventCategoryLabel } from '../lib/display-labels';
type UserOrderRow = { type UserOrderRow = {
id: string; id: string;
@@ -117,6 +121,24 @@ type UserBehaviorLog = {
extraJson?: Record<string, unknown> | null; extraJson?: Record<string, unknown> | null;
}; };
type AssocPartnerBrief = {
id: string;
name: string;
companyName?: string | null;
phone?: string | null;
};
type PartnerOption = { id: string; companyName?: string | null; name?: string; phone?: string };
const FILTERS_COLLAPSED_KEY = 'admin-users-filters-collapsed';
const ASSOC_UNBOUND = 'none';
function formatAssocPartner(p?: AssocPartnerBrief | PartnerOption | null) {
if (!p) return '—';
const title = p.companyName || p.name || p.id;
return [title, p.phone].filter(Boolean).join(' / ') || '—';
}
type UserDetail = AdminUserRow & { type UserDetail = AdminUserRow & {
wxUnionId?: string | null; wxUnionId?: string | null;
cityPref?: Record<string, unknown> | null; cityPref?: Record<string, unknown> | null;
@@ -125,6 +147,8 @@ type UserDetail = AdminUserRow & {
orders?: UserOrderRow[]; orders?: UserOrderRow[];
mergedFromCount?: number; mergedFromCount?: number;
addressCount?: number; addressCount?: number;
assocPartner?: AssocPartnerBrief | null;
assocBoundAt?: string | null;
}; };
type BatchDeletePreviewItem = { type BatchDeletePreviewItem = {
@@ -152,6 +176,7 @@ type BatchDeletePreview = {
export default function UsersPage() { export default function UsersPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const [form] = Form.useForm(); const [form] = Form.useForm();
const [profile, setProfile] = useState<HqProfile | null>(null); const [profile, setProfile] = useState<HqProfile | null>(null);
const [data, setData] = useState<Paginated<AdminUserRow> | null>(null); const [data, setData] = useState<Paginated<AdminUserRow> | null>(null);
@@ -172,44 +197,88 @@ export default function UsersPage() {
const [batchDeleting, setBatchDeleting] = useState(false); const [batchDeleting, setBatchDeleting] = useState(false);
const [batchRiskAck, setBatchRiskAck] = useState(false); const [batchRiskAck, setBatchRiskAck] = useState(false);
const canDeleteUsers = (profile?.permissionKeys ?? []).includes('users_delete'); const canDeleteUsers = (profile?.permissionKeys ?? []).includes('users_delete');
const canEditAssoc = (profile?.permissionKeys ?? []).includes('users_partner_assoc');
const [partners, setPartners] = useState<PartnerOption[]>([]);
const [assocPartnerId, setAssocPartnerId] = useState<string | undefined>();
const [savingAssoc, setSavingAssoc] = useState(false);
const [filtersCollapsed, setFiltersCollapsed] = useState(() => {
try {
return localStorage.getItem(FILTERS_COLLAPSED_KEY) === '1';
} catch {
return false;
}
});
const partnerOptions = useMemo(() => {
const map = new Map(partners.map((p) => [p.id, p]));
if (detail?.assocPartner && !map.has(detail.assocPartner.id)) {
map.set(detail.assocPartner.id, detail.assocPartner);
}
return [...map.values()];
}, [partners, detail?.assocPartner]);
useEffect(() => { useEffect(() => {
request<HqProfile>('/admin/auth/me').then(setProfile).catch(() => {}); request<HqProfile>('/admin/auth/me').then(setProfile).catch(() => {});
}, []); }, []);
useEffect(() => {
void request<Paginated<PartnerOption>>(`/admin/partners?pageSize=${ADMIN_OPTIONS_PAGE_SIZE}`)
.then((res) => setPartners(res.items ?? []))
.catch(() => setPartners([]));
}, []);
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
const values = form.getFieldsValue(); const values = form.getFieldsValue();
const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) }); const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
const userId = String(values.userId || '').trim();
if (userId) qs.set('userId', userId);
if (values.phone) qs.set('phone', values.phone); if (values.phone) qs.set('phone', values.phone);
if (values.userNo) qs.set('userNo', values.userNo); if (values.userNo) qs.set('userNo', values.userNo);
if (values.deviceKey) qs.set('deviceKey', values.deviceKey);
if (values.phoneVerified !== undefined && values.phoneVerified !== '') { if (values.phoneVerified !== undefined && values.phoneVerified !== '') {
qs.set('phoneVerified', values.phoneVerified); qs.set('phoneVerified', values.phoneVerified);
} }
if (values.status !== undefined && values.status !== '') { if (values.status !== undefined && values.status !== '') {
qs.set('status', String(values.status)); qs.set('status', String(values.status));
} }
if (values.excludeTest) qs.set('excludeTest', 'true'); const keyword = String(values.keyword || '').trim();
if (keyword) qs.set('keyword', keyword);
const assocPartnerAccountId = String(
values.assocPartnerAccountId || searchParams.get('assocPartnerAccountId') || '',
).trim();
if (assocPartnerAccountId) qs.set('assocPartnerAccountId', assocPartnerAccountId);
const res = await request<Paginated<AdminUserRow>>(`/admin/users?${qs}`); const res = await request<Paginated<AdminUserRow>>(`/admin/users?${qs}`);
setData(res); setData(res);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [form, page, pageSize]); }, [form, page, pageSize, searchParams]);
useEffect(() => {
const userId = searchParams.get('userId');
const assocPartnerAccountId = searchParams.get('assocPartnerAccountId');
form.setFieldsValue({
...(userId ? { userId } : {}),
...(assocPartnerAccountId ? { assocPartnerAccountId } : {}),
});
}, [searchParams, form]);
useEffect(() => { useEffect(() => {
void load(); void load();
}, [load]); }, [load, searchParams]);
useEffect(() => { useEffect(() => {
const openUserId = (location.state as { openUserId?: string } | null)?.openUserId; const openUserId = (location.state as { openUserId?: string } | null)?.openUserId;
if (openUserId) { if (!openUserId) return;
form.setFieldsValue({ userId: openUserId });
setPage(1);
void openDetail(openUserId); void openDetail(openUserId);
navigate(location.pathname, { replace: true, state: null }); navigate(`${location.pathname}?userId=${encodeURIComponent(openUserId)}`, {
} replace: true,
}, [location.state, location.pathname, navigate]); state: null,
});
}, [location.state, location.pathname, navigate, form]);
async function openDetail(id: string) { async function openDetail(id: string) {
const [res, logs] = await Promise.all([ const [res, logs] = await Promise.all([
@@ -219,10 +288,29 @@ export default function UsersPage() {
), ),
]); ]);
setDetail(res); setDetail(res);
setAssocPartnerId(res.assocPartner?.id);
setBehaviorLogs(logs.items ?? []); setBehaviorLogs(logs.items ?? []);
setDrawerOpen(true); setDrawerOpen(true);
} }
async function saveAssoc() {
if (!detail) return;
setSavingAssoc(true);
try {
await request(`/admin/users/${detail.id}/assoc`, {
method: 'PUT',
body: JSON.stringify({ partnerAccountId: assocPartnerId || null }),
});
message.success(assocPartnerId ? '已更新关联合伙人' : '已解除关联');
await openDetail(detail.id);
void load();
} catch (e) {
message.error(e instanceof Error ? e.message : '保存失败');
} finally {
setSavingAssoc(false);
}
}
function openDeleteModal() { function openDeleteModal() {
setDeleteConfirm(''); setDeleteConfirm('');
setDeleteOpen(true); setDeleteOpen(true);
@@ -332,7 +420,9 @@ export default function UsersPage() {
title: '昵称', title: '昵称',
dataIndex: 'nickname', dataIndex: 'nickname',
width: 140, width: 140,
render: (v: string | null) => v || '—', render: (v: string | null, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
),
}, },
{ {
title: '备注', title: '备注',
@@ -403,6 +493,12 @@ export default function UsersPage() {
width: 120, width: 120,
render: (v) => v || '—', render: (v) => v || '—',
}, },
{
title: '关联合伙人',
dataIndex: 'assocPartner',
width: 180,
render: (p: AdminUserRow['assocPartner']) => formatAssocPartner(p),
},
{ {
title: 'deviceKey', title: 'deviceKey',
dataIndex: 'deviceKey', dataIndex: 'deviceKey',
@@ -478,11 +574,11 @@ export default function UsersPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <AdminListHeader
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title> title="用户监控"
<Space> settings={settingsButton}
{settingsButton} actions={
{canDeleteUsers ? ( canDeleteUsers ? (
<Button <Button
danger danger
disabled={!selectedRowKeys.length} disabled={!selectedRowKeys.length}
@@ -490,40 +586,111 @@ export default function UsersPage() {
> >
{selectedRowKeys.length ? ` (${selectedRowKeys.length})` : ''} {selectedRowKeys.length ? ` (${selectedRowKeys.length})` : ''}
</Button> </Button>
) : null} ) : null
}
/>
<Form
form={form}
layout="vertical"
onFinish={() => {
setPage(1);
const next = new URLSearchParams();
const userId = String(form.getFieldValue('userId') || '').trim();
const assoc = String(form.getFieldValue('assocPartnerAccountId') || '').trim();
if (userId) next.set('userId', userId);
if (assoc) next.set('assocPartnerAccountId', assoc);
if (next.toString() !== searchParams.toString()) {
setSearchParams(next, { replace: true });
}
void load();
}}
>
<div className="admin-orders-filter-row">
<Form.Item name="keyword" label="搜索" className="admin-orders-filter-item admin-users-filter-item--keyword">
<Input allowClear placeholder="编号/昵称/备注/手机" />
</Form.Item>
<Form.Item
name="assocPartnerAccountId"
label="关联合伙人"
className="admin-orders-filter-item admin-orders-filter-item--status"
>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="全部"
options={[
{ value: 'any', label: '已关联(全部)' },
{ value: ASSOC_UNBOUND, label: '未关联' },
...partners.map((p) => ({
value: p.id,
label: formatAssocPartner(p),
})),
]}
/>
</Form.Item>
<Form.Item label=" " colon={false} className="admin-orders-filter-item admin-orders-filter-actions">
<Space size={8} wrap>
<Button type="primary" htmlType="submit"></Button>
<Button
onClick={() => {
form.resetFields();
setPage(1);
if (searchParams.toString()) {
setSearchParams({}, { replace: true });
} else {
void load();
}
}}
>
</Button>
<Button
type="link"
icon={filtersCollapsed ? <DownOutlined /> : <UpOutlined />}
onClick={() => {
setFiltersCollapsed((prev) => {
const next = !prev;
try {
localStorage.setItem(FILTERS_COLLAPSED_KEY, next ? '1' : '0');
} catch {
/* ignore */
}
return next;
});
}}
>
{filtersCollapsed ? '展开' : '收起'}
</Button>
</Space> </Space>
</Space> </Form.Item>
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={() => { setPage(1); void load(); }}> </div>
<Form.Item name="phone" label="手机号">
{!filtersCollapsed ? (
<div className="admin-orders-filter-row">
<Form.Item name="phone" label="手机号" className="admin-orders-filter-item admin-orders-filter-item--md">
<Input placeholder="模糊搜索" allowClear /> <Input placeholder="模糊搜索" allowClear />
</Form.Item> </Form.Item>
<Form.Item name="userNo" label="用户编号"> <Form.Item name="userNo" label="用户编号" className="admin-orders-filter-item admin-orders-filter-item--md">
<Input placeholder="DK..." allowClear /> <Input placeholder="DK..." allowClear />
</Form.Item> </Form.Item>
<Form.Item name="deviceKey" label="deviceKey"> <Form.Item name="userId" label="用户ID" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Input placeholder="UUID" allowClear style={{ width: 200 }} /> <Input placeholder="精确匹配" allowClear />
</Form.Item> </Form.Item>
<Form.Item name="phoneVerified" label="验手机"> <Form.Item name="phoneVerified" label="验手机" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Select allowClear style={{ width: 100 }} options={[ <Select allowClear placeholder="全部" options={[
{ value: '1', label: '已验证' }, { value: '1', label: '已验证' },
{ value: '0', label: '访客' }, { value: '0', label: '访客' },
]} /> ]} />
</Form.Item> </Form.Item>
<Form.Item name="status" label="状态"> <Form.Item name="status" label="状态" className="admin-orders-filter-item admin-orders-filter-item--sm">
<Select allowClear style={{ width: 90 }} options={[ <Select allowClear placeholder="全部" options={[
{ value: 1, label: '正常' }, { value: 1, label: '正常' },
{ value: 0, label: '停用' }, { value: 0, label: '停用' },
]} /> ]} />
</Form.Item> </Form.Item>
<Form.Item name="excludeTest" valuePropName="checked"> </div>
<Checkbox></Checkbox> ) : null}
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" htmlType="submit"></Button>
<Button onClick={() => { form.resetFields(); setPage(1); void load(); }}></Button>
</Space>
</Form.Item>
</Form> </Form>
<Table <Table
@@ -565,7 +732,7 @@ export default function UsersPage() {
<Descriptions.Item label="用户编号">{detail.userNo}</Descriptions.Item> <Descriptions.Item label="用户编号">{detail.userNo}</Descriptions.Item>
<Descriptions.Item label="昵称">{detail.nickname || '—'}</Descriptions.Item> <Descriptions.Item label="昵称">{detail.nickname || '—'}</Descriptions.Item>
<Descriptions.Item label="备注">{detail.hqRemark || '—'}</Descriptions.Item> <Descriptions.Item label="备注">{detail.hqRemark || '—'}</Descriptions.Item>
<Descriptions.Item label="手机号">{maskPhone(detail.phone)}</Descriptions.Item> <Descriptions.Item label="手机号">{detail.phone || '—'}</Descriptions.Item>
<Descriptions.Item label="验手机时间"> <Descriptions.Item label="验手机时间">
{detail.phoneVerifiedAt ? new Date(detail.phoneVerifiedAt).toLocaleString('zh-CN') : '未验证'} {detail.phoneVerifiedAt ? new Date(detail.phoneVerifiedAt).toLocaleString('zh-CN') : '未验证'}
</Descriptions.Item> </Descriptions.Item>
@@ -587,6 +754,38 @@ export default function UsersPage() {
) : '—'} ) : '—'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="来源标签">{detail.sourceLabel || '—'}</Descriptions.Item> <Descriptions.Item label="来源标签">{detail.sourceLabel || '—'}</Descriptions.Item>
<Descriptions.Item label="关联合伙人">
{canEditAssoc ? (
<Space wrap>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="未关联"
style={{ minWidth: 260 }}
value={assocPartnerId}
onChange={setAssocPartnerId}
options={partnerOptions.map((p) => ({
value: p.id,
label: `${p.companyName || p.name || p.id}${p.phone ? ` · ${p.phone}` : ''}`,
}))}
/>
<Button type="primary" size="small" loading={savingAssoc} onClick={() => void saveAssoc()}>
</Button>
<Typography.Text type="secondary"></Typography.Text>
</Space>
) : detail.assocPartner ? (
`${detail.assocPartner.companyName || detail.assocPartner.name}${
detail.assocPartner.phone ? ` / ${detail.assocPartner.phone}` : ''
}`
) : (
'—'
)}
</Descriptions.Item>
<Descriptions.Item label="关联时间">
{detail.assocBoundAt ? fmtTime(detail.assocBoundAt) : '—'}
</Descriptions.Item>
{detail.sourcePromo && ( {detail.sourcePromo && (
<Descriptions.Item label="推广码"> <Descriptions.Item label="推广码">
<Link to={`/promo-codes/${detail.sourcePromo.id}`}> <Link to={`/promo-codes/${detail.sourcePromo.id}`}>
@@ -599,7 +798,7 @@ export default function UsersPage() {
<Descriptions.Item label="deviceKey">{detail.deviceKey || '—'}</Descriptions.Item> <Descriptions.Item label="deviceKey">{detail.deviceKey || '—'}</Descriptions.Item>
<Descriptions.Item label="合并至"> <Descriptions.Item label="合并至">
{detail.mergedInto {detail.mergedInto
? `${detail.mergedInto.userNo} (${detail.mergedInto.phone ? maskPhone(detail.mergedInto.phone) : '无手机'})` ? `${detail.mergedInto.userNo} (${detail.mergedInto.phone || '无手机'})`
: '—'} : '—'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="被合并访客数">{detail.mergedFromCount ?? 0}</Descriptions.Item> <Descriptions.Item label="被合并访客数">{detail.mergedFromCount ?? 0}</Descriptions.Item>
@@ -636,10 +835,10 @@ export default function UsersPage() {
{ {
title: '分类', title: '分类',
width: 100, width: 100,
render: (_, r) => resolveUserLogCategory(r.eventName) ?? '—', render: (_, r) => userEventCategoryLabel(r.eventName),
}, },
{ title: '事件', dataIndex: 'eventName' }, { title: '事件', dataIndex: 'eventName', render: (v: string) => eventNameLabel(v) },
{ title: '端', dataIndex: 'clientApp', width: 90 }, { title: '端', dataIndex: 'clientApp', width: 110, render: (v: string | null) => clientAppLabel(v) },
]} ]}
/> />
@@ -8,6 +8,8 @@ import { AdminCellLine } from '../components/AdminCellLine';
import { fmtTime, maskPhone } from '../lib/constants'; import { fmtTime, maskPhone } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type ActorType = 'USER' | 'STORE' | 'PARTNER' | 'HQ'; type ActorType = 'USER' | 'STORE' | 'PARTNER' | 'HQ';
@@ -120,7 +122,9 @@ export default function WechatBindingsPage() {
title: '手机号', title: '手机号',
dataIndex: 'primaryPhone', dataIndex: 'primaryPhone',
width: 140, width: 140,
render: (v) => maskPhone(v), render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row)}>{maskPhone(v)}</AdminPrimaryLink>
),
}, },
{ {
title: '身份摘要', title: '身份摘要',
@@ -207,11 +211,11 @@ export default function WechatBindingsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader
{settingsButton} title="微信绑定总览"
<Typography.Paragraph type="secondary"> settings={settingsButton}
unionId C HQ unionId description="按 unionId 聚合展示已绑定微信的 C 端用户、门店账号、合伙人账号与 HQ 账号;无 unionId 时按单账号分组。"
</Typography.Paragraph> />
<Form <Form
form={form} form={form}
+24 -14
View File
@@ -4,8 +4,11 @@ import type { ColumnsType } from 'antd/es/table';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { request } from '../lib/api'; import { request } from '../lib/api';
import { fmtTime } from '../lib/constants'; import { fmtTime } from '../lib/constants';
import { WECOM_BOT_ACTION_LABELS, zhLabel } from '../lib/display-labels';
import type { WecomBotLogDto } from '@dukang/shared-types'; import type { WecomBotLogDto } from '@dukang/shared-types';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
export default function WecomBotLogsPage() { export default function WecomBotLogsPage() {
@@ -28,10 +31,17 @@ export default function WecomBotLogsPage() {
const baseColumns: ColumnsType<WecomBotLogDto> = [ const baseColumns: ColumnsType<WecomBotLogDto> = [
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ title: '机器人', dataIndex: 'botName', width: 120, render: (v, r) => v || r.botKey || '—' }, {
title: '机器人',
dataIndex: 'botName',
width: 120,
render: (v, r) => (
<AdminPrimaryLink onClick={() => setDetail(r)}>{v || r.botKey || ''}</AdminPrimaryLink>
),
},
{ title: '企微用户', dataIndex: 'wecomUserId', width: 120 }, { title: '企微用户', dataIndex: 'wecomUserId', width: 120 },
{ title: '动作', dataIndex: 'action', width: 160 }, { title: '动作', dataIndex: 'action', width: 180, render: (v: string) => zhLabel(WECOM_BOT_ACTION_LABELS, v) },
{ title: '权限', dataIndex: 'permission', width: 140, render: (v) => v || '—' }, { title: '权限', dataIndex: 'permission', width: 160, render: (v) => zhLabel(WECOM_BOT_ACTION_LABELS, v) },
{ {
title: '结果', title: '结果',
dataIndex: 'success', dataIndex: 'success',
@@ -56,11 +66,11 @@ export default function WecomBotLogsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<Typography.Title level={4}></Typography.Title> <AdminListHeader
{settingsButton} title="企微机器人日志"
<Typography.Paragraph type="secondary"> settings={settingsButton}
description="记录机器人在企微内的查询与审批操作,含权限点、耗时与成败。"
</Typography.Paragraph> />
<Form <Form
form={form} form={form}
@@ -72,13 +82,13 @@ export default function WecomBotLogsPage() {
}} }}
> >
<Form.Item name="botId" label="机器人 ID"> <Form.Item name="botId" label="机器人 ID">
<Input allowClear placeholder="wecom_bot.id" style={{ width: 140 }} /> <Input allowClear placeholder="机器人 ID" style={{ width: 140 }} />
</Form.Item> </Form.Item>
<Form.Item name="wecomUserId" label="企微 userid"> <Form.Item name="wecomUserId" label="企微用户">
<Input allowClear placeholder="userid" style={{ width: 140 }} /> <Input allowClear placeholder="企微用户 ID" style={{ width: 140 }} />
</Form.Item> </Form.Item>
<Form.Item name="action" label="动作"> <Form.Item name="action" label="动作">
<Input allowClear placeholder="order.read" style={{ width: 140 }} /> <Input allowClear placeholder="动作编码" style={{ width: 140 }} />
</Form.Item> </Form.Item>
<Form.Item name="success" label="结果"> <Form.Item name="success" label="结果">
<Select <Select
@@ -121,8 +131,8 @@ export default function WecomBotLogsPage() {
<Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item> <Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
<Descriptions.Item label="机器人">{detail.botName || detail.botKey || '—'}</Descriptions.Item> <Descriptions.Item label="机器人">{detail.botName || detail.botKey || '—'}</Descriptions.Item>
<Descriptions.Item label="企微用户">{detail.wecomUserId}</Descriptions.Item> <Descriptions.Item label="企微用户">{detail.wecomUserId}</Descriptions.Item>
<Descriptions.Item label="动作">{detail.action}</Descriptions.Item> <Descriptions.Item label="动作">{zhLabel(WECOM_BOT_ACTION_LABELS, detail.action)}</Descriptions.Item>
<Descriptions.Item label="权限">{detail.permission || '—'}</Descriptions.Item> <Descriptions.Item label="权限">{zhLabel(WECOM_BOT_ACTION_LABELS, detail.permission)}</Descriptions.Item>
<Descriptions.Item label="输入摘要">{detail.inputSummary || '—'}</Descriptions.Item> <Descriptions.Item label="输入摘要">{detail.inputSummary || '—'}</Descriptions.Item>
<Descriptions.Item label="结果">{detail.success ? '成功' : '失败'}</Descriptions.Item> <Descriptions.Item label="结果">{detail.success ? '成功' : '失败'}</Descriptions.Item>
<Descriptions.Item label="错误">{detail.errorMessage || '—'}</Descriptions.Item> <Descriptions.Item label="错误">{detail.errorMessage || '—'}</Descriptions.Item>
+9 -1
View File
@@ -37,6 +37,7 @@ import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type FormValues = { type FormValues = {
@@ -293,7 +294,14 @@ export default function WecomBotsPage() {
</Avatar> </Avatar>
), ),
}, },
{ title: '名称', dataIndex: 'name', width: 140 }, {
title: '名称',
dataIndex: 'name',
width: 140,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openEdit(row)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '角色', title: '角色',
dataIndex: 'role', dataIndex: 'role',
@@ -35,6 +35,8 @@ import { fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import OssUpload from '../components/OssUpload'; import OssUpload from '../components/OssUpload';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type FormValues = { type FormValues = {
@@ -202,7 +204,7 @@ function PushRoutesTab() {
render: (name: string, row) => ( render: (name: string, row) => (
<Space> <Space>
<Avatar src={row.avatarUrl ?? undefined}>{name.slice(0, 1)}</Avatar> <Avatar src={row.avatarUrl ?? undefined}>{name.slice(0, 1)}</Avatar>
<span>{name}</span> <AdminPrimaryLink onClick={() => openEdit(row)}>{name}</AdminPrimaryLink>
</Space> </Space>
), ),
}, },
@@ -271,9 +273,15 @@ function PushRoutesTab() {
return ( return (
<> <>
{settingsModal} {settingsModal}
<Typography.Paragraph type="secondary"> <AdminListHeader
Webhook / .env Webhook URL settings={settingsButton}
</Typography.Paragraph> description="配置群机器人 Webhook:按推送条件订阅业务通知 / 告警。运行时不再读取 .env 中的 Webhook URL。"
actions={
<Button type="primary" onClick={openCreate}>
</Button>
}
/>
<Form <Form
form={filterForm} form={filterForm}
@@ -308,10 +316,6 @@ function PushRoutesTab() {
> >
</Button> </Button>
<Button type="primary" onClick={openCreate}>
</Button>
{settingsButton}
</Space> </Space>
</Form.Item> </Form.Item>
</Form> </Form>
+19 -23
View File
@@ -27,6 +27,8 @@ import { downloadExcelCsv } from '../lib/exportExcel';
import { request, type HqProfile } from '../lib/api'; import { request, type HqProfile } from '../lib/api';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
import { useAdminListColumns } from '../lib/useAdminListColumns'; import { useAdminListColumns } from '../lib/useAdminListColumns';
import { AdminListHeader } from '../components/AdminListHeader';
import { AdminPrimaryLink } from '../components/AdminPrimaryLink';
type Row = { type Row = {
@@ -238,7 +240,14 @@ export default function WineryBillsPage() {
const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.wineryAmount), 0); const selectedAmount = selectedRows.reduce((s, r) => s + Number(r.wineryAmount), 0);
const baseColumns: ColumnsType<Row> = [ const baseColumns: ColumnsType<Row> = [
{ title: '账单号', dataIndex: 'billNo', width: 170 }, {
title: '账单号',
dataIndex: 'billNo',
width: 170,
render: (v, row) => (
<AdminPrimaryLink onClick={() => void openDetail(row.id)}>{v}</AdminPrimaryLink>
),
},
{ {
title: '账单日', title: '账单日',
dataIndex: 'billDate', dataIndex: 'billDate',
@@ -297,31 +306,18 @@ export default function WineryBillsPage() {
return ( return (
<div> <div>
{settingsModal} {settingsModal}
<div <AdminListHeader
style={{ title="酒厂对账单"
display: 'flex', settings={settingsButton}
justifyContent: 'space-between', description={`T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × ${ratePct}%);未打款红色、已打款绿色、应付为 0 无需打款(灰),可展开订单明细`}
alignItems: 'flex-start', actions={
marginBottom: 16, canEditWineryBank ? (
gap: 16,
}}
>
<Space direction="vertical" size={0}>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
{settingsButton}
<Typography.Text type="secondary">
T+3 8:00 3 / × {ratePct}%绿 0
</Typography.Text>
</Space>
{canEditWineryBank ? (
<Button type="default" onClick={() => void openBankModal()}> <Button type="default" onClick={() => void openBankModal()}>
</Button> </Button>
) : null} ) : null
</div> }
/>
{summary && ( {summary && (
<Card size="small" style={{ marginBottom: 16 }}> <Card size="small" style={{ marginBottom: 16 }}>
@@ -1,5 +1,6 @@
import { useState, type CSSProperties } from 'react'; import { useState, type CSSProperties } from 'react';
import { useOutletContext } from 'react-router-dom'; import { useNavigate, useOutletContext } from 'react-router-dom';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { import {
Button, Button,
Card, Card,
@@ -13,6 +14,7 @@ import {
Select, Select,
Space, Space,
Statistic, Statistic,
Tooltip,
Typography, Typography,
message, message,
} from 'antd'; } from 'antd';
@@ -35,6 +37,9 @@ const descContentStyle: CSSProperties = {
wordBreak: 'break-all', wordBreak: 'break-all',
}; };
const ATTRIBUTION_HINT =
'首次触达本推广码的用户。每人只归因一次、只归一个码:已登录用户扫码或带参进入时,若还没有归因记录,则记到本码;之后再扫其他码不会改。与「扫码注册」不同:注册只统计来源仍是自然量并被标记为本码的用户;已有其他来源(如分享)的用户仍可计入归因,但不计入扫码注册。';
async function downloadQrcode(url: string, filename: string) { async function downloadQrcode(url: string, filename: string) {
try { try {
const res = await fetch(url); const res = await fetch(url);
@@ -51,6 +56,7 @@ async function downloadQrcode(url: string, filename: string) {
} }
export default function PromoCodeDetailPage() { export default function PromoCodeDetailPage() {
const navigate = useNavigate();
const { detail, reload } = useOutletContext<PromoCodeDetailContext>(); const { detail, reload } = useOutletContext<PromoCodeDetailContext>();
const [editForm] = Form.useForm(); const [editForm] = Form.useForm();
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
@@ -209,14 +215,26 @@ export default function PromoCodeDetailPage() {
<Row gutter={16} style={{ marginTop: 16 }}> <Row gutter={16} style={{ marginTop: 16 }}>
<Col xs={12} sm={6}> <Col xs={12} sm={6}>
<Card size="small"> <Card
size="small"
hoverable
style={{ cursor: 'pointer' }}
onClick={() => navigate(`/promo-codes/${detail.id}?eventType=SCAN`)}
>
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} /> <Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
</Card> </Card>
</Col> </Col>
<Col xs={12} sm={6}> <Col xs={12} sm={6}>
<Card size="small"> <Card size="small">
<Statistic <Statistic
title="归因用户数" title={
<span>
<Tooltip title={ATTRIBUTION_HINT} overlayInnerStyle={{ maxWidth: 360 }}>
<QuestionCircleOutlined style={{ marginLeft: 6, color: 'rgba(0,0,0,0.45)' }} />
</Tooltip>
</span>
}
value={stats?.attributionCount ?? 0} value={stats?.attributionCount ?? 0}
/> />
</Card> </Card>
@@ -230,8 +248,23 @@ export default function PromoCodeDetailPage() {
</Card> </Card>
</Col> </Col>
<Col xs={12} sm={6}> <Col xs={12} sm={6}>
<Card size="small"> <Card
<Statistic title="订单数" value={stats?.orderCount ?? detail.orderCount} /> size="small"
hoverable
style={{ cursor: 'pointer' }}
onClick={() => navigate(`/orders?promoCodeId=${detail.id}&status=COMPLETED`)}
>
<Statistic
title={
<span>
<Tooltip title="仅统计已完成订单" overlayInnerStyle={{ maxWidth: 280 }}>
<QuestionCircleOutlined style={{ marginLeft: 6, color: 'rgba(0,0,0,0.45)' }} />
</Tooltip>
</span>
}
value={stats?.orderCount ?? detail.orderCount}
/>
</Card> </Card>
</Col> </Col>
<Col xs={12} sm={6}> <Col xs={12} sm={6}>
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { import {
Card, Card,
DatePicker, DatePicker,
@@ -21,6 +22,7 @@ import {
} from '@dukang/shared-types'; } from '@dukang/shared-types';
import { request, type Paginated } from '../../lib/api'; import { request, type Paginated } from '../../lib/api';
import { fmtTime } from '../../lib/constants'; import { fmtTime } from '../../lib/constants';
import { AdminPrimaryLink } from '../../components/AdminPrimaryLink';
type Props = { type Props = {
promoId: string; promoId: string;
@@ -57,11 +59,45 @@ function buildEventsQs(
return `/admin/promo-codes/${promoId}/metrics/events?${qs.toString()}`; return `/admin/promo-codes/${promoId}/metrics/events?${qs.toString()}`;
} }
function formatRefId(row: PromoMetricEventItem): string { function parseEventType(raw: string | null): PromoMetricEventType | undefined {
if (row.orderId) return `订单 ${row.orderId}`; if (raw === 'SCAN' || raw === 'ATTRIBUTION' || raw === 'REGISTER' || raw === 'ORDER') return raw;
if (row.userId) return `用户 ${row.userId}`; return undefined;
if (row.sessionId) return `会话 ${row.sessionId}`; }
return '—';
function EventRefLinks({ row }: { row: PromoMetricEventItem }) {
const navigate = useNavigate();
const links = [];
if (row.orderId) {
links.push(
<AdminPrimaryLink
key="order"
onClick={() => {
if (row.orderNo) {
navigate(`/orders?orderNo=${encodeURIComponent(row.orderNo)}`);
} else {
navigate('/orders', { state: { openOrderId: String(row.orderId) } });
}
}}
>
{row.orderNo || row.orderId}
</AdminPrimaryLink>,
);
}
if (row.userId) {
links.push(
<AdminPrimaryLink
key="user"
onClick={() => navigate('/users', { state: { openUserId: String(row.userId) } })}
>
{row.userNo || row.userId}
</AdminPrimaryLink>,
);
}
if (links.length) {
return <Space size={12}>{links}</Space>;
}
if (row.sessionId) return <> {row.sessionId}</>;
return <></>;
} }
function formatLocation(row: PromoMetricEventItem): string { function formatLocation(row: PromoMetricEventItem): string {
@@ -71,15 +107,27 @@ function formatLocation(row: PromoMetricEventItem): string {
} }
export default function PromoCodeMetricsPanel({ promoId }: Props) { export default function PromoCodeMetricsPanel({ promoId }: Props) {
const [searchParams, setSearchParams] = useSearchParams();
const urlEventType = parseEventType(searchParams.get('eventType'));
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(6, 'day'), dayjs()]); const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(6, 'day'), dayjs()]);
const [granularity, setGranularity] = useState<'day' | 'hour'>('day'); const [granularity, setGranularity] = useState<'day' | 'hour'>('day');
const [timeline, setTimeline] = useState<PromoMetricTimelineDto | null>(null); const [timeline, setTimeline] = useState<PromoMetricTimelineDto | null>(null);
const [timelineLoading, setTimelineLoading] = useState(false); const [timelineLoading, setTimelineLoading] = useState(false);
const [eventType, setEventType] = useState<PromoMetricEventType | undefined>(); const [eventType, setEventType] = useState<PromoMetricEventType | undefined>(urlEventType);
const [eventsPage, setEventsPage] = useState(1); const [eventsPage, setEventsPage] = useState(1);
const [events, setEvents] = useState<Paginated<PromoMetricEventItem> | null>(null); const [events, setEvents] = useState<Paginated<PromoMetricEventItem> | null>(null);
const [eventsLoading, setEventsLoading] = useState(false); const [eventsLoading, setEventsLoading] = useState(false);
useEffect(() => {
setEventType(urlEventType);
setEventsPage(1);
if (urlEventType) {
window.requestAnimationFrame(() => {
document.getElementById('promo-metric-events')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
}
}, [urlEventType]);
const loadTimeline = useCallback(() => { const loadTimeline = useCallback(() => {
setTimelineLoading(true); setTimelineLoading(true);
return request<PromoMetricTimelineDto>(buildTimelineQs(promoId, range, granularity)) return request<PromoMetricTimelineDto>(buildTimelineQs(promoId, range, granularity))
@@ -164,7 +212,7 @@ export default function PromoCodeMetricsPanel({ promoId }: Props) {
{ {
title: 'ID', title: 'ID',
key: 'ref', key: 'ref',
render: (_, row) => formatRefId(row), render: (_, row) => <EventRefLinks row={row} />,
}, },
{ {
title: 'IP', title: 'IP',
@@ -220,7 +268,7 @@ export default function PromoCodeMetricsPanel({ promoId }: Props) {
notMerge notMerge
/> />
<Typography.Title level={5} style={{ marginTop: 24, marginBottom: 12 }}> <Typography.Title id="promo-metric-events" level={5} style={{ marginTop: 24, marginBottom: 12 }}>
</Typography.Title> </Typography.Title>
<Space wrap style={{ marginBottom: 12 }}> <Space wrap style={{ marginBottom: 12 }}>
@@ -232,6 +280,10 @@ export default function PromoCodeMetricsPanel({ promoId }: Props) {
onChange={(v) => { onChange={(v) => {
setEventType(v); setEventType(v);
setEventsPage(1); setEventsPage(1);
const next = new URLSearchParams(searchParams);
if (v) next.set('eventType', v);
else next.delete('eventType');
setSearchParams(next, { replace: true });
}} }}
options={Object.entries(PROMO_METRIC_EVENT_LABELS).map(([value, label]) => ({ options={Object.entries(PROMO_METRIC_EVENT_LABELS).map(([value, label]) => ({
value, value,
@@ -1,5 +1,5 @@
import { useNavigate, useOutletContext, useParams } from 'react-router-dom'; import { useNavigate, useOutletContext, useParams } from 'react-router-dom';
import { Button, Space, Table, Tag } from 'antd'; import { Button, Space, Table, Tag, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { import {
USER_SOURCE_TYPE_LABELS, USER_SOURCE_TYPE_LABELS,
@@ -10,6 +10,8 @@ import { fmtTime } from '../../lib/constants';
import { useAdminList } from '../../lib/useAdminList'; import { useAdminList } from '../../lib/useAdminList';
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout'; import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';
import { useAdminListColumns } from '../../lib/useAdminListColumns'; import { useAdminListColumns } from '../../lib/useAdminListColumns';
import { AdminPrimaryLink } from '../../components/AdminPrimaryLink';
import { AdminListHeader } from '../../components/AdminListHeader';
export default function PromoCodeUsersPage() { export default function PromoCodeUsersPage() {
@@ -25,7 +27,16 @@ export default function PromoCodeUsersPage() {
const baseColumns: ColumnsType<PromoCodeAttributedUser> = [ const baseColumns: ColumnsType<PromoCodeAttributedUser> = [
{ title: '用户编号', dataIndex: 'userNo', width: 120 }, { title: '用户编号', dataIndex: 'userNo', width: 120 },
{ title: '昵称', dataIndex: 'nickname', width: 100, render: (v) => v || '—' }, {
title: '昵称',
dataIndex: 'nickname',
width: 100,
render: (v, row) => (
<AdminPrimaryLink onClick={() => navigate('/users', { state: { openUserId: row.id } })}>
{v}
</AdminPrimaryLink>
),
},
{ title: '手机', dataIndex: 'phone', width: 120, render: (v) => v || '—' }, { title: '手机', dataIndex: 'phone', width: 120, render: (v) => v || '—' },
{ {
title: '验手机', title: '验手机',
@@ -55,7 +66,7 @@ export default function PromoCodeUsersPage() {
width: 160, width: 160,
render: (v) => (v ? fmtTime(v) : '—'), render: (v) => (v ? fmtTime(v) : '—'),
}, },
{ title: '订单数', dataIndex: 'orderCount', width: 80 }, { title: <Tooltip title="仅统计已完成订单"></Tooltip>, dataIndex: 'orderCount', width: 80 },
{ title: '注册时间', dataIndex: 'createdAt', width: 160, render: fmtTime }, { title: '注册时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
{ {
title: '操作', title: '操作',
@@ -74,6 +85,9 @@ export default function PromoCodeUsersPage() {
const { columns, settingsButton, settingsModal } = useAdminListColumns('promo-code-users', baseColumns, { page, pageSize }); const { columns, settingsButton, settingsModal } = useAdminListColumns('promo-code-users', baseColumns, { page, pageSize });
return ( return (
<>
{settingsModal}
<AdminListHeader settings={settingsButton} />
<Table <Table
rowKey="id" rowKey="id"
className="admin-table-nowrap" className="admin-table-nowrap"
@@ -89,5 +103,6 @@ export default function PromoCodeUsersPage() {
onChange: (p, ps) => { setPage(p); setPageSize(ps); }, onChange: (p, ps) => { setPage(p); setPageSize(ps); },
}} }}
/> />
</>
); );
} }
+1
View File
@@ -3,6 +3,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="robots" content="noindex, nofollow, noarchive" />
<title>城市合伙人</title> <title>城市合伙人</title>
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+11
View File
@@ -22,12 +22,17 @@ import ProxyOrderDetailPage from './pages/ProxyOrderDetailPage';
import StaffListPage from './pages/StaffListPage'; import StaffListPage from './pages/StaffListPage';
import StaffCreatePage from './pages/StaffCreatePage'; import StaffCreatePage from './pages/StaffCreatePage';
import LeaderboardPage from './pages/LeaderboardPage'; import LeaderboardPage from './pages/LeaderboardPage';
import UsersManagePage from './pages/UsersManagePage';
import AssocOrdersPage from './pages/AssocOrdersPage';
import CommissionOrdersPage from './pages/CommissionOrdersPage';
import ActivityPostersPage from './pages/ActivityPostersPage';
function PrimaryRoutes() { function PrimaryRoutes() {
return ( return (
<Routes> <Routes>
<Route element={<TabLayout />}> <Route element={<TabLayout />}>
<Route path="/" element={<HomePage />} /> <Route path="/" element={<HomePage />} />
<Route path="/users" element={<UsersManagePage />} />
<Route path="/stores" element={<StoreListPage />} /> <Route path="/stores" element={<StoreListPage />} />
<Route path="/center" element={<CenterPage />} /> <Route path="/center" element={<CenterPage />} />
</Route> </Route>
@@ -37,6 +42,12 @@ function PrimaryRoutes() {
<Route path="/center/settlement" element={<SettlementPage />} /> <Route path="/center/settlement" element={<SettlementPage />} />
<Route path="/center/staff" element={<StaffListPage />} /> <Route path="/center/staff" element={<StaffListPage />} />
<Route path="/center/staff/new" element={<StaffCreatePage />} /> <Route path="/center/staff/new" element={<StaffCreatePage />} />
<Route path="/center/activity-posters" element={<ActivityPostersPage />} />
<Route path="/center/assoc" element={<Navigate to="/users" replace />} />
<Route path="/center/assoc/users" element={<Navigate to="/users" replace />} />
<Route path="/users/orders" element={<AssocOrdersPage />} />
<Route path="/users/:userId/orders" element={<AssocOrdersPage />} />
<Route path="/center/commissions" element={<CommissionOrdersPage />} />
<Route path="/center/proxy-orders" element={<ProxyOrderListPage />} /> <Route path="/center/proxy-orders" element={<ProxyOrderListPage />} />
<Route path="/center/proxy-orders/:id" element={<ProxyOrderDetailPage />} /> <Route path="/center/proxy-orders/:id" element={<ProxyOrderDetailPage />} />
<Route path="/proxy-order" element={<ProxyOrderPage />} /> <Route path="/proxy-order" element={<ProxyOrderPage />} />
@@ -0,0 +1,246 @@
import { useEffect, useRef, useState } from 'react';
import type { ActivityPosterItem, PartnerAssocSummary } from '@dukang/shared-types';
import { request } from '../lib/api';
import {
copyActivityCopy,
downloadBlob,
fetchActivityPosterImage,
fetchAssocQrcodeImage,
getActivityPosterSelection,
listActivityPosters,
saveActivityPosterSelection,
} from '../lib/activity-posters';
import { toastError, toastSuccess } from '../lib/toast';
import { isWechatEnv } from '../lib/weixin';
const NONE_ID = 'none';
type Props = {
initialId?: string | null;
};
export default function ActivityPosterPicker({ initialId }: Props) {
const [items, setItems] = useState<ActivityPosterItem[]>([]);
const [qrcodeUrl, setQrcodeUrl] = useState<string | null>(null);
const [partnerId, setPartnerId] = useState<string>('');
const [selectedId, setSelectedId] = useState<string>(NONE_ID);
const [previewUrls, setPreviewUrls] = useState<Record<string, string>>({});
const [listLoading, setListLoading] = useState(true);
const [previewLoading, setPreviewLoading] = useState(false);
const [downloading, setDownloading] = useState(false);
const blobsRef = useRef(new Map<string, Blob>());
const urlsRef = useRef<string[]>([]);
useEffect(() => () => {
urlsRef.current.forEach((url) => URL.revokeObjectURL(url));
}, []);
useEffect(() => {
let cancelled = false;
Promise.all([
listActivityPosters(),
request<PartnerAssocSummary>('PARTNER_H5', '/partner/assoc', { silent: true }),
getActivityPosterSelection().catch(() => ({ posterId: null })),
])
.then(([list, assoc, selection]) => {
if (cancelled) return;
setItems(list);
setQrcodeUrl(assoc.qrcodeUrl);
setPartnerId(assoc.partnerId);
const saved = selection.posterId && list.some((item) => item.id === selection.posterId)
? selection.posterId
: null;
const fromQuery = initialId && list.some((item) => item.id === initialId) ? initialId : null;
const next = saved || fromQuery || NONE_ID;
setSelectedId(next);
if (!saved && fromQuery) {
void saveActivityPosterSelection(fromQuery).catch((err) => {
toastError(err instanceof Error ? err.message : '保存失败');
});
}
})
.catch((e) => toastError(e instanceof Error ? e.message : '加载活动图失败'))
.finally(() => {
if (!cancelled) setListLoading(false);
});
return () => {
cancelled = true;
};
}, [initialId]);
useEffect(() => {
if (selectedId === NONE_ID || previewUrls[selectedId] || blobsRef.current.has(selectedId)) return;
let cancelled = false;
setPreviewLoading(true);
fetchActivityPosterImage(selectedId)
.then((blob) => {
if (cancelled) return;
blobsRef.current.set(selectedId, blob);
const url = URL.createObjectURL(blob);
urlsRef.current.push(url);
setPreviewUrls((prev) => ({ ...prev, [selectedId]: url }));
})
.catch((e) => {
if (!cancelled) toastError(e instanceof Error ? e.message : '预览失败');
})
.finally(() => {
if (!cancelled) setPreviewLoading(false);
});
return () => {
cancelled = true;
};
}, [selectedId, previewUrls]);
const selected = items.find((item) => item.id === selectedId) ?? null;
const previewUrl = selectedId !== NONE_ID ? previewUrls[selectedId] : undefined;
async function downloadSelected() {
setDownloading(true);
try {
if (selectedId === NONE_ID) {
const blob = await fetchAssocQrcodeImage();
if (isWechatEnv()) {
const url = URL.createObjectURL(blob);
urlsRef.current.push(url);
setQrcodeUrl(url);
toastSuccess('请长按上方图片保存到相册');
return;
}
downloadBlob(blob, `partner-assoc-${partnerId || 'qr'}.png`);
toastSuccess('已开始下载');
return;
}
if (!selected) return;
let blob = blobsRef.current.get(selected.id);
if (!blob) {
blob = await fetchActivityPosterImage(selected.id);
blobsRef.current.set(selected.id, blob);
}
if (isWechatEnv()) {
let url = previewUrls[selected.id];
if (!url) {
url = URL.createObjectURL(blob);
urlsRef.current.push(url);
setPreviewUrls((prev) => ({ ...prev, [selected.id]: url }));
}
toastSuccess('请长按上方图片保存到相册');
return;
}
downloadBlob(blob, `activity-poster-${selected.id}.png`);
toastSuccess('已开始下载');
} catch (e) {
toastError(e instanceof Error ? e.message : '下载失败');
} finally {
setDownloading(false);
}
}
async function selectPoster(id: string) {
const prev = selectedId;
setSelectedId(id);
try {
await saveActivityPosterSelection(id === NONE_ID ? null : id);
} catch (e) {
setSelectedId(prev);
toastError(e instanceof Error ? e.message : '保存失败');
}
}
function renderRadioRow(id: string, label: string) {
return (
<label className="partner-activity-radio-row">
<span className="headline-md">{label}</span>
<input
type="radio"
name="activity-poster"
checked={selectedId === id}
onChange={() => void selectPoster(id)}
/>
</label>
);
}
if (listLoading) {
return <div className="empty"></div>;
}
return (
<div className="partner-activity-picker">
<section className="partner-bill-card" style={{ overflow: 'hidden' }}>
{renderRadioRow(NONE_ID, '无')}
{selectedId === NONE_ID && (
<div className="partner-activity-panel">
{qrcodeUrl ? (
<div className="partner-activity-preview partner-activity-preview--qr">
<img src={qrcodeUrl} alt="关联码" />
</div>
) : (
<p className="body-md text-muted" style={{ marginBottom: 12 }}></p>
)}
<button
type="button"
className="partner-btn-primary"
disabled={downloading || !qrcodeUrl}
onClick={() => void downloadSelected()}
>
{downloading ? '下载中…' : '下载二维码'}
</button>
{isWechatEnv() && (
<p className="label-md text-muted" style={{ marginTop: 12 }}>
</p>
)}
</div>
)}
</section>
{items.map((item) => (
<section key={item.id} className="partner-bill-card" style={{ marginTop: 12, overflow: 'hidden' }}>
{renderRadioRow(item.id, item.title)}
{selectedId === item.id && (
<div className="partner-activity-panel">
<div className="partner-activity-preview">
<img src={previewUrl || item.imageUrl} alt={item.title} />
{previewLoading && !previewUrl && (
<div className="partner-activity-preview-mask"></div>
)}
</div>
{item.copyText ? (
<p className="body-md" style={{ whiteSpace: 'pre-wrap', margin: '12px 0' }}>{item.copyText}</p>
) : (
<p className="body-md text-muted" style={{ margin: '12px 0' }}>广</p>
)}
<div style={{ display: 'flex', gap: 12 }}>
<button
type="button"
className="partner-btn-outline"
onClick={() => {
void copyActivityCopy(item.copyText)
.then(() => toastSuccess('文案已复制'))
.catch((e) => toastError(e instanceof Error ? e.message : '复制失败'));
}}
>
</button>
<button
type="button"
className="partner-btn-primary"
style={{ flex: 1, width: 'auto', padding: 0, height: 48 }}
disabled={downloading || previewLoading}
onClick={() => void downloadSelected()}
>
{downloading || previewLoading ? '生成中…' : '下载活动图'}
</button>
</div>
{previewUrl && isWechatEnv() && (
<p className="label-md text-muted" style={{ marginTop: 12 }}>
</p>
)}
</div>
)}
</section>
))}
</div>
);
}
@@ -3,6 +3,7 @@ import { isLoggedIn } from '../lib/api';
const TABS = [ const TABS = [
{ to: '/', end: true, icon: 'dashboard', label: '首页' }, { to: '/', end: true, icon: 'dashboard', label: '首页' },
{ to: '/users', icon: 'group', label: '用户管理' },
{ to: '/stores', icon: 'store', label: '门店管理' }, { to: '/stores', icon: 'store', label: '门店管理' },
{ to: '/center', icon: 'account_circle', label: '合伙人中心' }, { to: '/center', icon: 'account_circle', label: '合伙人中心' },
] as const; ] as const;
@@ -0,0 +1,74 @@
import type { ActivityPosterItem, ActivityPosterSelection } from '@dukang/shared-types';
import { request } from './api';
export async function listActivityPosters() {
const data = await request<ActivityPosterItem[]>('PARTNER_H5', '/partner/activity-posters', {
silent: true,
});
return Array.isArray(data) ? data : [];
}
export async function fetchAssocQrcodeImage(): Promise<Blob> {
const token = localStorage.getItem('accessToken');
const res = await fetch('/api/v1/partner/assoc/qrcode', {
headers: {
Authorization: token ? `Bearer ${token}` : '',
'X-Client-App': 'PARTNER_H5',
},
});
if (!res.ok) throw new Error('下载二维码失败');
return res.blob();
}
export async function fetchActivityPosterImage(id: string): Promise<Blob> {
const token = localStorage.getItem('accessToken');
const res = await fetch(`/api/v1/partner/activity-posters/${id}/image`, {
headers: {
Authorization: token ? `Bearer ${token}` : '',
'X-Client-App': 'PARTNER_H5',
},
});
if (!res.ok) {
const json = await res.json().catch(() => null) as { message?: string } | null;
throw new Error(json?.message || '生成活动图失败');
}
return res.blob();
}
export function downloadBlob(blob: Blob, fileName: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}
export async function getActivityPosterSelection() {
return request<ActivityPosterSelection>('PARTNER_H5', '/partner/activity-posters/selection', {
silent: true,
});
}
export async function saveActivityPosterSelection(posterId: string | null) {
return request<ActivityPosterSelection>('PARTNER_H5', '/partner/activity-posters/selection', {
method: 'PUT',
body: JSON.stringify({ posterId }),
silent: true,
});
}
export async function copyActivityCopy(text: string) {
const value = text.trim();
if (!value) throw new Error('暂无文案');
try {
await navigator.clipboard.writeText(value);
} catch {
const ta = document.createElement('textarea');
ta.value = value;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
}
@@ -12,6 +12,7 @@ export type ProxyOrderDraft = {
promoCodeId: string; promoCodeId: string;
deliveryMode: PartnerProxyDeliveryMode; deliveryMode: PartnerProxyDeliveryMode;
autoReceive: boolean; autoReceive: boolean;
assocEnabled: boolean;
}; };
export function saveProxyOrderDraft(draft: ProxyOrderDraft) { export function saveProxyOrderDraft(draft: ProxyOrderDraft) {
@@ -40,6 +41,7 @@ export function loadProxyOrderDraft(): ProxyOrderDraft | null {
promoCodeId: typeof parsed.promoCodeId === 'string' ? parsed.promoCodeId : '', promoCodeId: typeof parsed.promoCodeId === 'string' ? parsed.promoCodeId : '',
deliveryMode: parsed.deliveryMode === 'ON_SITE_PICKUP' ? 'ON_SITE_PICKUP' : 'ADDRESS', deliveryMode: parsed.deliveryMode === 'ON_SITE_PICKUP' ? 'ON_SITE_PICKUP' : 'ADDRESS',
autoReceive: parsed.autoReceive === true, autoReceive: parsed.autoReceive === true,
assocEnabled: parsed.assocEnabled !== false,
}; };
} catch { } catch {
return null; return null;
@@ -0,0 +1,25 @@
import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import ActivityPosterPicker from '../components/ActivityPosterPicker';
import { usePartnerPageView } from '../lib/usePageView';
export default function ActivityPostersPage() {
usePartnerPageView('partner_activity_posters_view');
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const initialId = searchParams.get('id');
useEffect(() => {
document.title = '活动图';
}, []);
return (
<div>
<PageHeader title="活动图" onBack={() => navigate(-1)} />
<div style={{ padding: 16 }}>
<ActivityPosterPicker initialId={initialId} />
</div>
</div>
);
}
@@ -0,0 +1,68 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import type { PartnerAssocUserOrderItem } from '@dukang/shared-types';
import { request } from '../lib/api';
import { toastError } from '../lib/toast';
import { usePartnerPageView } from '../lib/usePageView';
type ListRes = { items: PartnerAssocUserOrderItem[]; total: number };
function fmtMoney(n: number) {
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
export default function AssocOrdersPage() {
const { userId } = useParams();
usePartnerPageView(userId ? 'partner_assoc_user_orders_view' : 'partner_assoc_orders_view');
const navigate = useNavigate();
const [items, setItems] = useState<PartnerAssocUserOrderItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setLoading(true);
try {
const path = userId
? `/partner/assoc/users/${userId}/orders?page=1&pageSize=50`
: '/partner/assoc/orders?page=1&pageSize=50';
const res = await request<ListRes>('PARTNER_H5', path);
setItems(res.items ?? []);
setTotal(res.total ?? 0);
} catch (e) {
toastError(e instanceof Error ? e.message : '加载失败');
setItems([]);
} finally {
setLoading(false);
}
}, [userId]);
useEffect(() => {
void load();
}, [load]);
return (
<PullToRefresh onRefresh={load}>
<PageHeader title={userId ? '用户订单' : '关联用户订单'} onBack={() => navigate(-1)} />
<div style={{ padding: '0 20px 24px' }}>
<p className="label-md text-muted" style={{ margin: '12px 0' }}>
{loading ? '加载中…' : `${total} 笔已付购酒单`}
</p>
{!loading && items.length === 0 && <div className="empty"></div>}
{items.map((o) => (
<div key={o.id} className="partner-store-card" style={{ marginBottom: 12 }}>
<div className="partner-store-card-header" style={{ marginBottom: 0 }}>
<div>
<p className="body-md">{o.productName}</p>
<p className="label-md text-muted">{o.orderNo} · ×{o.quantity}</p>
<p className="label-md text-muted">{o.paidAt ? o.paidAt.slice(0, 16).replace('T', ' ') : ''}</p>
</div>
<span className="amount-lg" style={{ fontSize: 18 }}>¥{fmtMoney(o.payAmount)}</span>
</div>
</div>
))}
</div>
</PullToRefresh>
);
}
@@ -0,0 +1,96 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import type { PartnerAssocSummary } from '@dukang/shared-types';
import { request } from '../lib/api';
import { toastError, toastSuccess } from '../lib/toast';
import { isWechatEnv } from '../lib/weixin';
import { usePartnerPageView } from '../lib/usePageView';
export default function AssocQrcodePage() {
usePartnerPageView('partner_assoc_qrcode_view');
const navigate = useNavigate();
const [summary, setSummary] = useState<PartnerAssocSummary | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
request<PartnerAssocSummary>('PARTNER_H5', '/partner/assoc')
.then(setSummary)
.catch((e) => toastError(e instanceof Error ? e.message : '加载失败'))
.finally(() => setLoading(false));
}, []);
useEffect(() => () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
}, [previewUrl]);
async function downloadQr() {
const token = localStorage.getItem('accessToken');
try {
const res = await fetch('/api/v1/partner/assoc/qrcode', {
headers: {
Authorization: token ? `Bearer ${token}` : '',
'X-Client-App': 'PARTNER_H5',
},
});
if (!res.ok) throw new Error('下载失败');
const blob = await res.blob();
const url = URL.createObjectURL(blob);
if (isWechatEnv()) {
setPreviewUrl(url);
toastSuccess('请长按图片保存到相册');
return;
}
const a = document.createElement('a');
a.href = url;
a.download = `partner-assoc-${summary?.partnerId || 'qr'}.png`;
a.click();
URL.revokeObjectURL(url);
toastSuccess('已开始下载');
} catch (e) {
if (summary?.qrcodeUrl) {
setPreviewUrl(summary.qrcodeUrl);
toastSuccess('请长按图片保存到相册');
return;
}
toastError(e instanceof Error ? e.message : '下载失败');
}
}
return (
<div>
<PageHeader title="关联码" onBack={() => navigate(-1)} />
{loading && <div className="empty"></div>}
{!loading && (
<section className="partner-bill-card" style={{ margin: 16 }}>
<div style={{ padding: 24, textAlign: 'center' }}>
<p className="body-md text-muted" style={{ marginBottom: 16 }}>
</p>
{summary?.qrcodeUrl ? (
<img
src={previewUrl || summary.qrcodeUrl}
alt="关联码"
style={{ width: 220, height: 220, background: '#fff' }}
/>
) : (
<p className="body-md text-muted"></p>
)}
<p className="label-md text-muted" style={{ marginTop: 12 }}>
{summary?.userCount ?? 0}
</p>
<button type="button" className="partner-btn-primary" style={{ marginTop: 20 }} onClick={() => void downloadQr()}>
</button>
{previewUrl && isWechatEnv() && (
<p className="label-md text-muted" style={{ marginTop: 12 }}>
</p>
)}
</div>
</section>
)}
</div>
);
}
@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import type { PartnerAssocUserItem } from '@dukang/shared-types';
import { request } from '../lib/api';
import { toastError } from '../lib/toast';
import { usePartnerPageView } from '../lib/usePageView';
type ListRes = { items: PartnerAssocUserItem[]; total: number; page: number; pageSize: number };
export default function AssocUsersPage() {
usePartnerPageView('partner_assoc_users_view');
const navigate = useNavigate();
const [items, setItems] = useState<PartnerAssocUserItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
async function load() {
setLoading(true);
try {
const res = await request<ListRes>('PARTNER_H5', '/partner/assoc/users?page=1&pageSize=50');
setItems(res.items ?? []);
setTotal(res.total ?? 0);
} catch (e) {
toastError(e instanceof Error ? e.message : '加载失败');
setItems([]);
} finally {
setLoading(false);
}
}
useEffect(() => {
void load();
}, []);
return (
<PullToRefresh onRefresh={load}>
<PageHeader title="关联用户" onBack={() => navigate(-1)} />
<div style={{ padding: '0 20px 24px' }}>
<p className="label-md text-muted" style={{ margin: '12px 0' }}>
{loading ? '加载中…' : `${total}`}
</p>
{!loading && items.length === 0 && <div className="empty"></div>}
{items.map((u) => (
<div key={u.id} className="partner-store-card" style={{ marginBottom: 12 }}>
<div className="partner-store-card-header" style={{ marginBottom: 0 }}>
<div>
<p className="body-md">{u.nickname || u.userNo}</p>
<p className="label-md text-muted">{u.phone || '未绑定手机'}</p>
<p className="label-md text-muted">{u.boundAt ? u.boundAt.slice(0, 16).replace('T', ' ') : ''}</p>
</div>
<span className="label-md">{u.orderCount} </span>
</div>
</div>
))}
</div>
</PullToRefresh>
);
}
+42 -11
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader'; import PageHeader from '@dukang/shared-ui/PageHeader';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh'; import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import type { PartnerBillDto } from '@dukang/shared-types'; import type { PartnerBillDetailDto, PartnerBillDto, PartnerBillItemDto } from '@dukang/shared-types';
import { isLoggedIn, request } from '../lib/api'; import { isLoggedIn, request } from '../lib/api';
import { toastError, toastSuccess } from '../lib/toast'; import { toastError, toastSuccess } from '../lib/toast';
import { usePartnerPageView } from '../lib/usePageView'; import { usePartnerPageView } from '../lib/usePageView';
@@ -34,6 +34,7 @@ export default function BillsPage() {
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [selectedIds, setSelectedIds] = useState<string[]>([]); const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [detail, setDetail] = useState<PartnerBillDetailDto | null>(null);
async function loadBills() { async function loadBills() {
setLoading(true); setLoading(true);
@@ -67,6 +68,44 @@ export default function BillsPage() {
const isRejected = status === 'REJECTED'; const isRejected = status === 'REJECTED';
const isPaid = status === 'PAID'; const isPaid = status === 'PAID';
useEffect(() => {
if (!bill?.id) {
setDetail(null);
return;
}
request<PartnerBillDetailDto>('PARTNER_H5', `/partner/settlement/bills/${bill.id}`)
.then(setDetail)
.catch(() => setDetail(null));
}, [bill?.id]);
function renderItemList(title: string, items: PartnerBillItemDto[] | undefined, subtotal: number) {
const list = items ?? [];
return (
<div style={{ marginTop: 16 }}>
<div className="partner-info-row" style={{ marginBottom: 8 }}>
<span className="body-md" style={{ fontWeight: 700 }}>{title}</span>
<span className="body-md" style={{ fontWeight: 700 }}>¥ {fmtMoney(subtotal)}</span>
</div>
{list.length === 0 ? (
<p className="label-md text-muted"></p>
) : (
list.map((it) => (
<div key={it.id} className="partner-info-row" style={{ alignItems: 'flex-start' }}>
<div>
<p className="body-md">{it.title || it.refNo}</p>
<p className="label-md text-muted">
{it.refNo}
{it.extra ? ` ${it.extra}` : ''} · {((it.rate ?? 0) * 100).toFixed(2)}%
</p>
</div>
<span className="body-md">¥ {fmtMoney(it.commission)}</span>
</div>
))
)}
</div>
);
}
function askConfirm(ids: string[]) { function askConfirm(ids: string[]) {
if (!window.confirm(`确认 ${ids.length} 笔账单无误并提交?确认后状态将变为「未打款」,等待总部打款。`)) { if (!window.confirm(`确认 ${ids.length} 笔账单无误并提交?确认后状态将变为「未打款」,等待总部打款。`)) {
return; return;
@@ -183,16 +222,8 @@ export default function BillsPage() {
</div> </div>
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> {renderItemList('酒订单', detail?.orderItems, Number(detail?.orderCommission ?? bill.orderCommission ?? 0))}
<div className="partner-info-row"> {renderItemList('核销订单', detail?.redeemItems, Number(detail?.redeemCommission ?? bill.redeemCommission ?? 0))}
<span className="text-variant body-md"></span>
<span className="body-md" style={{ fontWeight: 700 }}>¥ {fmtMoney(Number(bill.orderCommission || 0))}</span>
</div>
<div className="partner-info-row">
<span className="text-variant body-md"></span>
<span className="body-md" style={{ fontWeight: 700 }}>¥ {fmtMoney(Number(bill.redeemCommission || 0))}</span>
</div>
</div>
</div> </div>
</section> </section>
)} )}
+27
View File
@@ -219,6 +219,33 @@ export default function CenterPage({ variant = 'primary', roleLabel }: CenterPag
<span className="material-symbols-outlined text-muted">chevron_right</span> <span className="material-symbols-outlined text-muted">chevron_right</span>
</div> </div>
</Link> </Link>
<Link to="/center/activity-posters" className="partner-menu-item">
<div className="partner-menu-item-left">
<div className="partner-menu-icon">
<span className="material-symbols-outlined">image</span>
</div>
<span className="body-md" style={{ fontSize: 16 }}></span>
</div>
<span className="material-symbols-outlined text-muted">chevron_right</span>
</Link>
<Link to="/users" className="partner-menu-item">
<div className="partner-menu-item-left">
<div className="partner-menu-icon">
<span className="material-symbols-outlined">group</span>
</div>
<span className="body-md" style={{ fontSize: 16 }}></span>
</div>
<span className="material-symbols-outlined text-muted">chevron_right</span>
</Link>
<Link to="/center/commissions" className="partner-menu-item">
<div className="partner-menu-item-left">
<div className="partner-menu-icon">
<span className="material-symbols-outlined">payments</span>
</div>
<span className="body-md" style={{ fontSize: 16 }}></span>
</div>
<span className="material-symbols-outlined text-muted">chevron_right</span>
</Link>
<Link to="/center/proxy-orders" className="partner-menu-item"> <Link to="/center/proxy-orders" className="partner-menu-item">
<div className="partner-menu-item-left"> <div className="partner-menu-item-left">
<div className="partner-menu-icon"> <div className="partner-menu-icon">
@@ -0,0 +1,67 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import type { PartnerCommissionOrderItem } from '@dukang/shared-types';
import { request } from '../lib/api';
import { toastError } from '../lib/toast';
import { usePartnerPageView } from '../lib/usePageView';
function fmtMoney(n: number) {
return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
type ListRes = { items: PartnerCommissionOrderItem[]; total: number };
export default function CommissionOrdersPage() {
usePartnerPageView('partner_commission_orders_view');
const navigate = useNavigate();
const [items, setItems] = useState<PartnerCommissionOrderItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
async function load() {
setLoading(true);
try {
const res = await request<ListRes>('PARTNER_H5', '/partner/commissions/orders?page=1&pageSize=50');
setItems(res.items ?? []);
setTotal(res.total ?? 0);
} catch (e) {
toastError(e instanceof Error ? e.message : '加载失败');
setItems([]);
} finally {
setLoading(false);
}
}
useEffect(() => {
void load();
}, []);
return (
<PullToRefresh onRefresh={load}>
<PageHeader title="订单佣金" onBack={() => navigate(-1)} />
<div style={{ padding: '0 20px 24px' }}>
<p className="label-md text-muted" style={{ margin: '12px 0' }}>
{loading ? '加载中…' : `${total} 笔关联酒单`}
</p>
{!loading && items.length === 0 && <div className="empty"></div>}
{items.map((o) => (
<div key={o.id} className="partner-store-card" style={{ marginBottom: 12 }}>
<div className="partner-store-card-header">
<div>
<p className="body-md">{o.productName}</p>
<p className="label-md text-muted">{o.orderNo} · ×{o.quantity}</p>
<p className="label-md text-muted">{o.paidAt ? o.paidAt.slice(0, 16).replace('T', ' ') : ''}</p>
</div>
<span className="amount-lg" style={{ fontSize: 18 }}>¥{fmtMoney(o.commission)}</span>
</div>
<p className="label-md text-muted">
¥{fmtMoney(o.payAmount)} × {((o.rate ?? 0) * 100).toFixed(2)}%
</p>
</div>
))}
</div>
</PullToRefresh>
);
}
+58 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import type { PartnerLeaderboardEntry } from '@dukang/shared-types'; import type { PartnerAssocStats, PartnerLeaderboardEntry } from '@dukang/shared-types';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh'; import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import { usePartnerPageView } from '../lib/usePageView'; import { usePartnerPageView } from '../lib/usePageView';
import { isLoggedIn, request } from '../lib/api'; import { isLoggedIn, request } from '../lib/api';
@@ -153,6 +153,7 @@ export default function HomePage() {
const [stores, setStores] = useState<Array<Record<string, unknown>>>([]); const [stores, setStores] = useState<Array<Record<string, unknown>>>([]);
const [orders, setOrders] = useState<Array<Record<string, unknown>>>([]); const [orders, setOrders] = useState<Array<Record<string, unknown>>>([]);
const [leaderboardEntries, setLeaderboardEntries] = useState<PartnerLeaderboardEntry[]>([]); const [leaderboardEntries, setLeaderboardEntries] = useState<PartnerLeaderboardEntry[]>([]);
const [assocStats, setAssocStats] = useState<PartnerAssocStats | null>(null);
useEffect(() => { useEffect(() => {
document.title = '工作台'; document.title = '工作台';
@@ -197,6 +198,16 @@ export default function HomePage() {
setStores([]); setStores([]);
} }
if (isPrimary) {
tasks.push(
request<PartnerAssocStats>('PARTNER_H5', '/partner/assoc/stats', { silent: true })
.then(setAssocStats)
.catch(() => setAssocStats(null)),
);
} else {
setAssocStats(null);
}
tasks.push( tasks.push(
fetchPartnerLeaderboard('month') fetchPartnerLeaderboard('month')
.then((data) => { .then((data) => {
@@ -208,7 +219,7 @@ export default function HomePage() {
); );
return Promise.all(tasks).then(() => undefined); return Promise.all(tasks).then(() => undefined);
}, [navigate, account, canOrders, canDashboard, canStores]); }, [navigate, account, canOrders, canDashboard, canStores, isPrimary]);
useEffect(() => { useEffect(() => {
void loadHome(); void loadHome();
@@ -287,6 +298,51 @@ export default function HomePage() {
</> </>
)} )}
{isPrimary && (
<>
<Link to="/users" className="partner-bento-card" style={{ display: 'block', marginBottom: 16, color: 'inherit', textDecoration: 'none' }}>
<div className="partner-bento-header">
<h2 className="headline-md"></h2>
<span className="amount-lg" style={{ fontSize: 24 }}>{assocStats?.userTotal ?? 0}</span>
</div>
<div className="partner-store-stats">
<div className="partner-store-stat">
<div>
<p className="label-md text-muted"></p>
<p className="headline-md">{assocStats?.userToday ?? 0}</p>
</div>
</div>
<div className="partner-store-stat">
<div>
<p className="label-md text-muted"></p>
<p className="headline-md">{assocStats?.userMonth ?? 0}</p>
</div>
</div>
</div>
</Link>
<Link to="/users/orders" className="partner-bento-card" style={{ display: 'block', marginBottom: 16, color: 'inherit', textDecoration: 'none' }}>
<div className="partner-bento-header">
<h2 className="headline-md"></h2>
<span className="amount-lg" style={{ fontSize: 24 }}>{assocStats?.orderTotal ?? 0}</span>
</div>
<div className="partner-store-stats">
<div className="partner-store-stat">
<div>
<p className="label-md text-muted"></p>
<p className="headline-md">{assocStats?.orderToday ?? 0}</p>
</div>
</div>
<div className="partner-store-stat">
<div>
<p className="label-md text-muted"></p>
<p className="headline-md">{assocStats?.orderMonth ?? 0}</p>
</div>
</div>
</div>
</Link>
</>
)}
{isWarehouse && ( {isWarehouse && (
<p className="headline-md" style={{ marginBottom: 8 }}></p> <p className="headline-md" style={{ marginBottom: 8 }}></p>
)} )}

Some files were not shown because too many files have changed in this diff Show More