38 Commits

Author SHA1 Message Date
Eamon
2377616a07 发布v1.4.0版本 2026-04-18 18:15:03 +08:00
Eamon
9cb7d597cd 添加网关列表权限 2026-04-18 17:58:40 +08:00
Eamon
e5586f06d1 添加网关列表页面 & 添加单价不能低于最低价格校验 2026-04-18 17:41:27 +08:00
Eamon
13be8f3270 搜索框加空格校验 & 发布v1.3.0版本 2026-04-16 14:28:03 +08:00
c850831915 修复套餐编码顺序问题 2026-04-16 10:43:48 +08:00
aa0ab93ba9 修复创建套餐编码格式问题 & 其他样式问题 2026-04-16 10:43:48 +08:00
Eamon
f7de0fa535 发布v1.2.0版本 2026-04-13 11:53:28 +08:00
Eamon
ea8015924e 操作页面跳转添加返回上一级功能 2026-04-11 17:35:40 +08:00
04426ba36d 表格与页面样式调整 2026-04-11 17:12:16 +08:00
Eamon
4307efae98 更新操作按钮为菜单栏 & 调整页面表格顺序 2026-04-11 17:07:03 +08:00
Eamon
ed95f0520d 新增余额明细页面,修复页面useId不更新的问题 2026-04-11 14:57:45 +08:00
Eamon
790180a847 客户查询添加操作功能 2026-04-09 17:08:59 +08:00
Eamon
cc7e26561d 管理员页面操作列添加权限控制 2026-04-08 16:48:16 +08:00
Eamon
8fcf54ae10 添加客户查询页面包括导航权限控制 & 删除多余代码 2026-04-08 16:48:16 +08:00
Eamon
ff645aaaca 修改客户认领和客户管理页面的查询和操作功能并且包含按钮权限 & 产品管理添加启动/禁用和最低价格字段 2026-04-08 16:48:15 +08:00
f6ae0a9463 开发环境新增权限复制功能 2026-04-08 16:47:05 +08:00
30af977543 套餐编码可视化改造 2026-04-08 15:41:32 +08:00
0789462a8d 表格增加序号列,移除 id 列 2026-04-07 17:06:19 +08:00
edc87c6eea 修复构建问题 2026-04-02 14:46:26 +08:00
Eamon
5d9d3c844e 优化组件页面代码 2026-04-02 13:13:59 +08:00
Eamon
545435d095 更新navigation里的权限控制 & 更新客户认领查询逻辑 2026-04-01 13:46:23 +08:00
Eamon
be03cf6440 客户管理添加修改金额操作 2026-04-01 13:46:22 +08:00
Eamon
7479b83f13 产品管理价格做保留2位小数 & 账单详情列添加充值消费提示 2026-04-01 13:46:22 +08:00
Eamon
3387056ea9 更新客户管理的修改功能参数 2026-04-01 13:46:22 +08:00
Eamon
8c26d81846 固定表格操作列 2026-04-01 13:46:22 +08:00
Eamon
f72b6bddd0 更新客户管理模块 2026-04-01 13:46:22 +08:00
Eamon
76d2d480ed 添加优惠券功能 & 更新折扣管理的接口 2026-04-01 13:46:21 +08:00
Eamon
453d687c4a 添加表单查询和调整表格字段以及功能 2026-04-01 13:46:21 +08:00
a9e9ddd04b 修复鉴权失败后跳转的问题 2026-04-01 13:16:56 +08:00
61b766d939 完善权限获取机制 2026-03-31 11:59:00 +08:00
12b60e74df 实现权限列表与权限渲染组件 2026-03-31 10:56:01 +08:00
2c7970796f 完善权限树的展示与选择 2026-03-28 17:17:04 +08:00
1e6b307586 表格组件添加固定到边缘功能 2026-03-27 18:02:38 +08:00
523d46874b 实现价格折扣动态调整 2026-03-25 11:43:21 +08:00
8751ac19a6 实现基本产品查询与页面展示 2026-03-23 17:49:47 +08:00
c4e1da8912 实现权限管理页面与功能 2026-03-19 12:02:48 +08:00
Eamon
efe1568ab5 调整README.md文件显示格式 2026-03-05 10:14:13 +08:00
Eamon
8307b913ca 更新README.md文档 & 添加构建脚本文件 2026-03-03 17:15:29 +08:00
118 changed files with 13103 additions and 1801 deletions

View File

@@ -5,18 +5,18 @@
"formatter": { "language_server": { "name": "biome" } },
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true,
},
"source.organizeImports.biome": true
}
},
"TSX": {
"formatter": { "language_server": { "name": "biome" } },
"code_actions_on_format": {
"source.fixAll.biome": true,
"source.organizeImports.biome": true,
},
"source.organizeImports.biome": true
}
},
"JSON": {
"formatter": { "language_server": { "name": "biome" } },
},
},
"formatter": { "language_server": { "name": "biome" } }
}
}
}

View File

@@ -7,3 +7,65 @@
页面表格内单元样式细化
仪表盘填充真实数据
## 目录结构
```
public/ # 静态资源(图片、字体等)
src/
├── actions/ # 服务端 Action表单提交、数据操作等
├── app/ # App Router 核心目录
│ ├── (root)/ # 根路由组(无路径前缀)
│ ├── login/ # /login 路由页面
│ ├── favicon.ico # 网站图标
│ ├── globals.css # 全局样式
│ └── layout.tsx # 根布局组件
├── components/ # 可复用 UI 组件
├── hooks/ # 自定义 React Hooks
├── lib/ # 工具函数、第三方库封装
├── models/ # 数据模型、类型定义、Schema
└── proxy.ts # 代理配置API 转发等)
.env # 环境变量(本地开发)
.env.example # 环境变量示例模板
.gitignore # Git 忽略文件
.npmrc # npm 配置
biome.json # Biome 代码格式化/检查配置
bun.lock # Bun 包管理器锁文件
components.json # shadcn/ui 组件库配置
Dockerfile # Docker 容器化配置
next-env.d.ts # Next.js 类型声明
next.config.ts # Next.js 配置文件
package.json # 项目依赖与脚本
postcss.config.mjs # PostCSS 配置
README.md # 项目说明文档
tsconfig.json # TypeScript 配置
```
## 搭建开发环境
1. 下载本地项目:`git clone https://43.226.58.254:53000/lanhu/admin`
2. 安装依赖包:`bun install`
3. 创建环境变量文件 .env复制 .env.example 中的内容到 .env并根据实际情况修改
4. 启动项目终端运行 `bun run dev`
## 构建项目 & 版本管理
1. 在 package.json 文件中修改版本号
2. 构建并上传镜像, 终端运行 `./publish.ps1 <版本号>`
3. 终端执行成功后在 `https://43.226.58.254:53000/lanhu/admin` 发布最新版本
## 技术栈
| 类别 | 场景/库名 | 推荐方案/用途 |
| :--- | :--- | :--- |
| **核心框架** | Next.js | 服务框架 (React 全栈框架) |
| **UI / 样式体系** | Radix UI | 无样式基础 UI 组件原语 |
| | Tailwind CSS | CSS 框架 (原子化 CSS) |
| | lucide-react | 图标库 |
| **表单与数据验证** | React Hook Form | 表单状态管理及验证 |
| | Zod | 数据验证与类型推断 |
| **数据管理与通信** | Zustand | 全局状态管理库 |
| | TanStack Query | 服务端状态管理 (数据请求、缓存) |
| | TanStack Table | 无头 UI 表格库 |
| **工具库** | date-fns | 日期时间处理库 |
生产环境的项目部署通过单独的部署脚本进行管理,前端开发上线只需要构建以及发布版本,无需考虑部署问题。

View File

@@ -18,6 +18,15 @@
"recommended": true,
"style": {
"useNodejsImportProtocol": "off"
},
"a11y": {
"useButtonType": "off",
"noLabelWithoutControl": "off",
"noSvgWithoutTitle": "off",
"useSemanticElements": "off"
},
"suspicious": {
"noArrayIndexKey": "off"
}
}
},

View File

@@ -18,9 +18,11 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"jotai": "^2.19.0",
"lucide-react": "^0.562.0",
"next": "^16.0.10",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "^19.2.1",
"react-dom": "^19.2.1",
"react-hook-form": "^7.68.0",
@@ -164,28 +166,62 @@
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "https://registry.npmmirror.com/@radix-ui/primitive/-/primitive-1.1.3.tgz", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
"@radix-ui/react-accessible-icon": ["@radix-ui/react-accessible-icon@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-accessible-icon/-/react-accessible-icon-1.1.7.tgz", { "dependencies": { "@radix-ui/react-visually-hidden": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XM+E4WXl0OqUJFovy6GjmxxFyx9opfCAIUku4dlKRd5YEPqt4kALOkQOp0Of6reHuUkJuiPBEc5k0o4z4lTC8A=="],
"@radix-ui/react-accordion": ["@radix-ui/react-accordion@1.2.12", "https://registry.npmmirror.com/@radix-ui/react-accordion/-/react-accordion-1.2.12.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collapsible": "1.1.12", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA=="],
"@radix-ui/react-alert-dialog": ["@radix-ui/react-alert-dialog@1.1.15", "https://registry.npmmirror.com/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.15.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dialog": "1.1.15", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw=="],
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
"@radix-ui/react-aspect-ratio": ["@radix-ui/react-aspect-ratio@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Yq6lvO9HQyPwev1onK1daHCHqXVLzPhSVjmsNjCa2Zcxy2f7uJD2itDtxknv6FzAKCwD1qQkeVDmX/cev13n/g=="],
"@radix-ui/react-avatar": ["@radix-ui/react-avatar@1.1.10", "https://registry.npmmirror.com/@radix-ui/react-avatar/-/react-avatar-1.1.10.tgz", { "dependencies": { "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-is-hydrated": "0.1.0", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-V8piFfWapM5OmNCXTzVQY+E1rDa53zY+MQ4Y7356v4fFz6vqCyUtIz2rUD44ZEdwg78/jKmMJHj07+C/Z/rcog=="],
"@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.3.3", "https://registry.npmmirror.com/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw=="],
"@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.12", "https://registry.npmmirror.com/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA=="],
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-collection/-/react-collection-1.1.7.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "https://registry.npmmirror.com/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "https://registry.npmmirror.com/@radix-ui/react-context/-/react-context-1.1.2.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
"@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.2.16", "https://registry.npmmirror.com/@radix-ui/react-context-menu/-/react-context-menu-2.2.16.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww=="],
"@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.15", "https://registry.npmmirror.com/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw=="],
"@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-direction/-/react-direction-1.1.1.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw=="],
"@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-dismissable-layer/-/react-dismissable-layer-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="],
"@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.16", "https://registry.npmmirror.com/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.16.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw=="],
"@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "https://registry.npmmirror.com/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="],
"@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-focus-scope/-/react-focus-scope-1.1.7.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="],
"@radix-ui/react-form": ["@radix-ui/react-form@0.1.8", "https://registry.npmmirror.com/@radix-ui/react-form/-/react-form-0.1.8.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-label": "2.1.7", "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QM70k4Zwjttifr5a4sZFts9fn8FzHYvQ5PiB19O2HsYibaHSVt9fH9rzB0XZo/YcM+b7t/p7lYCT/F5eOeF5yQ=="],
"@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.15", "https://registry.npmmirror.com/@radix-ui/react-hover-card/-/react-hover-card-1.1.15.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg=="],
"@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-id/-/react-id-1.1.1.tgz", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="],
"@radix-ui/react-label": ["@radix-ui/react-label@2.1.8", "https://registry.npmmirror.com/@radix-ui/react-label/-/react-label-2.1.8.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-FmXs37I6hSBVDlO4y764TNz1rLgKwjJMQ0EGte6F3Cb3f4bIuHB/iLa/8I9VKkmOy+gNHq8rql3j686ACVV21A=="],
"@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.16", "https://registry.npmmirror.com/@radix-ui/react-menu/-/react-menu-2.1.16.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg=="],
"@radix-ui/react-menubar": ["@radix-ui/react-menubar@1.1.16", "https://registry.npmmirror.com/@radix-ui/react-menubar/-/react-menubar-1.1.16.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-EB1FktTz5xRRi2Er974AUQZWg2yVBb1yjip38/lgwtCVRd3a+maUoGHN/xs9Yv8SY8QwbSEb+YrxGadVWbEutA=="],
"@radix-ui/react-navigation-menu": ["@radix-ui/react-navigation-menu@1.2.14", "https://registry.npmmirror.com/@radix-ui/react-navigation-menu/-/react-navigation-menu-1.2.14.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YB9mTFQvCOAQMHU+C/jVl96WmuWeltyUEpRJJky51huhds5W2FQr1J8D/16sQlf0ozxkPK8uF3niQMdUwZPv5w=="],
"@radix-ui/react-one-time-password-field": ["@radix-ui/react-one-time-password-field@0.1.8", "https://registry.npmmirror.com/@radix-ui/react-one-time-password-field/-/react-one-time-password-field-0.1.8.tgz", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-is-hydrated": "0.1.0", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ycS4rbwURavDPVjCb5iS3aG4lURFDILi6sKI/WITUMZ13gMmn/xGjpLoqBAalhJaDk8I3UbCM5GzKHrnzwHbvg=="],
"@radix-ui/react-password-toggle-field": ["@radix-ui/react-password-toggle-field@0.1.3", "https://registry.npmmirror.com/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.1.3.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-is-hydrated": "0.1.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/UuCrDBWravcaMix4TdT+qlNdVwOM1Nck9kWx/vafXsdfj1ChfhOdfi3cy9SGBpWgTXwYCuboT/oYpJy3clqfw=="],
"@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.15", "https://registry.npmmirror.com/@radix-ui/react-popover/-/react-popover-1.1.15.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA=="],
"@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "https://registry.npmmirror.com/@radix-ui/react-popper/-/react-popper-1.2.8.tgz", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="],
"@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "https://registry.npmmirror.com/@radix-ui/react-portal/-/react-portal-1.1.9.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="],
@@ -194,6 +230,10 @@
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "https://registry.npmmirror.com/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
"@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-progress/-/react-progress-1.1.7.tgz", { "dependencies": { "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg=="],
"@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.3.8", "https://registry.npmmirror.com/@radix-ui/react-radio-group/-/react-radio-group-1.3.8.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ=="],
"@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA=="],
"@radix-ui/react-scroll-area": ["@radix-ui/react-scroll-area@1.2.10", "https://registry.npmmirror.com/@radix-ui/react-scroll-area/-/react-scroll-area-1.2.10.tgz", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A=="],
@@ -202,10 +242,22 @@
"@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.8", "https://registry.npmmirror.com/@radix-ui/react-separator/-/react-separator-1.1.8.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g=="],
"@radix-ui/react-slider": ["@radix-ui/react-slider@1.3.6", "https://registry.npmmirror.com/@radix-ui/react-slider/-/react-slider-1.3.6.tgz", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.4", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.4.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA=="],
"@radix-ui/react-switch": ["@radix-ui/react-switch@1.2.6", "https://registry.npmmirror.com/@radix-ui/react-switch/-/react-switch-1.2.6.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ=="],
"@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.1.13", "https://registry.npmmirror.com/@radix-ui/react-tabs/-/react-tabs-1.1.13.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A=="],
"@radix-ui/react-toast": ["@radix-ui/react-toast@1.2.15", "https://registry.npmmirror.com/@radix-ui/react-toast/-/react-toast-1.2.15.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g=="],
"@radix-ui/react-toggle": ["@radix-ui/react-toggle@1.1.10", "https://registry.npmmirror.com/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ=="],
"@radix-ui/react-toggle-group": ["@radix-ui/react-toggle-group@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-toggle": "1.1.10", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q=="],
"@radix-ui/react-toolbar": ["@radix-ui/react-toolbar@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-toolbar/-/react-toolbar-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-separator": "1.1.7", "@radix-ui/react-toggle-group": "1.1.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4ol06/1bLoFu1nwUqzdD4Y5RZ9oDdKeiHIsntug54Hcr1pgaHiPqHFEaXI1IFP/EsOfROQZ8Mig9VTIRza6Tjg=="],
"@radix-ui/react-tooltip": ["@radix-ui/react-tooltip@1.2.8", "https://registry.npmmirror.com/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-visually-hidden": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg=="],
"@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="],
@@ -216,6 +268,8 @@
"@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-use-escape-keydown/-/react-use-escape-keydown-1.1.1.tgz", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="],
"@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.0", "https://registry.npmmirror.com/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.0.tgz", { "dependencies": { "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA=="],
"@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.1", "https://registry.npmmirror.com/@radix-ui/react-use-previous/-/react-use-previous-1.1.1.tgz", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ=="],
@@ -306,6 +360,8 @@
"jiti": ["jiti@2.6.1", "https://registry.npmmirror.com/jiti/-/jiti-2.6.1.tgz", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
"jotai": ["jotai@2.19.0", "https://registry.npmmirror.com/jotai/-/jotai-2.19.0.tgz", { "peerDependencies": { "@babel/core": ">=7.0.0", "@babel/template": ">=7.0.0", "@types/react": ">=17.0.0", "react": ">=17.0.0" }, "optionalPeers": ["@babel/core", "@babel/template", "@types/react", "react"] }, "sha512-r2wwxEXP1F2JteDLZEOPoIpAHhV89paKsN5GWVYndPNMMP/uVZDcC+fNj0A8NjKgaPWzdyO8Vp8YcYKe0uCEqQ=="],
"lightningcss": ["lightningcss@1.30.2", "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.30.2.tgz", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.30.2", "lightningcss-darwin-arm64": "1.30.2", "lightningcss-darwin-x64": "1.30.2", "lightningcss-freebsd-x64": "1.30.2", "lightningcss-linux-arm-gnueabihf": "1.30.2", "lightningcss-linux-arm64-gnu": "1.30.2", "lightningcss-linux-arm64-musl": "1.30.2", "lightningcss-linux-x64-gnu": "1.30.2", "lightningcss-linux-x64-musl": "1.30.2", "lightningcss-win32-arm64-msvc": "1.30.2", "lightningcss-win32-x64-msvc": "1.30.2" } }, "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.30.2", "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.30.2.tgz", { "os": "android", "cpu": "arm64" }, "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A=="],
@@ -344,6 +400,8 @@
"postcss": ["postcss@8.5.3", "https://registry.npmmirror.com/postcss/-/postcss-8.5.3.tgz", { "dependencies": { "nanoid": "3.3.9", "picocolors": "1.1.1", "source-map-js": "1.2.1" } }, "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A=="],
"radix-ui": ["radix-ui@1.4.3", "https://registry.npmmirror.com/radix-ui/-/radix-ui-1.4.3.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-accessible-icon": "1.1.7", "@radix-ui/react-accordion": "1.2.12", "@radix-ui/react-alert-dialog": "1.1.15", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-aspect-ratio": "1.1.7", "@radix-ui/react-avatar": "1.1.10", "@radix-ui/react-checkbox": "1.3.3", "@radix-ui/react-collapsible": "1.1.12", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-context-menu": "2.2.16", "@radix-ui/react-dialog": "1.1.15", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-dropdown-menu": "2.1.16", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-form": "0.1.8", "@radix-ui/react-hover-card": "1.1.15", "@radix-ui/react-label": "2.1.7", "@radix-ui/react-menu": "2.1.16", "@radix-ui/react-menubar": "1.1.16", "@radix-ui/react-navigation-menu": "1.2.14", "@radix-ui/react-one-time-password-field": "0.1.8", "@radix-ui/react-password-toggle-field": "0.1.3", "@radix-ui/react-popover": "1.1.15", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-progress": "1.1.7", "@radix-ui/react-radio-group": "1.3.8", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-scroll-area": "1.2.10", "@radix-ui/react-select": "2.2.6", "@radix-ui/react-separator": "1.1.7", "@radix-ui/react-slider": "1.3.6", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-switch": "1.2.6", "@radix-ui/react-tabs": "1.1.13", "@radix-ui/react-toast": "1.2.15", "@radix-ui/react-toggle": "1.1.10", "@radix-ui/react-toggle-group": "1.1.11", "@radix-ui/react-toolbar": "1.1.11", "@radix-ui/react-tooltip": "1.2.8", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-escape-keydown": "1.1.1", "@radix-ui/react-use-is-hydrated": "0.1.0", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-aWizCQiyeAenIdUbqEpXgRA1ya65P13NKn/W8rWkcN0OPkRDxdBVLWnIEDsS2RpwCK2nobI7oMUSmexzTDyAmA=="],
"react": ["react@19.2.3", "https://registry.npmmirror.com/react/-/react-19.2.3.tgz", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
"react-dom": ["react-dom@19.2.3", "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.3.tgz", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
@@ -388,20 +446,34 @@
"use-sidecar": ["use-sidecar@1.1.3", "https://registry.npmmirror.com/use-sidecar/-/use-sidecar-1.1.3.tgz", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "https://registry.npmmirror.com/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"zod": ["zod@3.25.76", "https://registry.npmmirror.com/zod/-/zod-3.25.76.tgz", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zustand": ["zustand@5.0.9", "https://registry.npmmirror.com/zustand/-/zustand-5.0.9.tgz", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-ALBtUj0AfjJt3uNRQoL1tL2tMvj6Gp/6e39dnfT6uzpelGru8v1tPOGBzayOWbPJvujM8JojDk3E1LxeFisBNg=="],
"@radix-ui/react-alert-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-form/@radix-ui/react-label": ["@radix-ui/react-label@2.1.7", "https://registry.npmmirror.com/@radix-ui/react-label/-/react-label-2.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ=="],
"@radix-ui/react-label/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "https://registry.npmmirror.com/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
"@radix-ui/react-menu/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-popover/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-select/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-separator/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "https://registry.npmmirror.com/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
"@radix-ui/react-toolbar/@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-separator/-/react-separator-1.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA=="],
"@radix-ui/react-tooltip/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.7.1", "https://registry.npmmirror.com/@emnapi/core/-/core-1.7.1.tgz", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" }, "bundled": true }, "sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg=="],
@@ -417,5 +489,11 @@
"@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"next/postcss": ["postcss@8.4.31", "https://registry.npmmirror.com/postcss/-/postcss-8.4.31.tgz", { "dependencies": { "nanoid": "3.3.9", "picocolors": "1.1.1", "source-map-js": "1.2.1" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
"radix-ui/@radix-ui/react-label": ["@radix-ui/react-label@2.1.7", "https://registry.npmmirror.com/@radix-ui/react-label/-/react-label-2.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ=="],
"radix-ui/@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-separator/-/react-separator-1.1.7.tgz", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA=="],
"radix-ui/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "https://registry.npmmirror.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "lanhu-admin",
"version": "1.0.2",
"version": "1.4.0",
"private": true,
"scripts": {
"dev": "next dev -H 0.0.0.0 --turbopack",
"dev": "next dev -H 0.0.0.0 -p 3001 --turbopack",
"build": "next build --turbopack",
"lint": "eslint --fix"
"lint": "biome check --write"
},
"dependencies": {
"@hookform/resolvers": "^4.1.3",
@@ -21,9 +21,11 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"jotai": "^2.19.0",
"lucide-react": "^0.562.0",
"next": "^16.0.10",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "^19.2.1",
"react-dom": "^19.2.1",
"react-hook-form": "^7.68.0",

View File

@@ -1,5 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
}
export default config;
export default config

16
publish.ps1 Normal file
View File

@@ -0,0 +1,16 @@
if (-not $args) {
Write-Error "需要指定版本号"
exit 1
}
$confrim = Read-Host "构建版本为 [admin:$($args[0])],是否继续?(y/n)"
if ($confrim -ne "y") {
Write-Host "已取消构建"
exit 0
}
docker build -t repo.lanhuip.com:8554/lanhu/admin:latest .
docker build -t repo.lanhuip.com:8554/lanhu/admin:$($args[0]) .
docker push repo.lanhuip.com:8554/lanhu/admin:latest
docker push repo.lanhuip.com:8554/lanhu/admin:$($args[0])

41
src/actions/admin.ts Normal file
View File

@@ -0,0 +1,41 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Admin } from "@/models/admin"
import { callByUser } from "./base"
export async function getAllAdmin() {
return callByUser<Admin[]>("/api/admin/admin/all")
}
export async function getPageAdmin(params: { page: number; size: number }) {
return callByUser<PageRecord<Admin>>("/api/admin/admin/page", params)
}
export async function createAdmin(data: {
username: string
password: string
name?: string
phone?: string
email?: string
status?: number
roles?: number[]
}) {
return callByUser<Admin>("/api/admin/admin/create", data)
}
export async function updateAdmin(data: {
id: number
password?: string
name?: string
phone?: string
email?: string
status?: number
roles?: number[]
}) {
return callByUser<Admin>("/api/admin/admin/update", data)
}
export async function deleteAdmin(id: number) {
return callByUser<Admin>("/api/admin/admin/remove", { id })
}

View File

@@ -1,7 +1,7 @@
"use server"
import { cookies } from "next/headers"
import type { ApiResponse } from "@/lib/api"
import type { User } from "@/models/user"
import type { Admin } from "@/models/admin"
import { callByDevice, callByUser } from "./base"
export type TokenResp = {
@@ -16,7 +16,7 @@ export async function login(params: {
username: string
password: string
remember: boolean
}): Promise<ApiResponse> {
}): Promise<ApiResponse<string[]>> {
const resp = await callByDevice<TokenResp>("/api/auth/token", {
grant_type: "password",
login_type: "password",
@@ -43,7 +43,7 @@ export async function login(params: {
return {
success: true,
data: undefined,
data: data.scope?.split(" ") || [],
}
}
@@ -61,16 +61,8 @@ export async function logout() {
}
// 删除 cookies
cookieStore.set("admin/auth_token", "", {
httpOnly: true,
sameSite: "strict",
maxAge: -1,
})
cookieStore.set("admin/auth_refresh", "", {
httpOnly: true,
sameSite: "strict",
maxAge: -1,
})
cookieStore.delete("admin/auth_token")
cookieStore.delete("admin/auth_refresh")
return {
success: true,
@@ -79,7 +71,7 @@ export async function logout() {
}
export async function getProfile() {
return await callByUser<User>("/api/auth/introspect")
return await callByUser<Admin & { scopes: string[] }>("/api/auth/introspect")
}
export async function refreshAuth() {
@@ -128,5 +120,6 @@ export async function refreshAuth() {
return {
access_token: nextAccessToken,
refresh_token: nextRefreshToken,
scopes: data.scope?.split(" ") || [],
}
}

32
src/actions/balance.ts Normal file
View File

@@ -0,0 +1,32 @@
import type { PageRecord } from "@/lib/api"
import type { Balance } from "@/models/balance"
import { callByUser } from "./base"
export async function getPageBalance(params: {
page: number
size: number
user_phone?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Balance>>(
"/api/admin/balance-activity/page",
params,
)
}
export async function getBalance(params: {
page: number
size: number
user_id: number
user_phone?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Balance>>(
"/api/admin/balance-activity/page/of-user",
params,
)
}

View File

@@ -2,6 +2,33 @@ import type { PageRecord } from "@/lib/api"
import type { Batch } from "@/models/batch"
import { callByUser } from "./base"
export async function getPageBatch(params: { page: number; size: number }) {
export async function getPageBatch(params: {
page: number
size: number
user_phone?: string
resource_no?: string
batch_no?: string
prov?: string
city?: string
isp?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Batch>>("/api/admin/batch/page", params)
}
export async function getBatch(params: {
page: number
size: number
user_id: number
user_phone?: string
resource_no?: string
batch_no?: string
prov?: string
city?: string
isp?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Batch>>("/api/admin/batch/page/of-user", params)
}

View File

@@ -1,7 +1,44 @@
import type { PageRecord } from "@/lib/api"
import { ProductCode } from "@/lib/base"
import type { Billing } from "@/models/billing"
import type { ProductSku } from "@/models/product_sku"
import { callByUser } from "./base"
export async function getPageBill(params: { page: number; size: number }) {
export async function getPageBill(params: {
page: number
size: number
bill_no?: string
user_phone?: string
trade_inner_no?: string
resource_no?: string
sku_code?: string
product_code?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Billing>>("/api/admin/bill/page", params)
}
export async function getSkuList(params: { product_code?: ProductCode }) {
const requestParams = {
...params,
...(params.product_code === ProductCode.All && { product_code: undefined }),
}
return callByUser<ProductSku[]>("/api/admin/product/sku/all", requestParams)
}
export async function getBill(params: {
page: number
size: number
user_id: number
bill_no?: string
user_phone?: string
trade_inner_no?: string
resource_no?: string
sku_code?: string
product_code?: string
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Billing>>("/api/admin/bill/page/of-user", params)
}

View File

@@ -2,6 +2,35 @@ import type { PageRecord } from "@/lib/api"
import type { Channel } from "@/models/channel"
import { callByUser } from "./base"
export async function getPageChannel(params: { page: number; size: number }) {
export async function getPageChannel(params: {
page: number
size: number
batch_no?: string
user_phone?: string
resource_no?: string
proxy_port?: number
proxy_host?: string
node_ip?: string
expired_at_start?: Date
expired_at_end?: Date
}) {
return callByUser<PageRecord<Channel>>("/api/admin/channel/page", params)
}
export async function getChannel(params: {
page: number
size: number
user_id: number
batch_no?: string
user_phone?: string
resource_no?: string
proxy_port?: number
proxy_host?: string
node_ip?: string
expired_at_start?: Date
expired_at_end?: Date
}) {
return callByUser<PageRecord<Channel>>(
"/api/admin/channel/page/of-user",
params,
)
}

34
src/actions/coupon.ts Normal file
View File

@@ -0,0 +1,34 @@
import type { PageRecord } from "@/lib/api"
import type { Coupon } from "@/models/coupon"
import { callByUser } from "./base"
export async function getPagCoupon(params: { page: number; size: number }) {
return callByUser<PageRecord<Coupon>>("/api/admin/coupon/page", params)
}
export async function createCoupon(data: {
code: string
amount: number
remark?: string
min_amount?: number
expire_at?: Date
}) {
return callByUser<Coupon>("/api/admin/coupon/create", data)
}
export async function updateCoupon(data: {
code: string
amount: number
remark?: string
min_amount?: number
expire_at?: Date
status?: number
}) {
return callByUser<Coupon>("/api/admin/coupon/update", data)
}
export async function deleteCoupon(id: number) {
return callByUser<Coupon>("/api/admin/coupon/remove", {
id,
})
}

53
src/actions/cust.ts Normal file
View File

@@ -0,0 +1,53 @@
import type { PageRecord } from "@/lib/api"
import type { User } from "@/models/user"
import { callByUser } from "./base"
export async function getPageCusts(params: { page: number; size: number }) {
return callByUser<PageRecord<User>>("/api/admin/user/page", params)
}
export async function updateCust(data: {
id: number
username?: string
email?: string
password?: string
admin_id?: number
discount_id?: number
status?: number
contact_qq?: string
contact_wechat?: string
}) {
return callByUser<PageRecord<User>>("/api/admin/user/update", data)
}
export async function createCust(data: {
phone: string
password?: string
username?: string
admin_id?: number
discount_id?: number
email?: string
name?: string
avatar?: string
status?: number
contact_qq?: string
contact_wechat?: string
}) {
return callByUser<PageRecord<User>>("/api/admin/user/create", data)
}
export async function getDeposit(params: { user_id: number; amount: string }) {
return callByUser<PageRecord<User>>(
"/api/admin/user/update/balance-inc",
params,
)
}
export async function getDeduction(params: {
user_id: number
amount: string
}) {
return callByUser<PageRecord<User>>(
"/api/admin/user/update/balance-dec",
params,
)
}

26
src/actions/gateway.ts Normal file
View File

@@ -0,0 +1,26 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Gateway } from "@/models/gateway"
import { callByUser } from "./base"
export async function getGatewayPage(params: { page: number; size: number }) {
return callByUser<PageRecord<Gateway>>("/api/admin/proxy/page", params)
}
export async function createGateway(data: {
mac: string
ip: string
host?: string
type: number
status: number
}) {
return callByUser<Gateway>("/api/admin/proxy/create", data)
}
export async function deletegateway(id: number) {
return callByUser<Gateway>("/api/admin/proxy/remove", {
id,
})
}

19
src/actions/permission.ts Normal file
View File

@@ -0,0 +1,19 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Permission } from "@/models/permission"
import { callByUser } from "./base"
export async function getPagePermission(params: {
page: number
size: number
}) {
return callByUser<PageRecord<Permission>>(
"/api/admin/permission/page",
params,
)
}
export async function getAllPermissions() {
return callByUser<Permission[]>("/api/admin/permission/list", {})
}

74
src/actions/product.ts Normal file
View File

@@ -0,0 +1,74 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Product } from "@/models/product"
import type { ProductSku } from "@/models/product_sku"
import { callByUser } from "./base"
export async function getAllProduct() {
return callByUser<Product[]>("/api/admin/product/all")
}
export async function getPageProductSku(params: {
page: number
size: number
product_id?: number
}) {
return callByUser<PageRecord<ProductSku>>(
"/api/admin/product/sku/page",
params,
)
}
export async function createProductSku(data: {
product_id: number
code: string
name: string
price: string
discount_id?: number
price_min?: string
}) {
return callByUser<ProductSku>("/api/admin/product/sku/create", {
product_id: data.product_id,
code: data.code,
name: data.name,
price: data.price,
discount_id: data.discount_id,
price_min: data.price_min,
})
}
export async function updateProductSku(data: {
id: number
code?: string
name?: string
price?: string
discount_id?: number | null
price_min?: string
}) {
return callByUser<ProductSku>("/api/admin/product/sku/update", {
id: data.id,
code: data.code,
name: data.name,
price: data.price,
discount_id: data.discount_id,
price_min: data.price_min,
})
}
export async function deleteProductSku(id: number) {
return callByUser<ProductSku>("/api/admin/product/sku/remove", { id })
}
export async function batchUpdateProductSkuDiscount(data: {
product_id: number
discount_id: number | null
}) {
return callByUser<void>("/api/admin/product/sku/update/discount/batch", {
product_id: data.product_id,
discount_id: data.discount_id,
})
}
export async function activeProductSku(data: { id: number; status: number }) {
return callByUser<ProductSku>("/api/admin/product/sku/update/status", data)
}

View File

@@ -0,0 +1,47 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { ProductDiscount } from "@/models/product_discount"
import { callByUser } from "./base"
export async function getAllProductDiscount() {
return callByUser<ProductDiscount[]>("/api/admin/discount/all")
}
export async function getPageProductDiscount(params: {
page: number
size: number
}) {
return callByUser<PageRecord<ProductDiscount>>(
"/api/admin/discount/page",
params,
)
}
export async function createProductDiscount(data: {
name: string
discount: string
}) {
return callByUser<ProductDiscount>("/api/admin/discount/create", {
name: data.name,
discount: Number(data.discount),
})
}
export async function updateProductDiscount(data: {
id: number
name?: string
discount?: string
}) {
return callByUser<ProductDiscount>("/api/admin/discount/update", {
id: data.id,
name: data.name,
discount: data.discount ? Number(data.discount) : undefined,
})
}
export async function deleteProductDiscount(id: number) {
return callByUser<ProductDiscount>("/api/admin/discount/remove", {
id,
})
}

View File

@@ -2,19 +2,68 @@ import type { PageRecord } from "@/lib/api"
import type { Resources } from "@/models/resources"
import { callByUser } from "./base"
export async function listResourceLong(params: { page: number; size: number }) {
export interface ResourceListParams {
page: number
size: number
user_phone?: string
resource_no?: string
active?: boolean
mode?: number
created_at_start?: Date
created_at_end?: Date
expired?: boolean
}
export async function listResourceLong(params: ResourceListParams) {
return callByUser<PageRecord<Resources>>(
"/api/admin/resource/long/page",
params,
)
}
export async function listResourceShort(params: {
page: number
size: number
}) {
export async function listResourceShort(params: ResourceListParams) {
return callByUser<PageRecord<Resources>>(
"/api/admin/resource/short/page",
params,
)
}
export async function updateResource(data: { id: number; active?: boolean }) {
return callByUser<Resources>("/api/admin/resource/update", data)
}
export async function ResourceLong(params: {
page: number
size: number
user_id: number
user_phone?: string
resource_no?: string
active?: boolean
mode?: number
created_at_start?: Date
created_at_end?: Date
expired?: boolean
}) {
return callByUser<PageRecord<Resources>>(
"/api/admin/resource/long/page/of-user",
params,
)
}
export async function ResourceShort(params: {
page: number
size: number
user_id: number
user_phone?: string
resource_no?: string
active?: boolean
mode?: number
created_at_start?: Date
created_at_end?: Date
expired?: boolean
}) {
return callByUser<PageRecord<Resources>>(
"/api/admin/resource/short/page/of-user",
params,
)
}

38
src/actions/role.ts Normal file
View File

@@ -0,0 +1,38 @@
"use server"
import type { PageRecord } from "@/lib/api"
import type { Role } from "@/models/role"
import { callByUser } from "./base"
export async function getAllRoles() {
return callByUser<Role[]>("/api/admin/admin-role/list", {})
}
export async function getPageRole(params: { page: number; size: number }) {
return callByUser<PageRecord<Role>>("/api/admin/admin-role/page", params)
}
export async function createRole(data: {
name: string
description?: string
active?: boolean
sort?: number
permissions?: number[]
}) {
return callByUser<Role>("/api/admin/admin-role/create", data)
}
export async function updateRole(data: {
id: number
name?: string
description?: string
active?: boolean
sort?: number
permissions?: number[]
}) {
return callByUser<Role>("/api/admin/admin-role/update", data)
}
export async function deleteRole(id: number) {
return callByUser<Role>("/api/admin/admin-role/remove", { id })
}

View File

@@ -2,6 +2,31 @@ import type { PageRecord } from "@/lib/api"
import type { Trade } from "@/models/trade"
import { callByUser } from "./base"
export async function getPageTrade(params: { page: number; size: number }) {
export async function getPageTrade(params: {
page: number
size: number
user_phone?: string
inner_no?: string
method?: number
platform?: number
status?: number
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Trade>>("/api/admin/trade/page", params)
}
export async function getTrade(params: {
page: number
size: number
user_id: number
user_phone?: string
inner_no?: string
method?: number
platform?: number
status?: number
created_at_start?: Date
created_at_end?: Date
}) {
return callByUser<PageRecord<Trade>>("/api/admin/trade/page/of-user", params)
}

View File

@@ -6,8 +6,23 @@ export async function getPageUsers(params: { page: number; size: number }) {
return callByUser<PageRecord<User>>("/api/admin/user/page", params)
}
export async function bindAdmin(params: { id: number }) {
return callByUser("/api/admin/user/bind", {
export async function getPageUserPage(params: { page: number; size: number }) {
return callByUser<PageRecord<User>>("/api/admin/user/page/not-bind", params)
}
export async function bindAdmin(params: {
id: number
account?: string
name?: string
identified?: boolean
enabled?: boolean
assigned?: boolean
}) {
return callByUser("/api/admin/user/update/bind", {
user_id: params.id,
})
}
export async function getPageUser(params: { phone?: string; name?: string }) {
return callByUser<User>("/api/admin/user/get", params)
}

View File

@@ -0,0 +1,159 @@
import { useCallback, useEffect, useState } from "react"
import { toast } from "sonner"
import { updateAdmin } from "@/actions/admin"
import { getAllRoles } from "@/actions/role"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import type { Admin } from "@/models/admin"
import type { Role } from "@/models/role"
export function AssignRoles(props: { admin: Admin; onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [roles, setRoles] = useState<Role[]>([])
const [selected, setSelected] = useState<Set<number>>(new Set())
const fetchRoles = useCallback(async () => {
setLoading(true)
try {
const resp = await getAllRoles()
if (resp.success) {
setRoles(resp.data ?? [])
} else {
toast.error(resp.message ?? "获取角色列表失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (open) {
fetchRoles()
}
}, [open, fetchRoles])
const handleToggle = (id: number, checked: boolean) => {
setSelected(prev => {
const next = new Set(prev)
if (checked) {
next.add(id)
} else {
next.delete(id)
}
return next
})
}
const handleSubmit = async () => {
setSubmitting(true)
try {
const resp = await updateAdmin({
id: props.admin.id,
roles: Array.from(selected),
})
if (resp.success) {
toast.success("角色分配成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message ?? "角色分配失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setSubmitting(false)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
const existingIds = new Set((props.admin.roles ?? []).map(r => r.id))
setSelected(existingIds)
} else {
setSelected(new Set())
setRoles([])
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle> · {props.admin.username}</DialogTitle>
</DialogHeader>
<div className="max-h-[60vh] overflow-y-auto pr-1">
{loading ? (
<div className="py-8 text-center text-sm text-muted-foreground">
...
</div>
) : roles.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
</div>
) : (
<div className="flex flex-col gap-2">
{roles.map(role => {
const checkboxId = `assign-role-${role.id}`
const isChecked = selected.has(role.id)
return (
<div key={role.id} className="flex items-center gap-2 py-0.5">
<Checkbox
id={checkboxId}
checked={isChecked}
onCheckedChange={checked =>
handleToggle(role.id, checked === true)
}
/>
<label
htmlFor={checkboxId}
className="flex items-center gap-1.5 cursor-pointer select-none text-sm"
>
{role.name}
{role.description && (
<span className="text-xs text-muted-foreground">
{role.description}
</span>
)}
</label>
</div>
)
})}
</div>
)}
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button onClick={handleSubmit} disabled={submitting || loading}>
{submitting ? "保存中..." : "保存"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,237 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createAdmin } from "@/actions/admin"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { AdminStatus } from "@/models/admin"
const schema = z.object({
username: z.string().min(1, "请输入用户名"),
password: z.string().min(6, "密码至少 6 位"),
name: z.string().optional(),
phone: z.string().optional(),
email: z.string().email("请输入有效的邮箱地址").optional().or(z.literal("")),
status: z.nativeEnum(AdminStatus),
})
type FormValues = z.infer<typeof schema>
export function CreateAdmin(props: { onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
username: "",
password: "",
name: "",
phone: "",
email: "",
status: AdminStatus.Enabled,
},
})
const onSubmit = async (data: FormValues) => {
try {
const resp = await createAdmin({
username: data.username,
password: data.password,
name: data.name || undefined,
phone: data.phone || undefined,
email: data.email || undefined,
status: data.status,
})
if (resp.success) {
form.reset()
toast.success("管理员创建成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (!value) {
form.reset()
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="admin-create" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="username"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-create-username">
</FieldLabel>
<Input
id="admin-create-username"
autoComplete="off"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="password"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-create-password"></FieldLabel>
<Input
id="admin-create-password"
type="password"
autoComplete="new-password"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-create-name"></FieldLabel>
<Input
id="admin-create-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="phone"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-create-phone"></FieldLabel>
<Input
id="admin-create-phone"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="email"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-create-email"></FieldLabel>
<Input
id="admin-create-email"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="status"
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Select
value={String(field.value)}
onValueChange={value => field.onChange(Number(value))}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={String(AdminStatus.Enabled)}>
</SelectItem>
<SelectItem value={String(AdminStatus.Disabled)}>
</SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="admin-create">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,276 @@
"use client"
import { Lock } from "lucide-react"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { deleteAdmin, getPageAdmin, updateAdmin } from "@/actions/admin"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import { type Admin, AdminStatus } from "@/models/admin"
import type { Role } from "@/models/role"
import { AssignRoles } from "./assign-roles"
import { CreateAdmin } from "./create"
import { UpdateAdmin } from "./update"
export default function AdminPage() {
const table = useDataTable((page, size) => getPageAdmin({ page, size }))
return (
<Page>
{/* 操作栏 */}
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreateAdmin onSuccess={table.refresh} />
</div>
</div>
{/* 数据表 */}
<Suspense>
<DataTable
{...table}
columns={[
{ header: "用户名", accessorKey: "username" },
{
header: "姓名",
accessorFn: row => row.name ?? "",
},
{
header: "手机号",
accessorFn: row => row.phone ?? "",
},
{
header: "邮箱",
accessorFn: row => row.email ?? "",
},
{
header: "状态",
cell: ({ row }) => (
<Badge
variant={
row.original.status === AdminStatus.Enabled
? "default"
: "secondary"
}
>
{row.original.status === AdminStatus.Enabled
? "启用"
: "禁用"}
</Badge>
),
},
{
header: "角色",
cell: ({ row }) => <RolesCell roles={row.original.roles ?? []} />,
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => {
const admin = row.original
if (admin.lock === true) {
return (
<Tooltip>
<TooltipTrigger asChild>
<div className="flex justify-center items-center">
<Lock className="h-4 w-4 text-muted-foreground" />
</div>
</TooltipTrigger>
<TooltipContent>
<p></p>
</TooltipContent>
</Tooltip>
)
}
return (
<div className="flex gap-2">
<UpdateAdmin
admin={row.original}
onSuccess={table.refresh}
/>
<AssignRoles
admin={row.original}
onSuccess={table.refresh}
/>
<ToggleStatusButton
admin={row.original}
onSuccess={table.refresh}
/>
<DeleteButton
admin={row.original}
onSuccess={table.refresh}
/>
</div>
)
},
},
]}
/>
</Suspense>
</Page>
)
}
function RolesCell({ roles }: { roles: Role[] }) {
if (!roles || roles.length === 0) {
return <span className="text-muted-foreground text-xs"></span>
}
const preview = roles.slice(0, 3)
const rest = roles.length - preview.length
return (
<HoverCard>
<HoverCardTrigger asChild>
<div className="flex flex-wrap gap-1 cursor-default max-w-52">
{preview.map(r => (
<Badge key={r.id} variant="secondary">
{r.name}
</Badge>
))}
{rest > 0 && <Badge variant="outline">+{rest}</Badge>}
</div>
</HoverCardTrigger>
<HoverCardContent className="w-64" align="start">
<p className="text-xs font-medium text-muted-foreground mb-2">
{roles.length}
</p>
<div className="flex flex-wrap gap-1.5">
{roles.map(r => (
<Badge key={r.id} variant="secondary">
{r.name}
</Badge>
))}
</div>
</HoverCardContent>
</HoverCard>
)
}
function ToggleStatusButton({
admin,
onSuccess,
}: {
admin: Admin
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const isEnabled = admin.status === AdminStatus.Enabled
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await updateAdmin({
id: admin.id,
status: isEnabled ? AdminStatus.Disabled : AdminStatus.Enabled,
})
if (resp.success) {
toast.success(isEnabled ? "已禁用" : "已启用")
onSuccess?.()
} else {
toast.error(resp.message ?? "操作失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="secondary" disabled={loading}>
{isEnabled ? "禁用" : "启用"}
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle>{isEnabled ? "禁用" : "启用"}</AlertDialogTitle>
<AlertDialogDescription>
{isEnabled ? "禁用" : "启用"}{admin.username}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleConfirm}></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
function DeleteButton({
admin,
onSuccess,
}: {
admin: Admin
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await deleteAdmin(admin.id)
if (resp.success) {
toast.success("删除成功")
onSuccess?.()
} else {
toast.error(resp.message ?? "删除失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{admin.username}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -0,0 +1,229 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { updateAdmin } from "@/actions/admin"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { type Admin, AdminStatus } from "@/models/admin"
const schema = z.object({
password: z.string().min(6, "密码至少6位").optional().or(z.literal("")),
name: z.string().optional(),
phone: z.string().optional(),
email: z.string().email("请输入有效的邮箱地址").optional().or(z.literal("")),
status: z.nativeEnum(AdminStatus),
})
type FormValues = z.infer<typeof schema>
export function UpdateAdmin(props: { admin: Admin; onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
password: "",
name: props.admin.name ?? "",
phone: props.admin.phone ?? "",
email: props.admin.email ?? "",
status: props.admin.status,
},
})
const onSubmit = async (data: FormValues) => {
try {
const resp = await updateAdmin({
id: props.admin.id,
password: data.password || undefined,
name: data.name || undefined,
phone: data.phone || undefined,
email: data.email || undefined,
status: data.status,
})
if (resp.success) {
toast.success("管理员修改成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
form.reset({
password: "",
name: props.admin.name ?? "",
phone: props.admin.phone ?? "",
email: props.admin.email ?? "",
status: props.admin.status,
})
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="admin-update" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
{/* 用户名只读,不可修改 */}
<Field>
<FieldLabel></FieldLabel>
<Input value={props.admin.username} disabled />
</Field>
<Controller
control={form.control}
name="password"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-update-password">
</FieldLabel>
<Input
id="admin-update-password"
type="password"
placeholder="不修改请留空"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-update-name"></FieldLabel>
<Input
id="admin-update-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="phone"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-update-phone"></FieldLabel>
<Input
id="admin-update-phone"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="email"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="admin-update-email"></FieldLabel>
<Input
id="admin-update-email"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="status"
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Select
value={String(field.value)}
onValueChange={value => field.onChange(Number(value))}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={String(AdminStatus.Enabled)}>
</SelectItem>
<SelectItem value={String(AdminStatus.Disabled)}>
</SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="admin-update">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -1,12 +1,9 @@
"use client"
import {
BadgeQuestionMarkIcon,
BellIcon,
ChevronDownIcon,
ChevronRightIcon,
InboxIcon,
LogOutIcon,
SearchIcon,
SettingsIcon,
UserIcon,
} from "lucide-react"
@@ -14,39 +11,14 @@ import Image from "next/image"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { useEffect, useRef, useState } from "react"
import { getProfile, logout } from "@/actions/auth"
import { logout } from "@/actions/auth"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import type { User } from "@/models/user"
import type { Admin } from "@/models/admin"
export default function Appbar() {
const [currentUser, setCurrentUser] = useState<User>()
export default function Appbar(props: { admin: Admin }) {
const router = useRouter()
const [showDropdown, setShowDropdown] = useState(false)
const [showNotifications, setShowNotifications] = useState(false)
const [notifications] = useState([
{
id: 1,
title: "系统通知",
content: "您有新的待审核内容",
time: "10分钟前",
read: false,
},
{
id: 2,
title: "安全提醒",
content: "您的账号于昨天登录了新设备",
time: "1小时前",
read: true,
},
{
id: 3,
title: "系统更新",
content: "系统将在今晚进行例行维护",
time: "2小时前",
read: true,
},
])
const pathname = usePathname()
const dropdownRef = useRef<HTMLDivElement>(null)
@@ -73,14 +45,15 @@ export default function Appbar() {
return () => document.removeEventListener("mousedown", handleClickOutside)
}, [])
// 根据路径生成面包屑
const generateBreadcrumbs = () => {
const paths = pathname.split("/").filter(Boolean)
const hiddenSegments = ["client"]
const filteredPaths = paths.filter(path => !hiddenSegments.includes(path))
const breadcrumbs = [
{ path: "/", label: "首页" },
...paths.map((path, index) => {
const url = `/${paths.slice(0, index + 1).join("/")}`
...filteredPaths.map((path, index) => {
const originalIndex = paths.findIndex(p => p === path)
const url = `/${paths.slice(0, originalIndex + 1).join("/")}`
const label = getBreadcrumbLabel(path)
return { path: url, label }
}),
@@ -95,7 +68,7 @@ export default function Appbar() {
content: "内容管理",
articles: "文章管理",
media: "媒体库",
user: "用户管理",
user: "客户认领",
roles: "角色权限",
settings: "系统设置",
logs: "系统日志",
@@ -103,17 +76,25 @@ export default function Appbar() {
nodes: "节点列表",
trade: "交易明细",
billing: "账单详情",
cust: "客户管理",
product: "产品管理",
resources: "套餐管理",
batch: "使用记录",
batch: "提取记录",
channel: "IP管理",
pools: "IP池管理",
coupon: "优惠券",
admin: "管理员",
permissions: "权限列表",
discount: "折扣管理",
statistics: "数据统计",
balance: "余额明细",
gateway: "网关列表",
}
return labels[path] || path
}
const breadcrumbs = generateBreadcrumbs()
const unreadCount = notifications.filter(n => !n.read).length
const doLogout = async () => {
const resp = await logout()
if (resp.success) {
@@ -122,30 +103,8 @@ export default function Appbar() {
}
}
useEffect(() => {
async function fetchUserProfile() {
try {
const resp = await getProfile()
console.log(resp, "resp")
if (resp.success) {
setCurrentUser(resp.data)
} else {
console.error("获取用户信息失败:", resp.message)
if (resp.status === 401) {
router.replace("/login")
}
}
} catch (error) {
console.error("获取用户信息时出错:", error)
}
}
fetchUserProfile()
}, [router])
return (
<header className="bg-white h-16 border-b border-gray-200 flex items-center justify-between px-6">
<header className="bg-white flex-none basis-16 border-b border-gray-200 flex items-center justify-between px-6">
{/* 面包屑导航 */}
<div className="flex items-center text-sm">
{breadcrumbs.map((crumb, index) => (
@@ -169,88 +128,6 @@ export default function Appbar() {
{/* 右侧用户信息和工具栏 */}
<div className="flex items-center space-x-4">
{/* 搜索框 */}
<div className="hidden md:block relative">
<div className="relative">
<SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
<Input
type="text"
placeholder="搜索..."
className="pl-10 pr-4 py-2 bg-gray-100 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent w-56"
/>
</div>
</div>
{/* 通知图标 */}
<div className="relative" ref={notificationRef}>
<Button
onClick={() => setShowNotifications(!showNotifications)}
className="relative p-2 rounded-full text-gray-600 bg-gray-100 hover:bg-gray-100 hover:text-gray-800 transition-colors"
aria-label="通知"
>
<BellIcon />
{unreadCount > 0 && (
<span className="absolute top-1 right-1 h-4 w-4 text-xs flex items-center justify-center rounded-full bg-red-500 text-white">
{unreadCount}
</span>
)}
</Button>
{/* 通知下拉面板 */}
{showNotifications && (
<div className="absolute right-0 mt-2 w-80 bg-white rounded-md shadow-lg py-1 z-20 border border-gray-200">
<div className="px-4 py-2 border-b border-gray-100 flex justify-between items-center">
<h3 className="font-medium text-gray-800"></h3>
<Button className="text-xs text-blue-600 hover:text-blue-800">
</Button>
</div>
<div className="max-h-72 overflow-y-auto">
{notifications.length > 0 ? (
notifications.map(notification => (
<div
key={notification.id}
className={`px-4 py-3 border-b border-gray-100 hover:bg-gray-50 ${
notification.read ? "bg-white" : "bg-blue-50"
}`}
>
<div className="flex justify-between items-start">
<h4 className="text-sm font-medium text-gray-800">
{notification.title}
</h4>
<span className="text-xs text-gray-500">
{notification.time}
</span>
</div>
<p className="text-xs text-gray-600 mt-1">
{notification.content}
</p>
</div>
))
) : (
<div className="py-8 px-4 text-center">
<InboxIcon size={18} />
<p className="mt-2 text-sm text-gray-500"></p>
</div>
)}
</div>
<div className="border-t border-gray-100 p-2 text-center">
<Link
href="/notifications"
className="text-xs text-blue-600 hover:text-blue-800"
>
</Link>
</div>
</div>
)}
</div>
{/* 分隔线 */}
<div className="hidden md:block h-8 w-px bg-gray-200"></div>
{/* 用户下拉菜单 */}
<div className="relative" ref={dropdownRef}>
<Button
@@ -259,10 +136,10 @@ export default function Appbar() {
aria-label="用户菜单"
>
<div className="h-8 w-8 rounded-full bg-blue-100 text-blue-800 flex items-center justify-center overflow-hidden border-2 border-white shadow-sm">
{currentUser ? (
currentUser.avatar ? (
{props.admin ? (
props.admin.avatar ? (
<Image
src={currentUser.avatar}
src={props.admin.avatar}
alt="用户头像"
width={32}
height={32}
@@ -271,8 +148,8 @@ export default function Appbar() {
const target = e.target as HTMLImageElement
target.style.display = "none"
const parent = target.parentElement
if (parent && currentUser?.name) {
parent.textContent = currentUser.name
if (parent && props.admin?.name) {
parent.textContent = props.admin.name
.charAt(0)
.toUpperCase()
}
@@ -281,7 +158,7 @@ export default function Appbar() {
) : (
// 如果没有头像,直接显示用户名首字母
<span className="text-sm font-semibold">
{currentUser.name.charAt(0).toUpperCase()}
{props.admin.name?.charAt(0).toUpperCase()}
</span>
)
) : (
@@ -290,12 +167,14 @@ export default function Appbar() {
)}
</div>
<div className="hidden md:block text-left">
{currentUser && (
{props.admin && (
<div>
<p className="text-sm font-medium text-gray-800">
{currentUser.name}
{props.admin.name}
</p>
<p className="text-xs text-gray-500">
{props.admin.username}
</p>
<p className="text-xs text-gray-500">{currentUser.username}</p>
</div>
)}
</div>
@@ -305,13 +184,13 @@ export default function Appbar() {
{/* 用户下拉内容 */}
{showDropdown && (
<div className="absolute right-0 mt-2 w-56 bg-white rounded-lg shadow-lg py-2 z-20 border border-gray-200">
{currentUser && (
{props.admin && (
<div className="px-4 py-2 border-b border-gray-100 md:hidden">
<p className="font-medium text-gray-800">
{currentUser.name}
{props.admin.name}
</p>
<p className="text-xs text-gray-500">{currentUser.name}</p>
<p className="text-xs text-gray-500">{props.admin.name}</p>
</div>
)}

View File

@@ -0,0 +1,230 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import z from "zod"
import { getPageBalance } from "@/actions/balance"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { Balance } from "@/models/balance"
type FilterValues = {
user_phone?: string
bill_no?: string
admin_id?: string
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
phone: z.string().optional(),
bill_no: z.string().optional(),
admin_id: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FormValues = z.infer<typeof filterSchema>
export default function BalancePage() {
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
bill_no: "",
admin_id: "",
created_at_start: "",
created_at_end: "",
},
})
const fetchUsers = useCallback(
(page: number, size: number) => getPageBalance({ page, size, ...filters }),
[filters],
)
const table = useDataTable<Balance>(fetchUsers)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入账单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Balance>
{...table}
columns={[
{
header: "会员号",
accessorFn: row => row.user?.phone || "",
},
{
header: "账单号",
accessorFn: row => row.bill?.bill_no || "",
},
{
header: "管理员",
accessorKey: "admin_id",
accessorFn: row => row.admin?.name || "",
},
{
header: "变动金额",
accessorKey: "amount",
cell: ({ row }) => {
const amount = row.original.amount
const isPositive = Number(amount) > 0
return (
<div className="flex items-center gap-1">
<span
className={`font-semibold ${
isPositive ? "text-green-600" : "text-red-600"
}`}
>
{isPositive ? "+" : ""}
{Number(amount).toFixed(2)}
</span>
</div>
)
},
},
{
header: "余额变化",
accessorKey: "balance_prev",
cell: ({ row }) => (
<div className="flex items-center gap-2">
<span className="text-muted-foreground text-sm">
¥{Number(row.original.balance_prev).toFixed(2)}
</span>
<span className="text-muted-foreground"></span>
<span className="font-medium text-foreground">
¥{Number(row.original.balance_curr).toFixed(2)}
</span>
</div>
),
},
{
header: "备注",
accessorKey: "remark",
},
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -1,36 +1,276 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense } from "react"
import { Suspense, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getPageBatch } from "@/actions/batch"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Batch } from "@/models/batch"
type APIFilterParams = {
user_phone?: string
batch_no?: string
resource_no?: string
prov?: string
city?: string
isp?: string
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
user_phone: z.string().optional(),
resource_no: z.string().optional(),
batch_no: z.string().optional(),
prov: z.string().optional(),
city: z.string().optional(),
isp: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function BatchPage() {
const [filters, setFilters] = useState<APIFilterParams>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
user_phone: "",
batch_no: "",
prov: "",
city: "",
isp: "all",
created_at_start: "",
created_at_end: "",
},
})
const table = useDataTable<Batch>((page, size) =>
getPageBatch({ page, size }),
getPageBatch({ page, size, ...filters }),
)
const onFilter = handleSubmit(data => {
const result: APIFilterParams = {}
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.batch_no?.trim()) result.batch_no = data.batch_no.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.prov?.trim()) result.prov = data.prov.trim()
if (data.city?.trim()) result.city = data.city.trim()
if (data.isp && data.isp !== "all") result.isp = data.isp
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Suspense fallback={<div>Loading...</div>}>
<DataTable<Batch>
{...table}
columns={[
{ header: "ID", accessorKey: "id" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "省份", accessorKey: "prov" },
{ header: "城市", accessorKey: "city" },
{ header: "提取IP", accessorKey: "ip" },
{ header: "运营商", accessorKey: "isp" },
{ header: "提取数量", accessorKey: "count" },
{ header: "资源数量", accessorKey: "resource_id" },
{
header: "提取时间",
accessorKey: "time",
cell: ({ row }) =>
format(new Date(row.original.time), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
<Page>
{/* 搜索表单 */}
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="batch_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="prov"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入省份" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="city"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入城市" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="isp"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
<SelectItem value="3"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense fallback={<div>Loading...</div>}>
<DataTable<Batch>
{...table}
columns={[
{
header: "会员号",
accessorFn: row => row.user?.phone || "",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "省份", accessorKey: "prov" },
{ header: "城市", accessorKey: "city" },
{ header: "用户IP", accessorKey: "ip" },
{ header: "运营商", accessorKey: "isp" },
{ header: "提取数量", accessorKey: "count" },
{
header: "提取时间",
accessorKey: "time",
cell: ({ row }) =>
format(new Date(row.original.time), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -1,95 +1,460 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CreditCard } from "lucide-react"
import { Suspense } from "react"
import { getPageBill } from "@/actions/bill"
import { CreditCard, Wallet } from "lucide-react"
import { Suspense, useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getPageBill, getSkuList } from "@/actions/bill"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { ProductCode } from "@/lib/base"
import type { Billing } from "@/models/billing"
type FilterValues = {
bill_no?: string
user_phone?: string
trade_inner_no?: string
resource_no?: string
sku_code?: string
product_code?: string
created_at_start?: Date
created_at_end?: Date
}
type SkuOption = {
resource_code: string
resource_name: string
}
const filterSchema = z
.object({
phone: z
.string()
.optional()
.transform(val => val?.trim()),
bill_no: z
.string()
.optional()
.transform(val => val?.trim()),
resource_no: z.string().optional(),
inner_no: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
product_code: z.string().optional(),
sku_code: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function BillingPage() {
const table = useDataTable<Billing>((page, size) =>
getPageBill({ page, size }),
const [filters, setFilters] = useState<FilterValues>({})
const [skuOptions, setSkuOptions] = useState<SkuOption[]>([])
const [loading, setLoading] = useState(true)
const [skuProductCode, setSkuProductCode] = useState<ProductCode>(
ProductCode.All,
)
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
bill_no: "",
inner_no: "",
created_at_start: "",
created_at_end: "",
phone: "",
resource_no: "",
sku_code: "all",
product_code: "",
},
})
useEffect(() => {
setLoading(true)
getSkuList({
product_code: skuProductCode,
})
.then(resp => {
if (!resp.success) {
throw new Error(resp.message)
}
setSkuOptions(
resp.data.map(sku => ({
resource_code: sku.code,
resource_name: sku.name,
})),
)
})
.catch(e => {
console.error("获取套餐类型失败:", e)
toast.error(
`获取套餐类型失败:${e instanceof Error ? e.message : String(e)}`,
)
setSkuOptions([])
})
.finally(() => {
setLoading(false)
})
}, [skuProductCode])
const table = useDataTable<Billing>((page, size) =>
getPageBill({ page, size, ...filters }),
)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.inner_no?.trim()) result.trade_inner_no = data.inner_no.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.product_code && data.product_code !== ProductCode.All) {
result.product_code = data.product_code
}
if (data.sku_code && data.sku_code !== "all") {
result.sku_code = data.sku_code
}
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Suspense>
<DataTable<Billing>
{...table}
columns={[
{ header: "ID", accessorKey: "id" },
{ header: "账单号", accessorKey: "bill_no" },
{
header: "账单详情",
accessorKey: "info",
cell: ({ row }) => {
const bill = row.original
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入账单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="inner_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入订单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
return (
<div className="flex items-center gap-2">
{/* 类型展示 */}
<div className="shrink-0">
{bill.type === 1 && (
<div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.type === 2 && (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span>退</span>
</div>
)}
{bill.type === 3 && (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
<Controller
name="product_code"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Select
value={skuProductCode}
onValueChange={value => {
setSkuProductCode(value as ProductCode)
field.onChange(value)
}}
>
<SelectTrigger>
<SelectValue
placeholder={"请选择"}
defaultValue={
skuProductCode === ProductCode.All ? "全部" : ""
}
/>
</SelectTrigger>
<SelectContent>
<SelectItem value={ProductCode.All}></SelectItem>
<SelectItem value={ProductCode.Short}></SelectItem>
<SelectItem value={ProductCode.Long}></SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
<Controller
name="sku_code"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Select
value={loading ? undefined : field.value || "all"}
onValueChange={field.onChange}
>
<SelectTrigger>
<SelectValue placeholder={loading ? "加载中..." : "全部"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{skuOptions.map(option => (
<SelectItem
key={option.resource_code}
value={option.resource_code}
>
{option.resource_name || option.resource_code}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setSkuProductCode(ProductCode.All)
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Billing>
{...table}
columns={[
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "会员号", accessorFn: row => row.user?.phone || "" },
{
header: "账单详情",
accessorKey: "info",
cell: ({ row }) => {
const bill = row.original
return (
<div className="flex items-center gap-2">
<div className="shrink-0">
{bill.type === 1 && (
<div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.type === 2 && (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span>退</span>
</div>
)}
{bill.type === 3 && (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
</div>
<div className="text-sm">{bill.info}</div>
</div>
)
},
},
{
header: "应付金额",
accessorKey: "amount",
cell: ({ row }) => {
const amount =
typeof row.original.amount === "string"
? parseFloat(row.original.amount)
: row.original.amount || 0
return (
<div className="flex gap-1">
<span
className={
amount > 0 ? "text-green-500" : "text-orange-500"
}
>
{amount.toFixed(2)}
</span>
</div>
)
},
},
{
header: "实付金额",
accessorKey: "actual",
cell: ({ row }) => {
const actual =
typeof row.original.actual === "string"
? parseFloat(row.original.actual)
: row.original.actual || 0
return (
<div className="flex gap-1">
<span
className={
actual > 0 ? "text-green-500" : "text-orange-500"
}
>
{actual.toFixed(2)}
</span>
</div>
)
},
},
{ header: "账单号", accessorKey: "bill_no" },
{
header: "订单号",
accessorKey: "trade.inner_no",
cell: ({ row }) => {
const bill = row.original
{/* 账单详情 */}
<div className="text-sm">{bill.info}</div>
</div>
)
return (
<div className="flex items-center gap-2">
<div className="shrink-0 w-20">
{bill.trade?.acquirer === 1 && (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.trade?.acquirer === 2 && (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.trade?.acquirer === 3 && (
<div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{!bill.trade?.acquirer && (
<div className="flex gap-2 items-center bg-red-50 w-full px-2 py-1 rounded-md">
<Wallet size={16} />
<span></span>
</div>
)}
</div>
<div className="text-sm">{bill.trade?.inner_no}</div>
</div>
)
},
},
},
{
header: "支付信息",
accessorKey: "amount",
cell: ({ row }) => {
const amount =
typeof row.original.amount === "string"
? parseFloat(row.original.amount)
: row.original.amount || 0
return (
<div className="flex gap-1">
<span
className={
amount > 0 ? "text-green-500" : "text-orange-500"
}
>
{amount.toFixed(2)}
</span>
</div>
)
},
},
// { header: "资源数量", accessorKey: "resource_id" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -1,107 +1,328 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense } from "react"
import { Suspense, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getPageChannel } from "@/actions/channel"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { Channel } from "@/models/channel"
type FilterValues = {
batch_no?: string
user_phone?: string
resource_no?: string
proxy_host?: string
proxy_port?: number
node_ip?: string
expired_at_start?: Date
expired_at_end?: Date
}
const filterSchema = z
.object({
batch_no: z.string().optional(),
user_phone: z.string().optional(),
resource_no: z.string().optional(),
proxy_host: z.string().optional(),
proxy_port: z.string().optional(),
node_ip: z.string().optional(),
expired_at_start: z.string().optional(),
expired_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.expired_at_start && data.expired_at_end) {
const start = new Date(data.expired_at_start)
const end = new Date(data.expired_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["expired_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
const ispMap: Record<number, string> = {
1: "电信",
2: "联通",
3: "移动",
}
export default function ChannelPage() {
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
batch_no: "",
user_phone: "",
resource_no: "",
proxy_port: "",
proxy_host: "",
node_ip: "",
expired_at_start: "",
expired_at_end: "",
},
})
const table = useDataTable<Channel>((page, size) =>
getPageChannel({ page, size }),
getPageChannel({ page, size, ...filters }),
)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.batch_no?.trim()) result.batch_no = data.batch_no.trim()
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.proxy_host?.trim()) result.proxy_host = data.proxy_host.trim()
if (data.proxy_port?.trim())
result.proxy_port = Number(data.proxy_port.trim())
if (data.node_ip?.trim()) result.node_ip = data.node_ip.trim()
if (data.expired_at_start)
result.expired_at_start = new Date(data.expired_at_start)
if (data.expired_at_end)
result.expired_at_end = new Date(data.expired_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Suspense>
<DataTable<Channel>
{...table}
columns={[
{ header: "ID", accessorKey: "id" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "省份", accessorKey: "filter_prov" },
{ header: "城市", accessorKey: "filter_city" },
{
header: "运营商",
accessorKey: "filter_isp",
cell: ({ row }) => {
const value = row.getValue("filter_isp")
if (!value || value === "all") return "不限"
if (value === 1) return "电信"
if (value === 2) return "联通"
if (value === 3) return "移动"
return String(value)
},
},
{
header: "代理地址",
accessorKey: "host",
cell: ({ row }) => {
const ip = row.original.host
const port = row.original.port
return (
<span>
{ip}:{port}{" "}
</span>
)
},
},
{
header: "认证方式",
cell: ({ row }) => {
const channel = row.original
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="batch_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="proxy_host"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel>IP</FieldLabel>
<Input {...field} placeholder="请输入代理IP" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="proxy_port"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入代理端口" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="node_ip"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入节点" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
const hasWhitelist =
channel.whitelists && channel.whitelists.trim() !== ""
const hasAuth = channel.username && channel.password
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
return (
<div className="flex flex-col gap-1 min-w-0">
{hasWhitelist ? (
<div className="flex flex-col">
<span></span>
<div className="flex flex-wrap gap-1 max-w-50">
{channel.whitelists.split(",").map(ip => (
<Badge key={ip.trim()} variant="secondary">
{ip.trim()}
</Badge>
))}
<Suspense>
<DataTable<Channel>
{...table}
columns={[
{
header: "会员号",
accessorFn: row => row.user?.phone || "-",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{
header: "节点",
accessorFn: row => row.ip || row.edge_ref || row.edge_id,
},
{
header: "自动配置",
cell: ({ row }) => {
const prov = row.original.filter_prov
const city = row.original.filter_city
const isp = row.original.filter_isp
const parts = []
if (prov && prov !== "all") parts.push(prov)
if (city && city !== "all") parts.push(city)
if (isp && isp !== "all") {
parts.push(ispMap[Number(isp)] || isp)
}
return (
<div className="text-sm">
{parts.length > 0 ? parts.join(" / ") : "不限"}
</div>
)
},
},
{
header: "网关地址",
accessorKey: "host",
cell: ({ row }) => {
return (
<span>
{row.original.host}:{row.original.port}
</span>
)
},
},
{
header: "认证方式",
cell: ({ row }) => {
const channel = row.original
const hasWhitelist =
channel.whitelists && channel.whitelists.trim() !== ""
const hasAuth = channel.username && channel.password
return (
<div className="flex flex-col gap-1 min-w-0">
{hasWhitelist ? (
<div className="flex flex-col">
<span></span>
<div className="flex flex-wrap gap-1 max-w-50">
{channel.whitelists.split(",").map(ip => (
<Badge key={ip.trim()} variant="secondary">
{ip.trim()}
</Badge>
))}
</div>
</div>
</div>
) : hasAuth ? (
<div className="flex flex-col">
<span></span>
<Badge variant="secondary">
{channel.username}:{channel.password}
</Badge>
</div>
) : (
<span className="text-sm text-gray-400"></span>
)}
</div>
)
) : hasAuth ? (
<div className="flex flex-col">
<span></span>
<Badge variant="secondary">
{channel.username}:{channel.password}
</Badge>
</div>
) : (
<span className="text-sm text-gray-400"></span>
)}
</div>
)
},
},
},
{ header: "资源数量", accessorKey: "resource_id" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
{
header: "过期时间",
accessorKey: "expired_at",
cell: ({ row }) =>
format(new Date(row.original.expired_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
{
header: "过期时间",
accessorKey: "expired_at",
cell: ({ row }) =>
format(new Date(row.original.expired_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,225 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import z from "zod"
import { getBalance } from "@/actions/balance"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { Balance } from "@/models/balance"
type FilterValues = {
user_phone?: string
bill_no?: string
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
phone: z.string().optional(),
bill_no: z.string().optional(),
admin_id: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FormValues = z.infer<typeof filterSchema>
export default function BalancePage() {
const searchParams = useSearchParams()
const router = useRouter()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
bill_no: "",
admin_id: "",
created_at_start: "",
created_at_end: "",
},
})
const table = useDataTable<Balance>((page, size) =>
getBalance({ page, size, user_id: Number(userId), ...filters }),
)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入账单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Balance>
{...table}
columns={[
{
header: "账单号",
accessorFn: row => row.bill?.bill_no || "",
},
{
header: "管理员",
accessorKey: "admin_id",
accessorFn: row => row.admin?.name || "",
},
{
header: "变动金额",
accessorKey: "amount",
cell: ({ row }) => {
const amount = row.original.amount
const isPositive = Number(amount) > 0
return (
<div className="flex items-center gap-1">
<span
className={`font-semibold ${
isPositive ? "text-green-600" : "text-red-600"
}`}
>
{isPositive ? "+" : ""}
{Number(amount).toFixed(2)}
</span>
</div>
)
},
},
{
header: "余额变化",
accessorKey: "balance_prev",
cell: ({ row }) => (
<div className="flex items-center gap-2">
<span className="text-muted-foreground text-sm">
¥{Number(row.original.balance_prev).toFixed(2)}
</span>
<span className="text-muted-foreground"></span>
<span className="font-medium text-foreground">
¥{Number(row.original.balance_curr).toFixed(2)}
</span>
</div>
),
},
{
header: "备注",
accessorKey: "remark",
},
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,271 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getBatch } from "@/actions/batch"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Batch } from "@/models/batch"
type APIFilterParams = {
phone?: string
batch_no?: string
resource_no?: string
prov?: string
city?: string
isp?: string
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
user_phone: z.string().optional(),
resource_no: z.string().optional(),
batch_no: z.string().optional(),
prov: z.string().optional(),
city: z.string().optional(),
isp: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function BatchPage() {
const searchParams = useSearchParams()
const router = useRouter()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const [filters, setFilters] = useState<APIFilterParams>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
resource_no: "",
batch_no: "",
prov: "",
city: "",
isp: "all",
created_at_start: "",
created_at_end: "",
},
})
const table = useDataTable<Batch>((page, size) =>
getBatch({ page, size, user_id: Number(userId), ...filters }),
)
const onFilter = handleSubmit(data => {
const result: APIFilterParams = {}
if (data.user_phone?.trim()) result.phone = data.user_phone.trim()
if (data.batch_no?.trim()) result.batch_no = data.batch_no.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.prov?.trim()) result.prov = data.prov.trim()
if (data.city?.trim()) result.city = data.city.trim()
if (data.isp && data.isp !== "all") result.isp = data.isp
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="batch_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="prov"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入省份" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="city"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入城市" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="isp"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
<SelectItem value="3"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense fallback={<div>Loading...</div>}>
<DataTable<Batch>
{...table}
columns={[
{
header: "会员号",
accessorFn: row => row.user?.phone || "",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{ header: "省份", accessorKey: "prov" },
{ header: "城市", accessorKey: "city" },
{ header: "提取IP", accessorKey: "ip" },
{ header: "运营商", accessorKey: "isp" },
{ header: "提取数量", accessorKey: "count" },
{
header: "提取时间",
accessorKey: "time",
cell: ({ row }) =>
format(new Date(row.original.time), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,461 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CreditCard, Wallet } from "lucide-react"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getBill, getSkuList } from "@/actions/bill"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { ProductCode } from "@/lib/base"
import type { Billing } from "@/models/billing"
type FilterValues = {
bill_no?: string
user_phone?: string
trade_inner_no?: string
resource_no?: string
sku_code?: string
product_code?: string
created_at_start?: Date
created_at_end?: Date
}
type SkuOption = {
resource_code: string
resource_name: string
}
const filterSchema = z
.object({
phone: z
.string()
.optional()
.transform(val => val?.trim()),
bill_no: z
.string()
.optional()
.transform(val => val?.trim()),
resource_no: z.string().optional(),
inner_no: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
product_code: z.string().optional(),
sku_code: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function BillingPage() {
const router = useRouter()
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const [filters, setFilters] = useState<FilterValues>({})
const [skuOptions, setSkuOptions] = useState<SkuOption[]>([])
const [loading, setLoading] = useState(true)
const [skuProductCode, setSkuProductCode] = useState<ProductCode>(
ProductCode.All,
)
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
bill_no: "",
inner_no: "",
created_at_start: "",
created_at_end: "",
phone: "",
resource_no: "",
sku_code: "all",
product_code: "",
},
})
useEffect(() => {
setLoading(true)
getSkuList({
product_code: skuProductCode,
})
.then(resp => {
if (!resp.success) {
throw new Error(resp.message)
}
setSkuOptions(
resp.data.map(sku => ({
resource_code: sku.code,
resource_name: sku.name,
})),
)
})
.catch(e => {
console.error("获取套餐类型失败:", e)
toast.error(
`获取套餐类型失败:${e instanceof Error ? e.message : String(e)}`,
)
setSkuOptions([])
})
.finally(() => {
setLoading(false)
})
}, [skuProductCode])
const table = useDataTable<Billing>((page, size) =>
getBill({ page, size, user_id: Number(userId), ...filters }),
)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone?.trim()) result.user_phone = data.phone.trim()
if (data.inner_no?.trim()) result.trade_inner_no = data.inner_no.trim()
if (data.bill_no?.trim()) result.bill_no = data.bill_no.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.product_code && data.product_code !== ProductCode.All) {
result.product_code = data.product_code
}
if (data.sku_code && data.sku_code !== "all") {
result.sku_code = data.sku_code
}
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="bill_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入账单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="inner_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入订单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="product_code"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Select
value={skuProductCode}
onValueChange={value => {
setSkuProductCode(value as ProductCode)
field.onChange(value)
}}
>
<SelectTrigger>
<SelectValue
placeholder={"请选择"}
defaultValue={
skuProductCode === ProductCode.All ? "全部" : ""
}
/>
</SelectTrigger>
<SelectContent>
<SelectItem value={ProductCode.All}></SelectItem>
<SelectItem value={ProductCode.Short}></SelectItem>
<SelectItem value={ProductCode.Long}></SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
<Controller
name="sku_code"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Select
value={loading ? undefined : field.value || "all"}
onValueChange={field.onChange}
>
<SelectTrigger>
<SelectValue placeholder={loading ? "加载中..." : "全部"} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
{skuOptions.map(option => (
<SelectItem
key={option.resource_code}
value={option.resource_code}
>
{option.resource_name || option.resource_code}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setSkuProductCode(ProductCode.All)
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Billing>
{...table}
columns={[
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{
header: "账单详情",
accessorKey: "info",
cell: ({ row }) => {
const bill = row.original
return (
<div className="flex items-center gap-2">
<div className="shrink-0">
{bill.type === 1 && (
<div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.type === 2 && (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span>退</span>
</div>
)}
{bill.type === 3 && (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
</div>
<div className="text-sm">{bill.info}</div>
</div>
)
},
},
{
header: "应付金额",
accessorKey: "amount",
cell: ({ row }) => {
const amount =
typeof row.original.amount === "string"
? parseFloat(row.original.amount)
: row.original.amount || 0
return (
<div className="flex gap-1">
<span
className={
amount > 0 ? "text-green-500" : "text-orange-500"
}
>
{amount.toFixed(2)}
</span>
</div>
)
},
},
{
header: "实付金额",
accessorKey: "actual",
cell: ({ row }) => {
const actual =
typeof row.original.actual === "string"
? parseFloat(row.original.actual)
: row.original.actual || 0
return (
<div className="flex gap-1">
<span
className={
actual > 0 ? "text-green-500" : "text-orange-500"
}
>
{actual.toFixed(2)}
</span>
</div>
)
},
},
{ header: "账单号", accessorKey: "bill_no" },
{
header: "订单号",
accessorKey: "trade.inner_no",
cell: ({ row }) => {
const bill = row.original
return (
<div className="flex items-center gap-2">
<div className="shrink-0 w-20">
{bill.trade?.acquirer === 1 && (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.trade?.acquirer === 2 && (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{bill.trade?.acquirer === 3 && (
<div className="flex gap-2 items-center bg-orange-50 w-fit px-2 py-1 rounded-md">
<CreditCard size={16} />
<span></span>
</div>
)}
{!bill.trade?.acquirer && (
<div className="flex gap-2 items-center bg-red-50 w-full px-2 py-1 rounded-md">
<Wallet size={16} />
<span></span>
</div>
)}
</div>
<div className="text-sm">{bill.trade?.inner_no}</div>
</div>
)
},
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,329 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getChannel } from "@/actions/channel"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { Channel } from "@/models/channel"
type FilterValues = {
batch_no?: string
user_phone?: string
resource_no?: string
proxy_host?: string
proxy_port?: number
node_ip?: string
expired_at_start?: Date
expired_at_end?: Date
}
const filterSchema = z
.object({
batch_no: z.string().optional(),
user_phone: z.string().optional(),
resource_no: z.string().optional(),
proxy_host: z.string().optional(),
proxy_port: z.string().optional(),
node_ip: z.string().optional(),
expired_at_start: z.string().optional(),
expired_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.expired_at_start && data.expired_at_end) {
const start = new Date(data.expired_at_start)
const end = new Date(data.expired_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["expired_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
const ispMap: Record<number, string> = {
1: "电信",
2: "联通",
3: "移动",
}
export default function ChannelPage() {
const router = useRouter()
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
batch_no: "",
user_phone: "",
resource_no: "",
proxy_port: "",
proxy_host: "",
node_ip: "",
expired_at_start: "",
expired_at_end: "",
},
})
const table = useDataTable<Channel>((page, size) =>
getChannel({ page, size, user_id: Number(userId), ...filters }),
)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.batch_no?.trim()) result.batch_no = data.batch_no.trim()
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.proxy_host?.trim()) result.proxy_host = data.proxy_host.trim()
if (data.proxy_port?.trim())
result.proxy_port = Number(data.proxy_port.trim())
if (data.node_ip?.trim()) result.node_ip = data.node_ip.trim()
if (data.expired_at_start)
result.expired_at_start = new Date(data.expired_at_start)
if (data.expired_at_end)
result.expired_at_end = new Date(data.expired_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="batch_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入批次号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="proxy_host"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel>IP</FieldLabel>
<Input {...field} placeholder="请输入代理IP" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="proxy_port"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-32 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入代理端口" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="node_ip"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入节点" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Channel>
{...table}
columns={[
{
header: "会员号",
accessorFn: row => row.user?.phone || "",
},
{ header: "套餐号", accessorKey: "resource.resource_no" },
{ header: "批次号", accessorKey: "batch_no" },
{
header: "节点",
accessorFn: row => row.ip || row.edge_ref || row.edge_id,
},
{
header: "自动配置",
cell: ({ row }) => {
const prov = row.original.filter_prov
const city = row.original.filter_city
const isp = row.original.filter_isp
const parts = []
if (prov && prov !== "all") parts.push(prov)
if (city && city !== "all") parts.push(city)
if (isp && isp !== "all") {
parts.push(ispMap[Number(isp)] || isp)
}
return (
<div className="text-sm">
{parts.length > 0 ? parts.join(" / ") : "不限"}
</div>
)
},
},
{
header: "网关地址",
accessorKey: "host",
cell: ({ row }) => {
return (
<span>
{row.original.host}:{row.original.port}
</span>
)
},
},
{
header: "认证方式",
cell: ({ row }) => {
const channel = row.original
const hasWhitelist =
channel.whitelists && channel.whitelists.trim() !== ""
const hasAuth = channel.username && channel.password
return (
<div className="flex flex-col gap-1 min-w-0">
{hasWhitelist ? (
<div className="flex flex-col">
<span></span>
<div className="flex flex-wrap gap-1 max-w-50">
{channel.whitelists.split(",").map(ip => (
<Badge key={ip.trim()} variant="secondary">
{ip.trim()}
</Badge>
))}
</div>
</div>
) : hasAuth ? (
<div className="flex flex-col">
<span></span>
<Badge variant="secondary">
{channel.username}:{channel.password}
</Badge>
</div>
) : (
<span className="text-sm text-gray-400"></span>
)}
</div>
)
},
},
{
header: "过期时间",
accessorKey: "expired_at",
cell: ({ row }) =>
format(new Date(row.original.expired_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,339 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { useRouter } from "next/navigation"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getPageUser } from "@/actions/user"
import { UpdateDialog } from "@/app/(root)/cust/update"
import { Auth } from "@/components/auth"
import { DataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
ScopeBalanceActivityReadOfUser,
ScopeBatchReadOfUser,
ScopeBillReadOfUser,
ScopeChannelReadOfUser,
ScopeResourceRead,
ScopeTradeReadOfUser,
ScopeUserWrite,
ScopeUserWriteBalance,
} from "@/lib/scopes"
import type { User } from "@/models/user"
import { AddUserDialog } from "../../cust/create"
interface UserQueryParams {
account?: string
name?: string
}
const filterSchema = z.object({
phone: z.string().optional(),
name: z.string().optional(),
})
type FormValues = z.infer<typeof filterSchema>
export default function UserQueryPage() {
const [userList, setUserList] = useState<User[]>([])
const [loading, setLoading] = useState(false)
const [currentFilters, setCurrentFilters] = useState<UserQueryParams>({})
const router = useRouter()
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
name: "",
},
})
const fetchUsers = useCallback(async (filters: UserQueryParams = {}) => {
setLoading(true)
try {
const res = await getPageUser(filters)
if (res.success) {
const data = Array.isArray(res.data) ? res.data : [res.data]
setUserList(data)
} else {
toast.error(res.message || "获取用户失败")
setUserList([])
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`获取用户失败: ${message}`)
} finally {
setLoading(false)
}
}, [])
const onFilter = handleSubmit((data: FormValues) => {
const params: UserQueryParams = {}
if (data.phone?.trim()) params.account = data.phone.trim()
if (data.name?.trim()) params.name = data.name.trim()
if (Object.keys(params).length === 0) {
toast.info("请至少输入一个搜索条件")
return
}
setCurrentFilters(params)
fetchUsers(params)
})
const refreshTable = useCallback(() => {
if (Object.keys(currentFilters).length > 0) {
fetchUsers(currentFilters)
}
}, [fetchUsers, currentFilters])
const handleReset = () => {
reset()
setCurrentFilters({})
setUserList([])
}
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Auth scope={ScopeUserWrite}>
<AddUserDialog onSuccess={refreshTable} />
</Auth>
<Button type="button" variant="outline" onClick={handleReset}>
</Button>
<Button type="submit"></Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<User>
data={userList || []}
status={loading ? "load" : "done"}
columns={[
{ header: "手机", accessorKey: "phone" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "客户来源",
accessorKey: "source",
cell: ({ row }) => {
const sourceMap: Record<number, string> = {
0: "官网注册",
1: "管理员添加",
2: "代理商注册",
3: "代理商添加",
}
return sourceMap[row.original.source] ?? "官网注册"
},
},
{
header: "余额",
accessorKey: "balance",
cell: ({ row }) => {
const balance = Number(row.original.balance) || 0
return (
<span
className={
balance > 0 ? "text-green-500" : "text-orange-500"
}
>
{balance.toFixed(2)}
</span>
)
},
},
{ header: "账号", accessorKey: "username" },
{
header: "账号状态",
accessorKey: "status",
cell: ({ row }) => (row.original.status === 1 ? "正常" : "禁用"),
},
{
header: "客户经理",
cell: ({ row }) => row.original.admin?.name || "",
},
{ header: "姓名", accessorKey: "name" },
{
header: "实名状态",
accessorKey: "id_type",
cell: ({ row }) => (
<Badge
variant={row.original.id_type === 1 ? "default" : "secondary"}
className={
row.original.id_type === 1
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
}
>
{row.original.id_type === 1 ? "已认证" : "未认证"}
</Badge>
),
},
{
header: "最后登录时间",
accessorKey: "last_login",
cell: ({ row }) =>
row.original.last_login
? format(
new Date(row.original.last_login),
"yyyy-MM-dd HH:mm",
)
: "",
},
{
header: "最后登录IP",
accessorKey: "last_login_ip",
cell: ({ row }) => row.original.last_login_ip || "",
},
{ header: "联系方式", accessorKey: "contact_wechat" },
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => {
return (
<div className="flex flex-wrap gap-2 w-75">
<Auth scope={ScopeUserWriteBalance}>
<UpdateDialog
user={row.original}
onSuccess={refreshTable}
/>
</Auth>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="outline">
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-8">
<Auth scope={ScopeTradeReadOfUser}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/trade?userId=${row.original.id}`,
)
}}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBillReadOfUser}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/billing?userId=${row.original.id}`,
)
}}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeResourceRead}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/resources?userId=${row.original.id}`,
)
}}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBatchReadOfUser}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/batch?userId=${row.original.id}`,
)
}}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeChannelReadOfUser}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/channel?userId=${row.original.id}`,
)
}}
>
IP管理
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBalanceActivityReadOfUser}>
<DropdownMenuItem
onClick={() => {
router.push(
`/client/balance?userId=${row.original.id}&phone=${row.original.phone}`,
)
}}
>
</DropdownMenuItem>
</Auth>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
},
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,583 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format, isBefore, isSameDay } from "date-fns"
import { Box, Loader2, Timer } from "lucide-react"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useCallback, useMemo, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import {
ResourceLong,
ResourceShort,
updateResource,
} from "@/actions/resources"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import type { Resources } from "@/models/resources"
const filterSchema = z
.object({
user_phone: z.string().optional(),
resource_no: z.string().optional(),
status: z.string().optional(),
type: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
expired: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FormValues = z.infer<typeof filterSchema>
interface FilterParams {
user_phone?: string
resource_no?: string
active?: boolean
mode?: number
created_at_start?: Date
created_at_end?: Date
expired?: boolean
}
// 获取资源类型
function getResourceType(resource: Resources): number {
if ("short" in resource && resource.short) {
return resource.short.type
}
if ("long" in resource && resource.long) {
return resource.long.type
}
return resource.type
}
// 获取资源详情对象
function getResourceDetail(resource: Resources) {
if ("short" in resource && resource.short) {
return resource.short
}
if ("long" in resource && resource.long) {
return resource.long
}
return null
}
// 获取过期时间
function getExpireAt(resource: Resources): Date | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.expire_at
}
if ("long" in resource && resource.long) {
return resource.long.expire_at
}
return undefined
}
function getName(resource: Resources): string | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.sku?.name
}
if ("long" in resource && resource.long) {
return resource.long.sku?.name
}
return undefined
}
// 获取最近使用时间
function getLastAt(resource: Resources): Date | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.last_at
}
if ("long" in resource && resource.long) {
return resource.long.last_at
}
return undefined
}
// 资源类型徽章
function ResourceTypeBadge({ resource }: { resource: Resources }) {
const type = getResourceType(resource)
if (type === 1) {
return (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<Timer size={20} />
<span></span>
</div>
)
}
if (type === 2) {
return (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<Box size={20} />
<span></span>
</div>
)
}
return null
}
// 过期徽章
function ExpireBadge({ expireAt }: { expireAt: Date | null | undefined }) {
if (!expireAt) return null
if (isBefore(expireAt, new Date())) {
return <Badge variant="destructive"></Badge>
}
return null
}
// 格式化日期
function formatDateTime(date: Date | null | undefined) {
if (!date) return "-"
return format(date, "yyyy-MM-dd HH:mm")
}
// 计算今日使用量
function getTodayUsage(lastAt: Date | null | undefined, daily: number) {
if (lastAt && isSameDay(lastAt, new Date())) {
return daily
}
return 0
}
export default function ResourcesPage() {
const searchParams = useSearchParams()
const router = useRouter()
const userPhone = searchParams.get("phone")
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<Tabs defaultValue="short">
<TabsList className="bg-card p-1.5 rounded-lg">
<TabsTrigger
value="short"
className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
>
</TabsTrigger>
<TabsTrigger
value="long"
className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
>
</TabsTrigger>
</TabsList>
<TabsContent value="short" className="flex flex-col gap-4">
<ResourceList resourceType="short" />
</TabsContent>
<TabsContent value="long" className="flex flex-col gap-4">
<ResourceList resourceType="long" />
</TabsContent>
</Tabs>
</Page>
)
}
interface ResourceListProps {
resourceType: "long" | "short"
}
function ResourceList({ resourceType }: ResourceListProps) {
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const [filters, setFilters] = useState<FilterParams>({})
const isLong = resourceType === "long"
const listFn = isLong ? ResourceLong : ResourceShort
const [updatingId, setUpdatingId] = useState<number | null>(null)
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
user_phone: "",
resource_no: "",
status: "all",
type: "all",
created_at_start: "",
created_at_end: "",
expired: "all",
},
})
const fetchResources = useCallback(
(page: number, size: number) => {
return listFn({ page, size, user_id: Number(userId), ...filters })
},
[listFn, filters, userId],
)
const table = useDataTable<Resources>(fetchResources)
const refreshTable = useCallback(() => {
setFilters(prev => ({ ...prev }))
}, [])
const handleStatusChange = useCallback(
async (resource: Resources, newStatusValue: string) => {
const newActive = newStatusValue === "0"
if (newActive === resource.active) return
setUpdatingId(resource.id)
try {
await updateResource({
id: resource.id,
active: newActive,
})
toast.success("更新成功", {
description: `资源状态已更新为${newActive ? "启用" : "禁用"}`,
})
refreshTable()
} catch (error) {
console.error("更新状态失败:", error)
toast.error("更新失败", {
description: error instanceof Error ? error.message : "请稍后重试",
})
} finally {
setUpdatingId(null)
}
},
[refreshTable],
)
const onFilter = handleSubmit(data => {
const result: FilterParams = {}
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.status && data.status !== "all") {
result.active = data.status === "0"
}
if (data.type && data.type !== "all") {
result.mode = Number(data.type)
}
if (data.expired && data.expired !== "all") {
result.expired = data.expired === "1"
}
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
const columns = useMemo(
() => [
{
header: "会员号",
accessorFn: (row: Resources) => row.user?.phone || "-",
},
{
header: "套餐",
cell: ({ row }: { row: { original: Resources } }) => {
const resourceNo = row.original.resource_no
const name = getName(row.original)
const expireAt = getExpireAt(row.original)
return (
<div className="flex flex-col gap-1">
<div>{name}</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">{resourceNo}</span>
<ExpireBadge expireAt={expireAt} />
</div>
</div>
)
},
},
{
header: "类型",
cell: ({ row }: { row: { original: Resources } }) => {
return <ResourceTypeBadge resource={row.original} />
},
},
{
header: "IP时效",
cell: ({ row }: { row: { original: Resources } }) => {
const detail = getResourceDetail(row.original)
const live = detail?.live
if (live === undefined) return "-"
return <span>{isLong ? `${live}小时` : `${live}分钟`}</span>
},
},
{
header: "使用情况",
cell: ({ row }: { row: { original: Resources } }) => {
const detail = getResourceDetail(row.original)
const type = getResourceType(row.original)
if (!detail) return <span>-</span>
if (type === 1) {
// 包时
const todayUsage = getTodayUsage(detail.last_at, detail.daily || 0)
return (
<div className="flex gap-1">
<span>
{todayUsage}/{detail.quota}
</span>
</div>
)
} else {
// 包量
if (isLong) {
return (
<div className="flex gap-1">
{detail.used < detail.quota ? (
<span className="text-green-500"></span>
) : (
<span className="text-red-500"></span>
)}
<span>|</span>
<span>
{detail.used}/{detail.quota}
</span>
</div>
)
} else {
return (
<div className="flex gap-1">
<span>
{detail.used}/{detail.quota}
</span>
</div>
)
}
}
},
},
{
header: "最近使用时间",
cell: ({ row }: { row: { original: Resources } }) => {
const lastAt = getLastAt(row.original)
return lastAt ? formatDateTime(lastAt) : "暂未使用"
},
},
{
header: "开通时间",
cell: ({ row }: { row: { original: Resources } }) => {
return formatDateTime(row.original.created_at)
},
},
...(!isLong
? [
{
header: "到期时间",
cell: ({ row }: { row: { original: Resources } }) => {
return formatDateTime(getExpireAt(row.original))
},
},
]
: []),
{
id: "action",
meta: { pin: "right" },
header: "状态",
cell: ({ row }: { row: { original: Resources } }) => {
const resource = row.original
const isLoading = updatingId === resource.id
const currentActive = resource.active
return (
<div className="flex items-center gap-2">
<Select
value={currentActive ? "0" : "1"}
onValueChange={val => handleStatusChange(resource, val)}
disabled={isLoading}
>
<SelectTrigger className="min-w-20">
<SelectValue placeholder="状态" />
</SelectTrigger>
<SelectContent className="min-w-(--radix-select-trigger-width)">
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
{isLoading && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
)}
</div>
)
},
},
],
[isLong, updatingId, handleStatusChange],
)
return (
<div className="space-y-3">
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="type"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense fallback={<div className="text-center p-4">...</div>}>
<DataTable<Resources> {...table} columns={columns} />
</Suspense>
</div>
)
}

View File

@@ -0,0 +1,363 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CheckCircle, Clock, XCircle } from "lucide-react"
import { useRouter, useSearchParams } from "next/navigation"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getTrade } from "@/actions/trade"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Trade } from "@/models/trade"
type FilterValues = {
inner_no?: string
method?: number
platform?: number
status?: number
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
inner_no: z
.string()
.optional()
.transform(val => val?.trim()),
method: z.string().optional(),
platform: z.string().optional(),
status: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function TradePage() {
const router = useRouter()
const searchParams = useSearchParams()
const userId = searchParams.get("userId")
const userPhone = searchParams.get("phone")
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
inner_no: "",
method: "all",
platform: "all",
status: "all",
created_at_start: "",
created_at_end: "",
},
})
const fetchTrades = useCallback(
async (page: number, size: number) => {
return getTrade({ page, size, user_id: Number(userId), ...filters })
},
[filters, userId],
)
const table = useDataTable<Trade>(fetchTrades)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.inner_no?.trim()) result.inner_no = data.inner_no.trim()
if (data.method && data.method !== "all")
result.method = Number(data.method)
if (data.platform && data.platform !== "all")
result.platform = Number(data.platform)
if (data.status && data.status !== "all")
result.status = Number(data.status)
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Page>
<div>
<Button
onClick={() => {
router.back()
}}
className="gap-2"
>
</Button>
<span className="ml-2 text-gray-600">: {userPhone}</span>
</div>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="inner_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入订单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="method"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
<SelectItem value="3"></SelectItem>
<SelectItem value="4"></SelectItem>
<SelectItem value="5"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="platform"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Trade>
{...table}
columns={[
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "订单号",
accessorKey: "inner_no",
},
{ header: "购买套餐", accessorKey: "subject" },
{
header: "支付金额",
accessorKey: "payment",
cell: ({ row }) => {
const payment =
typeof row.original.payment === "string"
? parseFloat(row.original.payment)
: row.original.payment || 0
return (
<div className="flex gap-1">
<span
className={
payment > 0 ? "text-green-500" : "text-orange-500"
}
>
{payment.toFixed(2)}
</span>
</div>
)
},
},
{
header: "支付状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
switch (status) {
case 0:
return (
<div className="flex items-center gap-2 text-yellow-600">
<Clock className="h-4 w-4" />
<span></span>
</div>
)
case 1:
return (
<div className="flex items-center gap-2 text-green-600">
<CheckCircle className="h-4 w-4" />
<span></span>
</div>
)
case 2:
return (
<div className="flex items-center gap-2 text-gray-500">
<XCircle className="h-4 w-4" />
<span></span>
</div>
)
default:
return <span className="text-gray-400">-</span>
}
},
},
{
header: "支付平台",
accessorKey: "platform",
cell: ({ row }) => {
const platform = row.original.platform
if (!platform) return <span>-</span>
return platform === 1
? "电脑网站"
: platform === 2
? "手机网站"
: "-"
},
},
{
header: "支付渠道",
accessorKey: "method",
cell: ({ row }) => {
const methodMap: Record<number, string> = {
1: "支付宝",
2: "微信",
3: "商福通",
4: "商福通渠道支付宝",
5: "商福通渠道微信",
}
return (
<div>
{methodMap[row.original.method as number] || "未知"}
</div>
)
},
},
{
header: "渠道订单号",
accessorKey: "outer_no",
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,202 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { Plus } from "lucide-react"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createCoupon } from "@/actions/coupon"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
const schema = z.object({
code: z.string().min(1, "请输入优惠券名称"),
amount: z.string().min(1, "请输入优惠券金额"),
remark: z.string().optional(),
min_amount: z.string().optional(),
expire_at: z.string().optional(),
})
export function CreateDiscount(props: { onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: "",
remark: "",
amount: "0",
min_amount: "0",
expire_at: "",
},
mode: "onChange",
})
const { control, handleSubmit, reset } = form
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const payload = {
code: data.code,
amount: Number(data.amount),
remark: data?.remark,
min_amount: Number(data?.min_amount),
expire_at: data?.expire_at ? new Date(data.expire_at) : undefined,
}
const resp = await createCoupon(payload)
if (resp.success) {
reset()
toast.success("优惠券创建成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
return (
<Dialog
open={open}
onOpenChange={newOpen => {
setOpen(newOpen)
if (!newOpen) {
reset()
}
}}
>
<DialogTrigger asChild>
<Button>
<Plus />
</Button>
</DialogTrigger>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="discount-create" onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={control}
name="code"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="remark"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="min_amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="expire_at"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-30 pt-2">:</FieldLabel>
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<div className="flex-1">
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="discount-create">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,150 @@
"use client"
import { format } from "date-fns"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { deleteCoupon, getPagCoupon } from "@/actions/coupon"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import type { Coupon } from "@/models/coupon"
import { CreateDiscount } from "./create"
import { UpdateCoupon } from "./update"
export default function CouponPage() {
const table = useDataTable((page, size) => getPagCoupon({ page, size }))
return (
<Page>
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreateDiscount onSuccess={table.refresh} />
</div>
</div>
<Suspense>
<DataTable<Coupon>
{...table}
columns={[
{ header: "所属用户", accessorKey: "user_id" },
{ header: "代码", accessorKey: "code" },
{ header: "备注", accessorKey: "remark" },
{ header: "金额", accessorKey: "amount" },
{ header: "最低消费金额", accessorKey: "min_amount" },
{
header: "状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
if (status === 0) {
return <span className="text-yellow-600">使</span>
}
if (status === 1) {
return <span className="text-green-600">使</span>
}
return <span>-</span>
},
},
{
header: "过期时间",
accessorKey: "expire_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<UpdateCoupon
coupon={row.original}
onSuccess={table.refresh}
/>
<DeleteCoupon
coupon={row.original}
onSuccess={table.refresh}
/>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}
function DeleteCoupon({
coupon,
onSuccess,
}: {
coupon: Coupon
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await deleteCoupon(coupon.id)
if (resp.success) {
toast.success("删除成功")
onSuccess?.()
} else {
toast.error(resp.message ?? "删除失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{coupon.code}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -0,0 +1,247 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { updateCoupon } from "@/actions/coupon"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Coupon } from "@/models/coupon"
const schema = z.object({
code: z.string().min(1, "请输入优惠券名称"),
amount: z.string().min(1, "请输入优惠券金额"),
remark: z.string().optional(),
min_amount: z.string().optional(),
expire_at: z.string().optional(),
status: z.string().optional(),
})
export function UpdateCoupon(props: {
coupon: Coupon
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: props.coupon.code || "",
remark: props.coupon.remark || "",
amount: String(props.coupon.amount || 0),
min_amount: String(props.coupon.min_amount || 0),
expire_at: props.coupon.expire_at
? new Date(props.coupon.expire_at).toISOString().split("T")[0]
: "",
status: String(props.coupon.status || "0"),
},
mode: "onChange",
})
const { control, handleSubmit, reset } = form
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const payload = {
id: props.coupon.id,
code: data.code,
amount: Number(data.amount),
remark: data.remark,
min_amount: Number(data.min_amount),
expire_at: data.expire_at ? new Date(data.expire_at) : undefined,
status: Number(data.status),
}
const resp = await updateCoupon(payload)
if (resp.success) {
toast.success("优惠券修改成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
reset({
code: props.coupon.code || "",
remark: props.coupon.remark || "",
amount: String(props.coupon.amount || 0),
min_amount: String(props.coupon.min_amount || 0),
expire_at: props.coupon.expire_at
? new Date(props.coupon.expire_at).toISOString().split("T")[0]
: "",
status: String(props.coupon.status || "0"),
})
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="coupon-update" onSubmit={handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={control}
name="code"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="remark"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="min_amount"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="number"
min={0}
step={5}
{...field}
onChange={e => {
const value = e.target.value
if (value === "" || parseFloat(value) >= 0) {
field.onChange(value)
}
}}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="expire_at"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Input
type="date"
min={new Date().toISOString().split("T")[0]}
{...field}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
<Controller
control={control}
name="status"
render={({ field, fieldState }) => (
<div className="flex items-start gap-4">
<FieldLabel className="w-28 pt-2">:</FieldLabel>
<div className="flex-1">
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value="0">使</SelectItem>
<SelectItem value="1">使</SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</div>
</div>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="coupon-update">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,410 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getAllAdmin } from "@/actions/admin"
import { createCust } from "@/actions/cust"
import { getAllProductDiscount } from "@/actions/product_discount"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Admin } from "@/models/admin"
import type { ProductDiscount } from "@/models/product_discount"
// 表单验证规则
const addUserSchema = z
.object({
username: z.string().optional(),
password: z
.string()
.optional()
.refine(val => !val || val.length >= 6, { message: "密码至少6位" }),
confirmPassword: z.string().optional(),
phone: z.string().regex(/^1[3-9]\d{9}$/, "请输入正确的手机号格式"),
email: z
.string()
.email("请输入正确的邮箱格式")
.optional()
.or(z.literal("")),
name: z.string().optional(),
admin_id: z.string().optional(),
discount_id: z.string().optional(),
source: z.string().optional(),
avatar: z.string().optional(),
status: z.string().optional(),
contact_qq: z.string().optional(),
contact_wechat: z.string().optional(),
})
.refine(
data => {
if (data.password) {
return data.password === data.confirmPassword
}
return true
},
{
message: "两次输入的密码不一致",
path: ["confirmPassword"],
},
)
export type AddUserFormValues = z.infer<typeof addUserSchema>
interface AddUserDialogProps {
onSuccess?: () => void
}
export function AddUserDialog({ onSuccess }: AddUserDialogProps) {
const [open, setOpen] = useState(false)
const [isAdding, setIsAdding] = useState(false)
const [discountList, setDiscountList] = useState<ProductDiscount[]>([])
const [isLoadingDiscount, setIsLoadingDiscount] = useState(false)
const [adminList, setAdminList] = useState<Admin[]>([])
const [isLoadingAdmin, setIsLoadingAdmin] = useState(false)
const {
control,
handleSubmit,
reset: resetAddForm,
} = useForm<AddUserFormValues>({
resolver: zodResolver(addUserSchema),
defaultValues: {
username: "",
password: "",
confirmPassword: "",
phone: "",
email: "",
name: "",
admin_id: "",
discount_id: "",
avatar: "",
status: "1",
contact_qq: "",
contact_wechat: "",
},
})
const statusOptions = [
{ value: "0", label: "禁用" },
{ value: "1", label: "正常" },
]
const fetchDiscountList = useCallback(async () => {
setIsLoadingDiscount(true)
try {
const res = await getAllProductDiscount()
if (res.success) {
setDiscountList(res.data || [])
} else {
toast.error(res.message || "获取折扣失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`获取折扣失败: ${message}`)
} finally {
setIsLoadingDiscount(false)
}
}, [])
const fetchAdminList = useCallback(async () => {
setIsLoadingAdmin(true)
try {
const res = await getAllAdmin()
if (res.success) {
setAdminList(res.data || [])
} else {
toast.error(res.message || "获取管理员失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`获取管理员失败: ${message}`)
} finally {
setIsLoadingAdmin(false)
}
}, [])
useEffect(() => {
if (open) {
fetchDiscountList()
fetchAdminList()
}
}, [open, fetchDiscountList, fetchAdminList])
const onSubmit = handleSubmit(async data => {
const payload = {
phone: data.phone,
username: data?.username,
password: data?.password,
email: data?.email || "",
name: data?.name,
admin_id: data.admin_id ? Number(data.admin_id) : undefined,
discount_id: data.discount_id ? Number(data.discount_id) : undefined,
avatar: data?.avatar,
status: data.status ? parseInt(data?.status) : 1,
contact_qq: data?.contact_qq,
contact_wechat: data?.contact_wechat,
}
setIsAdding(true)
try {
const result = await createCust(payload)
if (result?.success) {
toast.success("添加用户成功")
setOpen(false)
resetAddForm()
onSuccess?.()
} else {
toast.error(result?.message || "添加失败")
}
} catch (error) {
toast.error("添加失败,请稍后重试")
console.error(error)
} finally {
setIsAdding(false)
}
})
const handleOpenChange = (open: boolean) => {
if (!open) {
resetAddForm()
}
setOpen(open)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button type="button"></Button>
</DialogTrigger>
<DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form onSubmit={onSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<Controller
name="username"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input
{...field}
placeholder="请输入用户名"
autoComplete="off"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel> *</FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
name="password"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel>
<span className="text-gray-400 text-xs"></span>
</FieldLabel>
<Input
{...field}
type="password"
placeholder="请输入密码至少6位"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="confirmPassword"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input
{...field}
type="password"
placeholder="请再次输入密码"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
name="email"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入邮箱" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择用户状态" />
</SelectTrigger>
<SelectContent>
{statusOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
name="contact_qq"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel>QQ联系方式</FieldLabel>
<Input {...field} placeholder="请输入QQ联系方式" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="contact_wechat"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel>/</FieldLabel>
<Input {...field} placeholder="请输入微信或联系方式" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<Controller
name="discount_id"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select
value={field.value}
onValueChange={field.onChange}
disabled={isLoadingDiscount}
>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择折扣" />
</SelectTrigger>
<SelectContent>
{discountList.map(discount => (
<SelectItem
key={discount.id}
value={discount.id.toString()}
>
{discount.name}{discount.discount}%
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="admin_id"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select
disabled={isLoadingAdmin}
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger className="w-full h-9">
<SelectValue
placeholder={
isLoadingAdmin ? "加载中..." : "请选择管理员"
}
/>
</SelectTrigger>
<SelectContent>
{adminList.map(admin => (
<SelectItem key={admin.id} value={admin.id.toString()}>
{admin.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-end gap-2 pt-2">
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
>
</Button>
<Button type="submit" disabled={isAdding}>
{isAdding ? "添加中..." : "确定添加"}
</Button>
</FieldGroup>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,144 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getDeduction } from "@/actions/cust"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { User } from "@/models/user"
const Schema = z.object({
deduction: z
.string()
.min(1, "请输入扣款金额")
.refine(val => !Number.isNaN(Number(val)), "请输入有效的数字")
.refine(val => Number(val) >= 0, "金额不能为负数"),
})
type FormValues = z.infer<typeof Schema>
interface UpdateDeductionDialogProps {
user: User
onSuccess: () => void
}
export function DeductionDialog({
user,
onSuccess,
}: UpdateDeductionDialogProps) {
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const {
register,
handleSubmit,
reset,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(Schema),
defaultValues: {
deduction: "",
},
})
const onSubmit = async (data: FormValues) => {
setIsLoading(true)
try {
const result = await getDeduction({
user_id: user.id,
amount: data.deduction,
})
if (result.success) {
toast.success("扣款成功")
setOpen(false)
reset()
onSuccess()
} else {
toast.error(result.message || "扣款失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`网络错误,请稍后重试: ${message}`)
} finally {
setIsLoading(false)
}
}
const handleOpenChange = (open: boolean) => {
if (!open) {
reset()
}
setOpen(open)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm"></Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
{user.name || user.username}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-4 py-4">
<Field data-invalid={!!errors.deduction}>
<FieldLabel></FieldLabel>
<Input
type="text"
placeholder="请输入扣款金额"
{...register("deduction")}
onInput={(e: React.ChangeEvent<HTMLInputElement>) => {
let value = e.target.value
value = value.replace(/[^\d.]/g, "")
const dotCount = (value.match(/\./g) || []).length
if (dotCount > 1) {
value = value.slice(0, value.lastIndexOf("."))
}
if (value.includes(".")) {
const [int, dec] = value.split(".")
value = `${int}.${dec.slice(0, 2)}`
}
setValue("deduction", value)
}}
/>
<FieldError>{errors.deduction?.message}</FieldError>
</Field>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "保存中" : "保存"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,141 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getDeposit } from "@/actions/cust"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { User } from "@/models/user"
const Schema = z.object({
deposit: z
.string()
.min(1, "请输入余额")
.refine(val => !Number.isNaN(Number(val)), "请输入有效的数字")
.refine(val => Number(val) >= 0, "余额不能为负数"),
})
type FormValues = z.infer<typeof Schema>
interface UpdateDepositDialogProps {
user: User
onSuccess: () => void
}
export function DepositDialog({ user, onSuccess }: UpdateDepositDialogProps) {
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const {
register,
handleSubmit,
reset,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(Schema),
defaultValues: {
deposit: "",
},
})
const onSubmit = async (data: FormValues) => {
setIsLoading(true)
try {
const result = await getDeposit({
user_id: user.id,
amount: data.deposit,
})
if (result.success) {
toast.success("充值成功")
setOpen(false)
reset()
onSuccess()
} else {
toast.error(result.message || "充值失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`网络错误,请稍后重试: ${message}`)
} finally {
setIsLoading(false)
}
}
const handleOpenChange = (open: boolean) => {
if (!open) {
reset()
}
setOpen(open)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm"></Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogDescription>
{user?.name || user?.username}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-4 py-4">
<Field data-invalid={!!errors.deposit}>
<FieldLabel></FieldLabel>
<Input
type="text"
placeholder="请输入充值金额"
{...register("deposit")}
onInput={(e: React.ChangeEvent<HTMLInputElement>) => {
let value = e.target.value
value = value.replace(/[^\d.]/g, "")
const dotCount = (value.match(/\./g) || []).length
if (dotCount > 1) {
value = value.slice(0, value.lastIndexOf("."))
}
if (value.includes(".")) {
const [int, dec] = value.split(".")
value = `${int}.${dec.slice(0, 2)}`
}
setValue("deposit", value)
}}
/>
<FieldError>{errors.deposit?.message}</FieldError>
</Field>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "保存中" : "保存"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,476 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { useRouter } from "next/navigation"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getPageCusts } from "@/actions/cust"
import { Auth } from "@/components/auth"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
ScopeBalanceActivityReadOfUser,
ScopeBatchReadOfUser,
ScopeBillReadOfUser,
ScopeChannelReadOfUser,
ScopeResourceRead,
ScopeTradeReadOfUser,
ScopeUserWrite,
ScopeUserWriteBalance,
ScopeUserWriteBalanceDec,
ScopeUserWriteBalanceInc,
} from "@/lib/scopes"
import type { User } from "@/models/user"
import { AddUserDialog } from "./create"
import { DeductionDialog } from "./deduction"
import { DepositDialog } from "./deposit"
import { UpdateDialog } from "./update"
type FilterValues = {
account?: string
name?: string
identified?: boolean
enabled?: boolean
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
account: z.string().optional(),
name: z.string().optional(),
identified: z.string().optional(),
enabled: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FormValues = z.infer<typeof filterSchema>
export default function CustPage() {
const [filters, setFilters] = useState<FilterValues>({})
const router = useRouter()
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
account: "",
name: "",
identified: "all",
enabled: "all",
created_at_start: "",
created_at_end: "",
},
})
const fetchUsers = useCallback(
(page: number, size: number) => getPageCusts({ page, size, ...filters }),
[filters],
)
const table = useDataTable<User>(fetchUsers)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.account?.trim()) result.account = data.account.trim()
if (data.name?.trim()) result.name = data.name.trim()
if (data.identified && data.identified !== "all")
result.identified = data.identified === "1"
if (data.enabled && data.enabled !== "all")
result.enabled = data.enabled === "1"
setFilters(result)
table.pagination.onPageChange(1)
})
const refreshTable = useCallback(() => {
table.refresh()
}, [table])
return (
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="account"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-80 flex-none"
>
<FieldLabel>//</FieldLabel>
<Input {...field} placeholder="请输入账号/手机号/邮箱" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="name"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入姓名" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="identified"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-24">
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="0"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="enabled"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="0"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Auth scope={ScopeUserWrite}>
<AddUserDialog onSuccess={refreshTable} />
</Auth>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
<Button type="submit"></Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<User>
{...table}
classNames={{ root: "flex-auto overflow-hidden" }}
columns={[
{ header: "手机", accessorKey: "phone" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
// { header: "邮箱", accessorKey: "email" },
{
header: "客户来源",
accessorKey: "source",
cell: ({ row }) => {
const sourceMap: Record<number, string> = {
0: "官网注册",
1: "管理员添加",
2: "代理商注册",
3: "代理商添加",
}
return sourceMap[row.original.source] ?? "官网注册"
},
},
{
header: "余额",
accessorKey: "balance",
cell: ({ row }) => {
const balance = Number(row.original.balance) || 0
return (
<span
className={
balance > 0 ? "text-green-500" : "text-orange-500"
}
>
{balance.toFixed(2)}
</span>
)
},
},
{ header: "账号", accessorKey: "username" },
{
header: "账号状态",
accessorKey: "status",
cell: ({ row }) => (row.original.status === 1 ? "正常" : "禁用"),
},
{ header: "客户经理", accessorKey: "admin.name" },
{ header: "姓名", accessorKey: "name" },
{
header: "身份证号",
accessorKey: "id_no",
cell: ({ row }) => {
const idNo = row.original.id_no
return idNo ? `${idNo.slice(0, 6)}****${idNo.slice(-4)}` : ""
},
},
{
header: "实名状态",
accessorKey: "id_type",
cell: ({ row }) => (
<Badge
variant={row.original.id_type === 1 ? "default" : "secondary"}
className={
row.original.id_type === 1
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
}
>
{row.original.id_type === 1 ? "已认证" : "未认证"}
</Badge>
),
},
{
header: "最后登录时间",
accessorKey: "last_login",
cell: ({ row }) =>
row.original.last_login
? format(
new Date(row.original.last_login),
"yyyy-MM-dd HH:mm",
)
: "",
},
{
header: "最后登录IP",
accessorKey: "last_login_ip",
cell: ({ row }) => row.original.last_login_ip || "",
},
{ header: "折扣", accessorKey: "discount.name" },
{
header: "联系方式",
cell: ({ row }) => {
const qq = row.original.contact_qq || ""
const wechat = row.original.contact_wechat || ""
const hasQQ = qq.trim() !== ""
const hasWechat = wechat.trim() !== ""
if (!hasQQ && !hasWechat) return null
return (
<div className="space-y-1">
{hasWechat && <div>{wechat}</div>}
{hasQQ && <div>QQ{qq}</div>}
</div>
)
},
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => {
const user = row.original
return (
<div className="flex gap-2">
<Auth scope={ScopeUserWriteBalanceInc}>
<DepositDialog
user={row.original}
onSuccess={refreshTable}
/>
</Auth>
<Auth scope={ScopeUserWriteBalanceDec}>
<DeductionDialog
user={row.original}
onSuccess={refreshTable}
/>
</Auth>
<Auth scope={ScopeUserWriteBalance}>
<UpdateDialog
user={row.original}
onSuccess={refreshTable}
/>
</Auth>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="sm" variant="outline">
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-8">
<Auth scope={ScopeTradeReadOfUser}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/trade?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBillReadOfUser}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/billing?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeResourceRead}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/resources?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBatchReadOfUser}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/batch?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeChannelReadOfUser}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/channel?userId=${user.id}&phone=${user.phone}`,
)
}
>
IP管理
</DropdownMenuItem>
</Auth>
<Auth scope={ScopeBalanceActivityReadOfUser}>
<DropdownMenuItem
onClick={() =>
router.push(
`/client/balance?userId=${user.id}&phone=${user.phone}`,
)
}
>
</DropdownMenuItem>
</Auth>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
},
},
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -0,0 +1,385 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { getAllAdmin } from "@/actions/admin"
import { updateCust } from "@/actions/cust"
import { getAllProductDiscount } from "@/actions/product_discount"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Admin } from "@/models/admin"
import type { ProductDiscount } from "@/models/product_discount"
import type { User } from "@/models/user"
// 表单验证规则
const editUserSchema = z
.object({
id: z.number(),
username: z.string().optional(),
email: z.string().email("邮箱格式不正确").optional().or(z.literal("")),
password: z.string().optional(),
confirmPassword: z.string().optional(),
admin_id: z.string().optional(),
discount_id: z.string().optional(),
status: z.string().optional(),
contact_qq: z.string().optional(),
contact_wechat: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.password && data.password.length < 6) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "密码至少6位",
path: ["password"],
})
}
if (data.password && data.password !== data.confirmPassword) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "两次输入的密码不一致",
path: ["confirmPassword"],
})
}
})
export type EditUserFormValues = z.infer<typeof editUserSchema>
interface EditUserDialogProps {
user: User
onSuccess: () => void
}
export function UpdateDialog({ user, onSuccess }: EditUserDialogProps) {
const [open, setOpen] = useState(false)
const [admins, setAdmins] = useState<Admin[]>([])
const [discounts, setDiscounts] = useState<ProductDiscount[]>([])
const [isSubmitting, setIsSubmitting] = useState(false)
// 表单
const { control, handleSubmit, reset } = useForm<EditUserFormValues>({
resolver: zodResolver(editUserSchema),
defaultValues: {
id: 0,
username: "",
email: "",
password: "",
confirmPassword: "",
admin_id: "",
discount_id: "",
status: "",
contact_qq: "",
contact_wechat: "",
},
})
useEffect(() => {
const loadOptions = async () => {
try {
const [adminRes, discountRes] = await Promise.all([
getAllAdmin(),
getAllProductDiscount(),
])
if (adminRes.success) {
setAdmins(adminRes.data)
} else {
toast.error(adminRes.message || "获取管理员失败")
setAdmins([])
}
if (discountRes.success) {
setDiscounts(discountRes.data)
} else {
toast.error(discountRes.message || "获取折扣方案失败")
setDiscounts([])
}
} catch (error) {
const message = error instanceof Error ? error.message : "加载数据失败"
toast.error(message)
}
}
if (open) {
loadOptions()
}
}, [open])
useEffect(() => {
if (open) {
reset({
id: user.id,
username: user.username,
email: user.email || "",
password: "",
confirmPassword: "",
admin_id: user.admin_id ? String(user.admin_id) : "",
discount_id: user.discount_id ? String(user.discount_id) : "",
status: user.status !== undefined ? String(user.status) : "",
contact_qq: user.contact_qq || "",
contact_wechat: user.contact_wechat || "",
})
}
}, [open, user, reset])
const onSubmit = async (data: EditUserFormValues) => {
setIsSubmitting(true)
try {
const updateData: {
id: number
username?: string
email?: string
password?: string
admin_id?: number
discount_id?: number
status?: number
contact_qq?: string
contact_wechat?: string
} = { id: data.id }
if (data.username && data.username.trim() !== "") {
updateData.username = data.username.trim()
}
if (data.email && data.email.trim() !== "") {
updateData.email = data.email.trim()
}
if (data.password && data.password.trim() !== "") {
updateData.password = data.password
}
if (data.admin_id && data.admin_id !== "") {
updateData.admin_id = Number(data.admin_id)
}
if (data.discount_id && data.discount_id !== "") {
updateData.discount_id = Number(data.discount_id)
}
if (data.status && data.status !== "") {
updateData.status = Number(data.status)
}
if (data.contact_qq !== undefined) {
updateData.contact_qq = data.contact_qq
}
if (data.contact_wechat !== undefined) {
updateData.contact_wechat = data.contact_wechat
}
const result = await updateCust(updateData)
if (result?.success) {
toast.success("修改成功")
setOpen(false)
onSuccess()
} else {
toast.error(result?.message || "修改失败")
}
} catch (error) {
console.error("修改用户失败:", error)
const message =
error instanceof Error ? error.message : "修改失败,请稍后重试"
toast.error(`修改失败:${message}`)
} finally {
setIsSubmitting(false)
}
}
const handleOpenChange = (open: boolean) => {
if (!open) {
reset()
}
setOpen(open)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm"></Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-2">
<div className="grid grid-cols-2 gap-4">
<Controller
name="username"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入用户名" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="email"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入邮箱" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="password"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input
{...field}
type="password"
placeholder="选填,修改请输入新密码至少6位"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="confirmPassword"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Input
{...field}
type="password"
placeholder="请再次输入密码"
/>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择账号状态" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1"></SelectItem>
<SelectItem value="0"></SelectItem>
</SelectContent>
</Select>
</Field>
)}
/>
<Controller
name="admin_id"
control={control}
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择客户经理" />
</SelectTrigger>
<SelectContent>
{admins.map(admin => (
<SelectItem key={admin.id} value={admin.id.toString()}>
{admin.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
/>
<Controller
name="discount_id"
control={control}
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="请选择折扣方案" />
</SelectTrigger>
<SelectContent>
{discounts.map(discount => (
<SelectItem
key={discount.id}
value={discount.id.toString()}
>
{discount.name}{discount.discount}%
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
/>
<Controller
name="contact_qq"
control={control}
render={({ field }) => (
<Field>
<FieldLabel>QQ</FieldLabel>
<Input {...field} placeholder="QQ号" />
</Field>
)}
/>
<Controller
name="contact_wechat"
control={control}
render={({ field }) => (
<Field>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="微信号" />
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-end gap-2 pt-2">
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
disabled={isSubmitting}
>
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "提交中..." : "确认修改"}
</Button>
</FieldGroup>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,122 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createProductDiscount } from "@/actions/product_discount"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
const schema = z.object({
name: z.string().min(1, "请输入折扣名称"),
discount: z.string().min(1, "请输入折扣代码"),
})
export function CreateDiscount(props: { onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
name: "",
discount: "",
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await createProductDiscount(data)
if (resp.success) {
form.reset()
toast.success("折扣创建成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="discount-create" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="discount-create-name"></FieldLabel>
<Input
id="discount-create-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="discount"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="discount-create-discount">
</FieldLabel>
<Input
id="discount-create-discount"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="discount-create">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,134 @@
"use client"
import { format } from "date-fns"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import {
deleteProductDiscount,
getPageProductDiscount,
} from "@/actions/product_discount"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import type { ProductDiscount } from "@/models/product_discount"
import { CreateDiscount } from "./create"
import { UpdateDiscount } from "./update"
export default function DiscountPage() {
const table = useDataTable((page, size) =>
getPageProductDiscount({ page, size }),
)
return (
<Page>
{/* 操作栏 */}
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreateDiscount onSuccess={table.refresh} />
</div>
</div>
{/* 数据表 */}
<Suspense>
<DataTable<ProductDiscount>
{...table}
columns={[
{ header: "名称", accessorKey: "name" },
{ header: "折扣", accessorKey: "discount" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<UpdateDiscount
discount={row.original}
onSuccess={table.refresh}
/>
<DeleteButton
discount={row.original}
onSuccess={table.refresh}
/>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}
function DeleteButton({
discount,
onSuccess,
}: {
discount: ProductDiscount
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await deleteProductDiscount(discount.id)
if (resp.success) {
toast.success("删除成功")
onSuccess?.()
} else {
toast.error(resp.message ?? "删除失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{discount.name}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -0,0 +1,140 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { updateProductDiscount } from "@/actions/product_discount"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import type { ProductDiscount } from "@/models/product_discount"
const schema = z.object({
name: z.string().min(1, "请输入折扣名称"),
discount: z.string().min(1, "请输入折扣代码"),
})
export function UpdateDiscount(props: {
discount: ProductDiscount
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
name: props.discount.name,
discount: String(props.discount.discount),
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await updateProductDiscount({
id: props.discount.id,
...data,
})
if (resp.success) {
toast.success("折扣修改成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
form.reset({
name: props.discount.name,
discount: String(props.discount.discount),
})
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="discount-update" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="discount-update-name"></FieldLabel>
<Input
id="discount-update-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="discount"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="discount-update-discount">
</FieldLabel>
<Input
id="discount-update-discount"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="discount-update">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,245 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import z from "zod"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { toast } from "sonner"
import { createGateway } from "@/actions/gateway"
const schema = z.object({
mac: z.string().regex(/^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/, {
message: "MAC地址格式不正确请使用如 00:11:22:AA:BB:CC 或 00-11-22-AA-BB-CC 的格式"
}),
ip: z.string().regex(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, {
message: "IP地址格式不正确请使用如 192.168.1.1 的格式"
}),
host: z.string().regex(/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/, {
message: "域名格式不正确,请使用如 example.com 的格式"
}).or(z.literal("")),
type: z.string().optional(),
status: z.string().optional(),
})
export default function CreatePage(props: { onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
mac: "",
ip: "",
host: "",
type: "1",
status: "0",
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
setIsLoading(true)
try {
const payload = {
mac: data.mac.trim(),
ip: data.ip.trim(),
host: data?.host.trim(),
type: data.type ? Number(data.type) : 0,
status: data.status ? Number(data.status) : 0,
}
const res = await createGateway(payload)
if (res.success) {
toast.success("添加网关成功")
setOpen(false)
props.onSuccess?.()
form.reset()
}else {
toast.error(res.message || "添加失败")
}
} catch (error) {
console.error("添加网关失败:", error)
const message = error instanceof Error ? error.message : error
toast.error(`添加失败: ${message}`)
} finally {
setIsLoading(false)
}
}
const handleCancel = () => {
setOpen(false)
form.reset()
}
const statusOptions = [
{ value: "0", label: "离线" },
{ value: "1", label: "在线" },
]
const typeOptions = [
{ value: "1", label: "自有" },
{ value: "2", label: "白银" },
]
return (
<Dialog
open={open}
onOpenChange={newOpen => {
setOpen(newOpen)
if (!newOpen) {
form.reset()
}
}}
>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form
id="gateway-create"
onSubmit={form.handleSubmit(onSubmit)}
>
<FieldGroup>
<Controller
control={form.control}
name="mac"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-mac">MAC地址:</FieldLabel>
<Input
id="gateway-create-mac"
placeholder="请输入MAC地址00:11:22:33:44:55"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="ip"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-ip">IP地址:</FieldLabel>
<Input
id="gateway-create-ip"
placeholder="请输入IP地址192.168.1.1"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="host"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="gateway-create-host">:</FieldLabel>
<Input
id="gateway-create-host"
placeholder="请输入域名example.com"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && fieldState.error && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="type"
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择网关类型" />
</SelectTrigger>
<SelectContent>
{typeOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && fieldState.error && (
<FieldError>{fieldState.error?.message}</FieldError>
)}
</Field>
)}
/>
<Controller
control={form.control}
name="status"
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger className="w-full h-9">
<SelectValue placeholder="请选择网关状态" />
</SelectTrigger>
<SelectContent>
{statusOptions.map(option => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && fieldState.error && (
<FieldError>{fieldState.error?.message}</FieldError>
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter className="gap-2">
<Button variant="ghost" onClick={handleCancel} disabled={isLoading}>
</Button>
<Button type="submit" form="gateway-create" disabled={isLoading}>
{isLoading ? "添加中..." : "添加"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,136 @@
"use client"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { deletegateway, getGatewayPage } from "@/actions/gateway"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"
import type { Gateway } from "@/models/gateway"
import CreatePage from "./create"
import { format } from "date-fns"
import { ScopeProxyWrite } from "@/lib/scopes"
import { Auth } from "@/components/auth"
export default function GatewayPage() {
const [loading, setLoading] = useState(false)
const table = useDataTable((page, size) => getGatewayPage({ page, size }))
return (
<Page>
<Auth scope={ScopeProxyWrite}>
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreatePage onSuccess={table.refresh} />
</div>
</div>
</Auth>
<Suspense>
<DataTable<Gateway>
{...table}
status={loading ? "load" : "done"}
columns={[
// { header: "id", accessorKey: "id" },
{
header: "域名",
accessorKey: "host",
},
{ header: "IP地址", accessorKey: "ip" },
{
header: "MAC地址",
accessorKey: "mac",
},
{
header: "类型",
accessorKey: "type",
cell: ({ row }) => (row.original.type === 1 ? "自有" : "白银"),
},
{
header: "状态",
accessorKey: "status",
cell: ({ row }) => (row.original.status === 0 ? "离线" : "在线"),
},
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<Auth scope={ScopeProxyWrite}><Delete gateway={row.original} onSuccess={table.refresh} /></Auth>
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}
function Delete({
gateway,
onSuccess,
}: {
gateway: Gateway
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await deletegateway(gateway.id)
if (resp.success) {
toast.success("删除成功")
onSuccess?.()
} else {
toast.error(resp.message ?? "删除失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{gateway.host || gateway.ip}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -1,26 +1,38 @@
import {ReactNode} from 'react'
import Appbar from '@/app/(root)/appbar'
import Navigation from '@/app/(root)/navigation'
import { type ReactNode, Suspense } from "react"
import { getProfile } from "@/actions/auth"
import Appbar from "@/app/(root)/appbar"
import Navigation from "@/app/(root)/navigation"
import SetScopes from "./scopes"
export type RootLayoutProps = {
children: ReactNode
}
export default function RootLayout({children}: RootLayoutProps) {
export default async function RootLayout({ children }: RootLayoutProps) {
return (
<div className="flex h-screen bg-gray-100">
<Suspense>
<Layout>{children}</Layout>
</Suspense>
)
}
async function Layout(props: { children: ReactNode }) {
const profile = await getProfile()
if (!profile.success) throw new Error("页面渲染失败:无法获取账号信息")
return (
<div className="flex h-screen overflow-hidden bg-gray-100">
<SetScopes admin={profile.data} />
{/* 侧边栏 */}
<Navigation/>
<Navigation />
{/* 主内容区 */}
<div className="flex-1 flex flex-col overflow-hidden">
{/* 顶部导航栏 */}
<Appbar/>
<Appbar admin={profile.data} />
{/* 内容区域 */}
<main className="flex-1 overflow-auto p-6">
{children}
</main>
<main className="flex-auto overflow-hidden">{props.children}</main>
</div>
</div>
)

View File

@@ -4,25 +4,29 @@ import {
BarChart3,
ChevronsLeft,
ChevronsRight,
CircleDollarSign,
ClipboardList,
Code,
ComputerIcon,
Database,
ContactRound,
DollarSign,
FileText,
Globe,
DoorClosedIcon,
FolderCode,
Home,
KeyRound,
type LucideIcon,
Package,
Server,
Settings,
ScanSearch,
Shield,
ShoppingBag,
SquarePercent,
TicketPercent,
Users,
} from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { createContext, type ReactNode, useContext, useState } from "react"
import { twJoin } from "tailwind-merge"
import { Auth } from "@/components/auth"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
@@ -32,6 +36,24 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
import {
ScopeAdminRead,
ScopeAdminRoleRead,
ScopeBalanceActivity,
ScopeBatchRead,
ScopeBillRead,
ScopeChannelRead,
ScopeCouponRead,
ScopeDiscountRead,
ScopePermissionRead,
ScopeProductRead,
ScopeProxyRead,
ScopeResourceRead,
ScopeTradeRead,
ScopeUserRead,
ScopeUserReadNotBind,
ScopeUserReadOne,
} from "@/lib/scopes"
// Navigation Context
interface NavigationContextType {
@@ -78,13 +100,14 @@ interface NavItemProps {
href: string
icon: LucideIcon
label: string
requiredScope?: string
}
function NavItem({ href, icon: Icon, label }: NavItemProps) {
function NavItem({ href, icon: Icon, label, requiredScope }: NavItemProps) {
const { collapsed, isActive } = useNavigation()
const active = isActive(href)
const linkContent = (
let linkContent = (
<Link
href={href}
className={`flex items-center ${
@@ -101,19 +124,25 @@ function NavItem({ href, icon: Icon, label }: NavItemProps) {
)
if (collapsed) {
return (
<li>
<Tooltip>
<TooltipTrigger asChild>{linkContent}</TooltipTrigger>
<TooltipContent side="right">
<p>{label}</p>
</TooltipContent>
</Tooltip>
</li>
linkContent = (
<Tooltip>
<TooltipTrigger asChild>{linkContent}</TooltipTrigger>
<TooltipContent side="right">
<p>{label}</p>
</TooltipContent>
</Tooltip>
)
}
return <li>{linkContent}</li>
if (requiredScope) {
linkContent = (
<Auth scope={requiredScope}>
<li>{linkContent}</li>
</Auth>
)
}
return linkContent
}
// NavSeparator Component
@@ -129,13 +158,136 @@ function NavSeparator() {
)
}
const menuSections: { title: string; items: NavItemProps[] }[] = [
{
title: "概览",
items: [
{ href: "/", icon: Home, label: "首页" },
{ href: "/statistics", icon: BarChart3, label: "数据统计" },
],
},
{
title: "客户",
items: [
{
href: "/user",
icon: Users,
label: "客户认领",
requiredScope: ScopeUserReadNotBind,
},
{
href: "/client/cust",
icon: ScanSearch,
label: "客户查询",
requiredScope: ScopeUserReadOne,
},
{
href: "/cust",
icon: ContactRound,
label: "客户管理",
requiredScope: ScopeUserRead,
},
{
href: "/trade",
icon: Activity,
label: "交易明细",
requiredScope: ScopeTradeRead,
},
{
href: "/balance",
icon: CircleDollarSign,
label: "余额明细",
requiredScope: ScopeBalanceActivity,
},
{
href: "/billing",
icon: DollarSign,
label: "账单详情",
requiredScope: ScopeBillRead,
},
],
},
{
title: "运营",
items: [
{
href: "/product",
icon: ShoppingBag,
label: "产品管理",
requiredScope: ScopeProductRead,
},
{
href: "/discount",
icon: SquarePercent,
label: "折扣管理",
requiredScope: ScopeDiscountRead,
},
{
href: "/coupon",
icon: TicketPercent,
label: "优惠券",
requiredScope: ScopeCouponRead,
},
{
href: "/resources",
icon: Package,
label: "套餐管理",
requiredScope: ScopeResourceRead,
},
{
href: "/batch",
icon: ClipboardList,
label: "提取记录",
requiredScope: ScopeBatchRead,
},
{
href: "/channel",
icon: FolderCode,
label: "IP管理",
requiredScope: ScopeChannelRead,
},
],
},
{
title: "系统",
items: [
{
href: "/gateway",
icon: DoorClosedIcon,
label: "网关列表",
requiredScope:ScopeProxyRead
},
{
href: "/admin",
icon: Shield,
label: "管理员",
requiredScope: ScopeAdminRead,
},
{
href: "/roles",
icon: KeyRound,
label: "角色列表",
requiredScope: ScopeAdminRoleRead,
},
{
href: "/permissions",
icon: Shield,
label: "权限列表",
requiredScope: ScopePermissionRead,
},
],
},
]
// Main Navigation Component
export default function Navigation() {
const [collapsed, setCollapsed] = useState(false)
const pathname = usePathname()
const isActive = (path: string) => {
return path === "/" ? pathname === path : pathname.startsWith(path)
if (path === "/") {
return pathname === path
}
return pathname === path || pathname.startsWith(path + "/")
}
const contextValue: NavigationContextType = {
@@ -149,12 +301,12 @@ export default function Navigation() {
<NavigationContext.Provider value={contextValue}>
<aside
className={twJoin(
"bg-background border-r border-border transition-all duration-300 ease-in-out flex flex-col",
"bg-background border-r border-border transition-all duration-300 ease-in-out flex flex-col h-full",
collapsed ? "w-16" : "w-64",
)}
>
{/* Logo */}
<div className="h-16 flex items-center justify-center border-b border-border">
{/*Logo 区域 */}
<div className="h-16 flex items-center justify-center border-b border-border p-4 shrink-0">
{!collapsed ? (
<span className="text-xl font-bold tracking-wide text-foreground">
@@ -165,55 +317,23 @@ export default function Navigation() {
</span>
)}
</div>
{/* Navigation Menu */}
<ScrollArea className="flex-1 py-3">
<ScrollArea className="flex-1 py-3 overflow-hidden">
<nav className="space-y-3">
{/* 概览 */}
<NavGroup title="概览">
<NavItem href="/" icon={Home} label="首页" />
<NavItem href="/statistics" icon={BarChart3} label="数据统计" />
</NavGroup>
{/*<NavSeparator />*/}
{/* IP 资源 */}
{/*<NavGroup title="IP 资源">
<NavItem href="/proxy/nodes" icon={Globe} label="节点列表" />
<NavItem href="/proxy/pools" icon={Server} label="IP池管理" />
</NavGroup>*/}
<NavSeparator />
{/* 客户 */}
<NavGroup title="客户">
<NavItem href="/user" icon={Users} label="客户管理" />
<NavItem href="/trade" icon={Activity} label="交易明细" />
<NavItem href="/billing" icon={DollarSign} label="账单详情" />
</NavGroup>
<NavSeparator />
{/* 运营 */}
<NavGroup title="运营">
<NavItem href="/resources" icon={Package} label="套餐管理" />
<NavItem href="/batch" icon={ClipboardList} label="使用记录" />
<NavItem href="/channel" icon={Code} label="IP管理" />
</NavGroup>
<NavSeparator />
{/* 系统 */}
<NavGroup title="系统">
{/*<NavItem href="/settings" icon={Settings} label="系统设置" />*/}
<NavItem href="/security" icon={Shield} label="管理员" />
{/*<NavItem href="/logs" icon={FileText} label="系统日志" />*/}
</NavGroup>
{menuSections.map((section, idx) => (
<div key={section.title}>
<NavGroup title={section.title}>
{section.items.map(item => (
<NavItem key={item.label} {...item} />
))}
</NavGroup>
{idx !== menuSections.length - 1 && <NavSeparator />}
</div>
))}
</nav>
</ScrollArea>
{/* Toggle Button */}
<div className="p-4 border-t border-border mt-auto">
<div className="p-4 border-t border-border mt-auto shrink-0">
<Button
variant="ghost"
onClick={() => setCollapsed(!collapsed)}

View File

@@ -0,0 +1,186 @@
"use client"
import {
getCoreRowModel,
getExpandedRowModel,
type Row,
useReactTable,
} from "@tanstack/react-table"
import { Copy } from "lucide-react"
import { Suspense, useCallback, useEffect, useState } from "react"
import { toast } from "sonner"
import { getAllPermissions } from "@/actions/permission"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { cn } from "@/lib/utils"
type Node = {
id: number
name: string
description: string
children: Node[]
}
function toConstName(name: string): string {
return (
"Scope" +
name
.split(/[:_]/)
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join("")
)
}
function generateScopeCode(roots: Node[]): string {
function generateNode(node: Node, isRoot: boolean): string[] {
const lines: string[] = []
if (isRoot) {
lines.push(`// ${node.description}`)
}
const constName = toConstName(node.name)
const comment = isRoot ? "" : ` // ${node.description}`
lines.push(`export const ${constName} = "${node.name}"${comment}`)
for (const child of node.children) {
lines.push(...generateNode(child, false))
}
return lines
}
return roots.map(root => generateNode(root, true).join("\n")).join("\n\n")
}
export default function PermissionsPage() {
return (
<Page>
<Suspense>
<PermissionTable />
</Suspense>
</Page>
)
}
function PermissionTable() {
const [data, setData] = useState<Node[]>([])
const table = useReactTable({
getCoreRowModel: getCoreRowModel(),
getExpandedRowModel: getExpandedRowModel(),
data,
columns: [
{ header: "编码", accessorKey: "name" },
{ header: "描述", accessorKey: "description" },
],
getSubRows: row => row.children,
})
const refresh = useCallback(async () => {
try {
const resp = await getAllPermissions()
if (!resp.success) {
throw new Error(resp.message)
}
const map = new Map<number, Node>()
resp.data.forEach(permission => {
map.set(permission.id, {
id: permission.id,
name: permission.name,
description: permission.description,
children: [],
})
})
const roots: Node[] = []
resp.data.forEach(permission => {
const node = map.get(permission.id)
if (!node) {
throw new Error(`找不到权限节点: ${permission.name}`)
}
if (!permission.parent_id) {
roots.push(node)
return
}
const parent = map.get(permission.parent_id)
if (!parent) {
throw new Error(`找不到父权限节点: ${permission.name}`)
}
parent.children.push(node)
})
setData(roots)
console.log(roots)
} catch (e) {
toast.error(e instanceof Error ? e.message : "获取权限列表失败")
}
}, [])
useEffect(() => {
refresh()
}, [refresh])
const handleCopy = useCallback(async () => {
try {
const code = generateScopeCode(data)
await navigator.clipboard.writeText(code)
toast.success("已复制权限代码到剪贴板")
} catch (e) {
toast.error(e instanceof Error ? e.message : "复制失败")
}
}, [data])
return (
<div className="flex flex-col gap-3 overflow-auto">
{process.env.NODE_ENV === "development" && (
<div>
<Button variant="outline" size="sm" onClick={handleCopy}>
<Copy className="mr-2 h-4 w-4" />
</Button>
</div>
)}
<Table>
<TableHeader>
<TableRow className="h-10 sticky top-0 bg-background">
<TableHead></TableHead>
<TableHead></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{table.getRowModel().rows.map(row => (
<PermisionRow key={row.id} row={row} />
))}
</TableBody>
</Table>
</div>
)
}
function PermisionRow(props: { row: Row<Node> }) {
const row = props.row
return (
<>
<TableRow key={row.id} className="h-10">
<TableCell className="flex">
<div style={{ width: row.depth * 16 }}></div>
<span className={cn(row.subRows.length ? "font-bold" : "text-sm")}>
{row.original.name}
</span>
</TableCell>
<TableCell>{row.original.description}</TableCell>
</TableRow>
{row.subRows.map(subRow => (
<PermisionRow key={subRow.id} row={subRow} />
))}
</>
)
}

View File

@@ -0,0 +1,144 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { batchUpdateProductSkuDiscount } from "@/actions/product"
import { getAllProductDiscount } from "@/actions/product_discount"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { ProductDiscount } from "@/models/product_discount"
const schema = z.object({
discount_id: z.string().min(1, "请选择折扣"),
})
export function BatchUpdateDiscount(props: {
productId: number
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [discounts, setDiscounts] = useState<ProductDiscount[]>([])
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
discount_id: "",
},
})
useEffect(() => {
if (open) {
getAllProductDiscount().then(resp => {
if (resp.success) {
setDiscounts(resp.data)
}
})
}
}, [open])
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await batchUpdateProductSkuDiscount({
product_id: props.productId,
discount_id:
data.discount_id === "none" ? null : Number(data.discount_id),
})
if (resp.success) {
toast.success("批量配置折扣成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message ?? "操作失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (!value) {
form.reset()
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" disabled={!props.productId}>
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="sku-batch-discount" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="discount_id"
render={({ field, fieldState }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger
className="w-full"
aria-invalid={fieldState.invalid}
>
<SelectValue placeholder="请选择要应用的折扣" />
</SelectTrigger>
<SelectContent>
{discounts.map(d => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}{d.discount}%
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="sku-batch-discount">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,283 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createProductSku } from "@/actions/product"
import { getAllProductDiscount } from "@/actions/product_discount"
import { ProductCodeField } from "@/components/products"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
FieldSeparator,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { ProductDiscount } from "@/models/product_discount"
import type { SelectedProduct } from "./type"
const schema = z
.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
.refine(
data => {
const price = Number(data.price)
const priceMin = Number(data.price_min)
if (isNaN(price) || isNaN(priceMin)) return true
return price >= priceMin
},
{
message: "单价不能低于最低价格",
path: ["price"],
},
)
export function CreateProductSku(props: {
product?: SelectedProduct
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [discounts, setDiscounts] = useState<ProductDiscount[]>([])
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: "",
name: "",
price: "",
discount_id: "",
price_min: "",
},
})
useEffect(() => {
if (open) {
getAllProductDiscount()
.then(resp => {
if (resp.success) {
setDiscounts(resp.data)
}
})
.catch(e => toast.error(e.message))
}
}, [open])
const onSubmit = async (data: z.infer<typeof schema>) => {
if (!props.product) return
try {
const resp = await createProductSku({
product_id: props.product.id,
code: data.code,
name: data.name,
price: data.price,
discount_id:
data.discount_id && data.discount_id !== ""
? Number(data.discount_id)
: undefined,
price_min: data.price_min,
})
if (resp.success) {
form.reset()
toast.success("套餐创建成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (!value) {
form.reset()
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button disabled={!props.product}></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="sku-create" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-create-name"></FieldLabel>
<Input
id="sku-create-name"
placeholder="请输入套餐名称"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="price"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-update-price"></FieldLabel>
<Input
id="sku-update-price"
placeholder="请输入单价"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="price_min"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-create-price"></FieldLabel>
<Input
id="sku-create-price"
placeholder="请输入最低价格"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="discount_id"
render={({ field, fieldState }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger
className="w-full"
aria-invalid={fieldState.invalid}
>
<SelectValue placeholder="选择折扣" />
</SelectTrigger>
<SelectContent>
{discounts.map(d => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}{d.discount}%
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<FieldSeparator />
{props.product && (
<ProductCodeField
control={form.control}
name="code"
code={props.product.code}
/>
)}
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="sku-create">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,212 @@
"use client"
import { format } from "date-fns"
import { Loader2 } from "lucide-react"
import { Suspense, useCallback, useEffect, useMemo, useState } from "react"
import { toast } from "sonner"
import {
activeProductSku,
getAllProduct,
getPageProductSku,
} from "@/actions/product"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { SkuCodeBadge } from "@/components/products/format"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import type { ProductCode } from "@/lib/base"
import { cn } from "@/lib/utils"
import type { Product } from "@/models/product"
import type { ProductSku } from "@/models/product_sku"
import { BatchUpdateDiscount } from "./batch-discount"
import { CreateProductSku } from "./create"
import type { SelectedProduct } from "./type"
import { UpdateProductSku } from "./update"
export default function ProductPage() {
const [selected, setSelected] = useState<SelectedProduct | undefined>(
undefined,
)
return (
<Page className="flex-row items-stretch">
<Products selected={selected} onSelect={setSelected} />
<ProductSkus selected={selected} />
</Page>
)
}
function Products(props: {
selected?: SelectedProduct
onSelect?: (id: SelectedProduct) => void
}) {
const [list, setList] = useState<Product[]>([])
const refresh = useCallback(async () => {
const resp = await getAllProduct()
if (resp.success) {
setList(resp.data)
}
}, [])
const selected = useMemo(() => {
return list.find(item => item.id === props.selected?.id)
}, [list, props.selected])
useEffect(() => {
refresh()
}, [refresh])
return (
<section className="flex-none basis-50 bg-background rounded-lg">
<header className="pl-3 pr-1 h-10 border-b flex items-center justify-between">
<h3 className="text-sm"></h3>
</header>
<ul className="flex flex-col gap-1 py-1">
{list.map(item => (
<li key={item.id} className="px-1">
<Button
variant="ghost"
className={cn(
"size-full box-border p-2 rounded-md flex justify-between items-center select-none",
selected?.id === item.id && "bg-primary/20",
)}
onClick={() => props.onSelect?.({ id: item.id, code: item.code })}
>
<div>
<p>{item.name}</p>
<p className="text-sm text-gray-500">{item.description}</p>
</div>
<Badge className="bg-green-600/60"></Badge>
</Button>
</li>
))}
</ul>
</section>
)
}
function ProductSkus(props: {
selected?: {
id: number
code: ProductCode
}
}) {
const action = useCallback(
(page: number, size: number) =>
getPageProductSku({ page, size, product_id: props.selected?.id }),
[props.selected],
)
const table = useDataTable(action)
return (
<div className="flex-auto overflow-hidden flex flex-col items-stretch gap-3">
<div className="flex gap-3">
<CreateProductSku product={props.selected} onSuccess={table.refresh} />
<BatchUpdateDiscount
productId={props.selected?.id ?? 0}
onSuccess={table.refresh}
/>
</div>
<Suspense>
<DataTable<ProductSku>
classNames={{
root: "overflow-auto",
}}
{...table}
columns={[
{
header: "套餐编码",
cell: ({ row }) =>
row.original.product ? (
<SkuCodeBadge
productCode={row.original.product.code}
skuCode={row.original.code}
/>
) : (
row.original.code
),
},
{ header: "套餐名称", accessorKey: "name" },
{ header: "单价", accessorFn: row => Number(row.price) },
{ header: "折扣", accessorFn: row => row.discount?.name ?? "—" },
{
header: "折后价",
accessorFn: row => {
const value = row.discount
? (Number(row.price) * Number(row.discount.discount)) / 100
: Number(row.price)
return Number(value)
},
},
{ header: "最低价格", accessorKey: "price_min" },
{
header: "创建时间",
accessorFn: row => format(row.created_at, "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorFn: row => format(row.updated_at, "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-1">
<UpdateProductSku
sku={row.original}
onSuccess={table.refresh}
/>
<ActiveButton sku={row.original} onSuccess={table.refresh} />
</div>
),
},
]}
/>
</Suspense>
</div>
)
}
function ActiveButton(props: { sku: ProductSku; onSuccess?: () => void }) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const newStatus = props.sku.status === 1 ? 0 : 1
const resp = await activeProductSku({
id: props.sku.id,
status: newStatus,
})
if (resp.success) {
toast.success(newStatus === 1 ? "已启用" : "已禁用")
props.onSuccess?.()
} else {
toast.error(resp.message ?? "操作失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<Button
size="sm"
variant={props.sku?.status === 1 ? "outline" : "default"}
onClick={handleConfirm}
disabled={loading}
>
{loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>{props.sku?.status === 1 ? "禁用" : "启用"}</>
)}
</Button>
)
}

View File

@@ -0,0 +1,6 @@
import type { ProductCode } from "@/lib/base"
export type SelectedProduct = {
id: number
code: ProductCode
}

View File

@@ -0,0 +1,285 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { updateProductSku } from "@/actions/product"
import { getAllProductDiscount } from "@/actions/product_discount"
import { ProductCodeField } from "@/components/products"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
FieldSeparator,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { ProductDiscount } from "@/models/product_discount"
import type { ProductSku } from "@/models/product_sku"
const schema = z
.object({
code: z.string().min(1, "请输入套餐编码"),
name: z.string().min(1, "请输入套餐名称"),
price: z
.string()
.min(1, "请输入单价")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数单价",
),
discount_id: z.string().optional(),
price_min: z
.string()
.min(1, "请输入最低价格")
.refine(
v => !Number.isNaN(Number(v)) && Number(v) > 0,
"请输入有效的正数价格",
),
})
.refine(
data => {
const price = Number(data.price)
const priceMin = Number(data.price_min)
if (isNaN(price) || isNaN(priceMin)) return true
return price >= priceMin
},
{
message: "单价不能低于最低价格",
path: ["price"],
},
)
export function UpdateProductSku(props: {
sku: ProductSku
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [discounts, setDiscounts] = useState<ProductDiscount[]>([])
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
code: props.sku.code,
name: props.sku.name,
price: props.sku.price,
discount_id: props.sku.discount ? String(props.sku.discount.id) : "",
price_min: props.sku.price_min ?? "",
},
})
useEffect(() => {
if (open) {
getAllProductDiscount().then(resp => {
if (resp.success) {
setDiscounts(resp.data)
}
})
}
}, [open])
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await updateProductSku({
id: props.sku.id,
code: data.code,
name: data.name,
price: data.price,
discount_id:
data.discount_id && data.discount_id !== ""
? Number(data.discount_id)
: null,
price_min: data.price_min,
})
if (resp.success) {
toast.success("套餐修改成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
form.reset({
code: props.sku.code,
name: props.sku.name,
price: props.sku.price,
discount_id: props.sku.discount ? String(props.sku.discount.id) : "",
price_min: props.sku.price_min ?? "",
})
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="sku-update" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-update-name"></FieldLabel>
<Input
id="sku-update-name"
placeholder="请输入套餐名称"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="price"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-update-price"></FieldLabel>
<Input
id="sku-update-price"
placeholder="请输入单价"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="price_min"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="sku-create-price"></FieldLabel>
<Input
id="sku-create-price"
placeholder="请输入最低价格"
{...field}
aria-invalid={fieldState.invalid}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
// let value = e.target.value
// value = value.replace(/[^\d.]/g, "")
// const dotCount = (value.match(/\./g) || []).length
// if (dotCount > 1) {
// value = value.slice(0, value.lastIndexOf("."))
// }
// if (value.includes(".")) {
// const [int, dec] = value.split(".")
// value = `${int}.${dec.slice(0, 2)}`
// }
// field.onChange(value)
// }}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="discount_id"
render={({ field, fieldState }) => (
<Field>
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger
className="w-full"
aria-invalid={fieldState.invalid}
>
<SelectValue placeholder="选择折扣" />
</SelectTrigger>
<SelectContent>
{discounts.map(d => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}{d.discount}%
</SelectItem>
))}
</SelectContent>
</Select>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<FieldSeparator />
{props.sku.product && (
<ProductCodeField
control={form.control}
name="code"
code={props.sku.product.code}
/>
)}
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="sku-update">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -1,495 +0,0 @@
'use client'
import {useState, useEffect} from 'react'
import Link from 'next/link'
// 定义节点数据接口
interface ProxyNode {
id: string;
ipAddress: string;
location: {
country: string;
region: string;
};
type: string;
status: 'online' | 'offline' | 'warning';
responseTime: number;
lastCheckTime: string;
pool: string;
isStatic: boolean;
}
export type ProxyNodesPageProps = {}
export default function ProxyNodesPage(props: ProxyNodesPageProps) {
const [loading, setLoading] = useState<boolean>(true)
const [nodes, setNodes] = useState<ProxyNode[]>([])
const [searchTerm, setSearchTerm] = useState<string>('')
const [filterStatus, setFilterStatus] = useState<string>('all')
const [filterType, setFilterType] = useState<string>('all')
const [filterPool, setFilterPool] = useState<string>('all')
// 模拟数据加载
useEffect(() => {
setTimeout(() => {
setNodes([
{
id: 'ip-1',
ipAddress: '203.45.167.82',
location: {country: '美国', region: '纽约'},
type: '数据中心',
status: 'online',
responseTime: 126,
lastCheckTime: '2024-05-10 15:30:22',
pool: '北美专用池',
isStatic: true,
},
{
id: 'ip-2',
ipAddress: '185.72.193.54',
location: {country: '德国', region: '法兰克福'},
type: '住宅',
status: 'online',
responseTime: 158,
lastCheckTime: '2024-05-10 15:28:45',
pool: '欧洲高速池',
isStatic: false,
},
{
id: 'ip-3',
ipAddress: '118.96.244.105',
location: {country: '新加坡', region: '中心区'},
type: '移动',
status: 'warning',
responseTime: 312,
lastCheckTime: '2024-05-10 15:25:12',
pool: '亚太地区池',
isStatic: false,
},
{
id: 'ip-4',
ipAddress: '45.178.29.6',
location: {country: '加拿大', region: '多伦多'},
type: '数据中心',
status: 'online',
responseTime: 143,
lastCheckTime: '2024-05-10 15:23:08',
pool: '北美专用池',
isStatic: false,
},
{
id: 'ip-5',
ipAddress: '79.114.83.201',
location: {country: '英国', region: '伦敦'},
type: '住宅',
status: 'offline',
responseTime: 0,
lastCheckTime: '2024-05-10 15:18:33',
pool: '欧洲高速池',
isStatic: false,
},
{
id: 'ip-6',
ipAddress: '164.83.219.47',
location: {country: '日本', region: '东京'},
type: '住宅',
status: 'online',
responseTime: 87,
lastCheckTime: '2024-05-10 15:15:21',
pool: '亚太地区池',
isStatic: true,
},
{
id: 'ip-7',
ipAddress: '221.67.93.143',
location: {country: '中国', region: '上海'},
type: '移动',
status: 'online',
responseTime: 104,
lastCheckTime: '2024-05-10 15:10:46',
pool: '亚太地区池',
isStatic: false,
},
{
id: 'ip-8',
ipAddress: '37.209.148.72',
location: {country: '法国', region: '巴黎'},
type: '数据中心',
status: 'warning',
responseTime: 276,
lastCheckTime: '2024-05-10 15:05:19',
pool: '欧洲高速池',
isStatic: false,
},
])
setLoading(false)
}, 800)
}, [])
// 过滤节点数据
const filteredNodes = nodes.filter(node => {
return (
(searchTerm === '' ||
node.ipAddress.includes(searchTerm) ||
node.location.country.includes(searchTerm) ||
node.pool.includes(searchTerm)) &&
(filterStatus === 'all' ||
(filterStatus === 'online' && node.status === 'online') ||
(filterStatus === 'offline' && node.status === 'offline') ||
(filterStatus === 'warning' && node.status === 'warning')) &&
(filterType === 'all' || node.type === filterType) &&
(filterPool === 'all' || node.pool === filterPool)
)
})
return (
<div className="space-y-5">
{/* 概览区域 - 使用色块和留白风格 */}
<div className="border border-gray-200 rounded-lg overflow-hidden">
{/* 标题区域 - 简洁风格 */}
<div className="bg-white px-5 py-4">
<div className="flex justify-between items-center">
<h1 className="text-lg font-bold text-gray-900"></h1>
<div className="flex gap-2">
<button
className="bg-gray-50 border border-gray-200 text-gray-700 px-3 py-1.5 rounded-md text-sm font-medium flex items-center hover:bg-gray-100">
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
</svg>
</button>
<button
className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center">
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
</svg>
</button>
</div>
</div>
<p className="mt-1 text-sm text-gray-500">IP资源</p>
</div>
{/* 统计信息区域 - 色块风格 */}
<div className="grid grid-cols-4 gap-px bg-gray-100">
{/* 总IP数量 */}
<div className="bg-white p-4">
<div className="flex items-center">
<div className="w-10 h-10 flex items-center justify-center bg-blue-50 rounded-md">
<svg className="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9"/>
</svg>
</div>
<div className="ml-3">
<p className="text-xs font-medium text-gray-500">IP数量</p>
<div className="text-lg font-semibold text-gray-900">152,487</div>
</div>
</div>
</div>
{/* 在线IP */}
<div className="bg-white p-4">
<div className="flex items-center">
<div className="w-10 h-10 flex items-center justify-center bg-green-50 rounded-md">
<svg className="h-5 w-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M5 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</div>
<div className="ml-3">
<div className="flex items-center">
<p className="text-xs font-medium text-gray-500">线IP</p>
<span className="ml-2 text-xs font-medium text-green-600">91%</span>
</div>
<div className="text-lg font-semibold text-gray-900">138,954</div>
</div>
</div>
</div>
{/* IP池分布 */}
<div className="bg-white p-4">
<div className="flex items-center">
<div className="w-10 h-10 flex items-center justify-center bg-indigo-50 rounded-md">
<svg className="h-5 w-5 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
</svg>
</div>
<div className="ml-3">
<div className="flex items-center">
<p className="text-xs font-medium text-gray-500">IP池分布</p>
<span className="ml-2 text-xs font-medium text-gray-500">5</span>
</div>
<div className="text-lg font-semibold text-gray-900">12</div>
</div>
</div>
</div>
{/* 异常IP */}
<div className="bg-white p-4">
<div className="flex items-center">
<div className="w-10 h-10 flex items-center justify-center bg-red-50 rounded-md">
<svg className="h-5 w-5 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
</svg>
</div>
<div className="ml-3">
<div className="flex items-center">
<p className="text-xs font-medium text-gray-500">IP</p>
<span className="ml-2 text-xs font-medium text-red-600"></span>
</div>
<div className="text-lg font-semibold text-gray-900">1,205</div>
</div>
</div>
</div>
</div>
</div>
{/* 数据展示 */}
<div className="border border-gray-200 rounded-lg overflow-hidden">
{/* 筛选搜索区域 */}
<div className="bg-white p-4 border-b border-gray-200">
<div className="grid grid-cols-1 gap-4 md:grid-cols-12">
{/* 搜索框 */}
<div className="relative md:col-span-5">
<input
type="text"
placeholder="搜索IP地址、地区或标签..."
className="w-full px-3 py-2 bg-gray-50 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm"
/>
<svg
className="absolute right-3 top-2.5 h-4 w-4 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
{/* 筛选区域 */}
<div className="flex space-x-3 md:col-span-7">
<select
className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm bg-white text-gray-700 flex-1"
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
>
<option value="all"></option>
<option value="online">线</option>
<option value="offline">线</option>
<option value="warning"></option>
</select>
<select
className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm bg-white text-gray-700 flex-1"
value={filterType}
onChange={(e) => setFilterType(e.target.value)}
>
<option value="all"></option>
<option value="数据中心"></option>
<option value="住宅"></option>
<option value="移动"></option>
</select>
<select
className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm bg-white text-gray-700 flex-1"
value={filterPool}
onChange={(e) => setFilterPool(e.target.value)}
>
<option value="all"></option>
<option value="北美专用池"></option>
<option value="欧洲高速池"></option>
<option value="亚太地区池"></option>
</select>
</div>
</div>
</div>
{/* IP表格区域 */}
{loading ? (
<div className="p-12 flex justify-center items-center bg-white">
<svg
className="animate-spin h-6 w-6 text-blue-600"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</div>
) : (
<div className="overflow-x-auto bg-white">
<table className="min-w-full">
<thead>
<tr>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
IP地址
</th>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
<th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
<th scope="col" className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200 bg-gray-50">
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{filteredNodes.map((node, index) => (
<tr key={node.id} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className="px-4 py-3 whitespace-nowrap text-sm">
<div className="flex items-center">
<span className={`w-2 h-2 rounded-full mr-2 ${
node.status === 'online' ? 'bg-green-500' :
node.status === 'offline' ? 'bg-red-500' : 'bg-yellow-500'
}`}></span>
<span className="font-medium text-gray-900">{node.ipAddress}</span>
{node.isStatic && (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
</span>
)}
</div>
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm">
<div className="text-gray-900">{node.location.country}</div>
<div className="text-xs text-gray-500">{node.location.region}</div>
</td>
<td className="px-4 py-3 whitespace-nowrap">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
node.type === '数据中心' ? 'bg-purple-100 text-purple-800' :
node.type === '住宅' ? 'bg-blue-100 text-blue-800' : 'bg-indigo-100 text-indigo-800'
}`}>
{node.type}
</span>
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm">
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
node.status === 'online' ? 'bg-green-100 text-green-800' :
node.status === 'offline' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'
}`}>
{node.status === 'online' ? '在线' : node.status === 'offline' ? '离线' : '异常'}
</span>
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
{node.responseTime > 0 ? (
<div className="flex items-center">
<span className={`font-medium ${
node.responseTime < 150 ? 'text-green-600' :
node.responseTime < 250 ? 'text-yellow-600' : 'text-red-600'
}`}>
{node.responseTime} ms
</span>
</div>
) : (
<span className="text-gray-400">-</span>
)}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
{node.pool}
</td>
<td className="px-4 py-3 whitespace-nowrap text-right text-sm font-medium space-x-2">
<Link href={`/proxy/nodes/${node.id}`} className="text-blue-600 hover:text-blue-900">
</Link>
<button className="text-gray-600 hover:text-gray-900">
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* 分页控制 */}
<div className="bg-gray-50 px-5 py-3 border-t border-gray-200">
<div className="flex items-center justify-between">
<div className="text-sm text-gray-700">
<span className="font-medium">1</span> <span className="font-medium">8</span> <span
className="font-medium">152,487</span>
</div>
<div>
<nav className="relative z-0 inline-flex -space-x-px">
<button
className="relative inline-flex items-center px-2 py-1.5 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
<svg className="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
clipRule="evenodd"/>
</svg>
</button>
<button
className="relative inline-flex items-center px-3 py-1.5 border border-gray-300 bg-white text-sm font-medium hover:bg-gray-50 text-blue-600 bg-blue-50 border-blue-300">
1
</button>
<button
className="relative inline-flex items-center px-3 py-1.5 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
2
</button>
<button
className="relative inline-flex items-center px-3 py-1.5 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
3
</button>
<span
className="relative inline-flex items-center px-3 py-1.5 border border-gray-300 bg-white text-sm font-medium text-gray-700">
...
</span>
<button
className="relative inline-flex items-center px-3 py-1.5 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
152
</button>
<button
className="relative inline-flex items-center px-2 py-1.5 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
<svg className="h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path
fillRule="evenodd"
d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
clipRule="evenodd"/>
</svg>
</button>
</nav>
</div>
</div>
</div>
</div>
</div>
)
}

View File

@@ -1,421 +0,0 @@
'use client'
import {useState, useEffect} from 'react'
import Link from 'next/link'
export type ProxyPoolsPageProps = {}
// 定义IP池接口
interface ProxyPool {
id: string;
name: string;
description: string;
ips: number;
activeIps: number;
region: string;
type: string;
createdAt: string;
status: 'active' | 'inactive' | 'maintenance';
}
export default function ProxyPoolsPage(props: ProxyPoolsPageProps) {
const [pools, setPools] = useState<ProxyPool[]>([])
const [loading, setLoading] = useState<boolean>(true)
const [searchTerm, setSearchTerm] = useState<string>('')
const [filterStatus, setFilterStatus] = useState<string>('all')
const [filterRegion, setFilterRegion] = useState<string>('all')
// 模拟数据加载
useEffect(() => {
// 实际项目中替换为API调用
setTimeout(() => {
setPools([
{
id: 'pool-1',
name: '全球通用池',
description: '包含全球多个地区的高质量IP',
ips: 5000,
activeIps: 4328,
region: '全球',
type: '住宅IP',
createdAt: '2023-10-15',
status: 'active',
},
{
id: 'pool-2',
name: '北美专用池',
description: '美国和加拿大地区专用IP池',
ips: 3200,
activeIps: 2950,
region: '北美',
type: '数据中心IP',
createdAt: '2023-11-02',
status: 'active',
},
{
id: 'pool-3',
name: '欧洲高速池',
description: '欧洲地区高速稳定IP',
ips: 2800,
activeIps: 2180,
region: '欧洲',
type: '住宅IP',
createdAt: '2023-09-28',
status: 'active',
},
{
id: 'pool-4',
name: '亚太地区池',
description: '亚洲和太平洋地区IP',
ips: 4200,
activeIps: 3890,
region: '亚太',
type: '移动IP',
createdAt: '2023-12-05',
status: 'maintenance',
},
{
id: 'pool-5',
name: '电商专用池',
description: '适用于电商平台的IP池',
ips: 1500,
activeIps: 1200,
region: '全球',
type: '住宅IP',
createdAt: '2024-01-10',
status: 'inactive',
},
])
setLoading(false)
}, 800)
}, [])
// 过滤IP池
const filteredPools = pools.filter(pool => {
return (
(searchTerm === '' ||
pool.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
pool.description.toLowerCase().includes(searchTerm.toLowerCase())) &&
(filterStatus === 'all' || pool.status === filterStatus) &&
(filterRegion === 'all' || pool.region === filterRegion)
)
})
// 获取状态颜色和文本
const getStatusInfo = (status: string) => {
switch (status) {
case 'active':
return {color: 'bg-green-100 text-green-800', text: '运行中'}
case 'inactive':
return {color: 'bg-gray-100 text-gray-800', text: '未启用'}
case 'maintenance':
return {color: 'bg-yellow-100 text-yellow-800', text: '维护中'}
default:
return {color: 'bg-gray-100 text-gray-800', text: '未知'}
}
}
return (
<div className="space-y-6">
{/* 页面标题 */}
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-gray-900">IP池管理</h1>
<p className="mt-1 text-sm text-gray-500">IP池</p>
</div>
<button
className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium flex items-center">
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
</svg>
IP池
</button>
</div>
{/* 筛选和搜索工具栏 */}
<div className="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
<div className="relative">
<input
type="text"
placeholder="搜索IP池..."
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<svg
className="absolute right-3 top-2.5 h-5 w-5 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
<div className="flex space-x-4">
<div className="w-full">
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<select
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
>
<option value="all"></option>
<option value="active"></option>
<option value="inactive"></option>
<option value="maintenance"></option>
</select>
</div>
</div>
<div className="w-full">
<label className="block text-sm font-medium text-gray-700 mb-1"></label>
<select
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
value={filterRegion}
onChange={(e) => setFilterRegion(e.target.value)}
>
<option value="all"></option>
<option value="全球"></option>
<option value="北美"></option>
<option value="欧洲"></option>
<option value="亚太"></option>
</select>
</div>
</div>
</div>
{/* IP池列表 */}
<div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
{loading ? (
<div className="p-8 flex justify-center">
<svg
className="animate-spin h-8 w-8 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path
className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
) : filteredPools.length === 0 ? (
<div className="p-8 text-center">
<svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
<p className="mt-4 text-gray-500 text-lg">IP池</p>
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
IP池名称
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
IP概况
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
IP类型
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
<th
scope="col"
className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{filteredPools.map((pool) => {
const statusInfo = getStatusInfo(pool.status)
return (
<tr key={pool.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div>
<div className="text-sm font-medium text-gray-900">{pool.name}</div>
<div className="text-sm text-gray-500 max-w-xs truncate">{pool.description}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">IP: {pool.ips.toLocaleString()}</div>
<div className="text-sm text-gray-500">IP: {pool.activeIps.toLocaleString()}</div>
<div className="w-full bg-gray-200 rounded-full h-1.5 mt-1.5">
<div
className="bg-blue-600 h-1.5 rounded-full"
style={{width: `${(pool.activeIps / pool.ips) * 100}%`}}
></div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">{pool.region}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">{pool.type}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusInfo.color}`}>
{statusInfo.text}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{pool.createdAt}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<Link href={`/proxy/pools/${pool.id}`} className="text-blue-600 hover:text-blue-900 mr-4">
</Link>
<Link
href={`/proxy/pools/${pool.id}/edit`} className="text-indigo-600 hover:text-indigo-900 mr-4">
</Link>
<button className="text-red-600 hover:text-red-900">
</button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
{/* 数据卡片概览 */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<div className="flex items-center">
<div className="p-3 rounded-full bg-blue-100 text-blue-600">
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-lg font-medium text-gray-900">IP池</h3>
<div className="mt-1 text-3xl font-semibold">{pools.length}</div>
</div>
</div>
<div className="mt-4">
<div className="flex justify-between text-sm">
<span className="text-gray-500">IP池</span>
<span className="font-medium text-gray-900">{pools.filter(p => p.status === 'active').length}</span>
</div>
</div>
</div>
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<div className="flex items-center">
<div className="p-3 rounded-full bg-green-100 text-green-600">
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-lg font-medium text-gray-900">IP数量</h3>
<div className="mt-1 text-3xl font-semibold">
{pools.reduce((sum, pool) => sum + pool.ips, 0).toLocaleString()}
</div>
</div>
</div>
<div className="mt-4">
<div className="flex justify-between text-sm">
<span className="text-gray-500">IP</span>
<span className="font-medium text-gray-900">
{pools.reduce((sum, pool) => sum + pool.activeIps, 0).toLocaleString()}
</span>
</div>
</div>
</div>
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<div className="flex items-center">
<div className="p-3 rounded-full bg-purple-100 text-purple-600">
<svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</div>
<div className="ml-4">
<h3 className="text-lg font-medium text-gray-900">IP利用率</h3>
<div className="mt-1 text-3xl font-semibold">
{Math.round((pools.reduce((sum, pool) => sum + pool.activeIps, 0) /
pools.reduce((sum, pool) => sum + pool.ips, 0)) * 100)}%
</div>
</div>
</div>
<div className="mt-4">
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-purple-600 h-2 rounded-full"
style={{
width: `${(pools.reduce((sum, pool) => sum + pool.activeIps, 0) /
pools.reduce((sum, pool) => sum + pool.ips, 0)) * 100}%`,
}}
></div>
</div>
</div>
</div>
</div>
{/* 操作指南 */}
<div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</div>
<div className="ml-3 flex-1 md:flex md:justify-between">
<p className="text-sm text-blue-700">
IP池是管理IP资源的基础单位IP池访
</p>
<p className="mt-3 text-sm md:mt-0 md:ml-6">
<a href="/help/proxy-pools" className="whitespace-nowrap font-medium text-blue-700 hover:text-blue-600">
<span aria-hidden="true">&rarr;</span>
</a>
</p>
</div>
</div>
</div>
</div>
)
}

View File

@@ -1,5 +0,0 @@
export type ProxySourcesPageProps = {}
export default function ProxySourcesPage(props: ProxySourcesPageProps) {
return <div></div>
}

View File

@@ -1,36 +1,197 @@
"use client"
import { Suspense } from "react"
import { listResourceLong, listResourceShort } from "@/actions/resources"
import { zodResolver } from "@hookform/resolvers/zod"
import { format, isBefore, isSameDay } from "date-fns"
import { Box, Loader2, Timer } from "lucide-react"
import { Suspense, useCallback, useMemo, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import {
listResourceLong,
listResourceShort,
updateResource,
} from "@/actions/resources"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import type { Resources } from "@/models/resources"
const filterSchema = z
.object({
user_phone: z.string().optional(),
resource_no: z.string().optional(),
status: z.string().optional(),
type: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
expired: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FormValues = z.infer<typeof filterSchema>
interface FilterParams {
user_phone?: string
resource_no?: string
active?: boolean
mode?: number
created_at_start?: Date
created_at_end?: Date
expired?: boolean
}
// 获取资源类型
function getResourceType(resource: Resources): number {
if ("short" in resource && resource.short) {
return resource.short.type
}
if ("long" in resource && resource.long) {
return resource.long.type
}
return resource.type
}
// 获取资源详情对象
function getResourceDetail(resource: Resources) {
if ("short" in resource && resource.short) {
return resource.short
}
if ("long" in resource && resource.long) {
return resource.long
}
return null
}
// 获取过期时间
function getExpireAt(resource: Resources): Date | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.expire_at
}
if ("long" in resource && resource.long) {
return resource.long.expire_at
}
return undefined
}
function getName(resource: Resources): string | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.sku?.name
}
if ("long" in resource && resource.long) {
return resource.long.sku?.name
}
return undefined
}
// 获取最近使用时间
function getLastAt(resource: Resources): Date | null | undefined {
if ("short" in resource && resource.short) {
return resource.short.last_at
}
if ("long" in resource && resource.long) {
return resource.long.last_at
}
return undefined
}
// 资源类型徽章
function ResourceTypeBadge({ resource }: { resource: Resources }) {
const type = getResourceType(resource)
if (type === 1) {
return (
<div className="flex gap-2 items-center bg-green-50 w-fit px-2 py-1 rounded-md">
<Timer size={20} />
<span></span>
</div>
)
}
if (type === 2) {
return (
<div className="flex gap-2 items-center bg-blue-50 w-fit px-2 py-1 rounded-md">
<Box size={20} />
<span></span>
</div>
)
}
return null
}
// 过期徽章
function ExpireBadge({ expireAt }: { expireAt: Date | null | undefined }) {
if (!expireAt) return null
if (isBefore(expireAt, new Date())) {
return <Badge variant="destructive"></Badge>
}
return null
}
// 格式化日期
function formatDateTime(date: Date | null | undefined) {
if (!date) return "-"
return format(date, "yyyy-MM-dd HH:mm")
}
// 计算今日使用量
function getTodayUsage(lastAt: Date | null | undefined, daily: number) {
if (lastAt && isSameDay(lastAt, new Date())) {
return daily
}
return 0
}
export default function ResourcesPage() {
return (
<div>
<Tabs defaultValue="short">
<TabsList className="bg-card p-1.5 rounded-lg">
<TabsTrigger
value="short"
className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
>
<Page>
<Tabs defaultValue="short" className="overflow-hidden">
<TabsList className="bg-card">
<TabsTrigger value="short" className="h-10 px-4 shadow-none">
</TabsTrigger>
<TabsTrigger
value="long"
className="w-30 h-9 data-[state=active]:bg-primary-muted text-base rounded-md"
>
<TabsTrigger value="long" className="h-10 px-4 shadow-none">
</TabsTrigger>
</TabsList>
<TabsContent value="short" className="flex flex-col gap-4">
<TabsContent
value="short"
className="flex flex-col gap-4 overflow-hidden"
>
<ResourceList resourceType="short" />
</TabsContent>
<TabsContent value="long" className="flex flex-col gap-4">
<ResourceList resourceType="long" />
</TabsContent>
</Tabs>
</div>
</Page>
)
}
@@ -41,21 +202,369 @@ interface ResourceListProps {
function ResourceList({ resourceType }: ResourceListProps) {
const isLong = resourceType === "long"
const listFn = isLong ? listResourceLong : listResourceShort
const table = useDataTable<Resources>((page, size) => listFn({ page, size }))
const [filters, setFilters] = useState<FilterParams>({})
const [updatingId, setUpdatingId] = useState<number | null>(null)
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
user_phone: "",
resource_no: "",
status: "all",
type: "all",
created_at_start: "",
created_at_end: "",
expired: "all",
},
})
const fetchResources = useCallback(
(page: number, size: number) => {
return listFn({ page, size, ...filters })
},
[listFn, filters],
)
const table = useDataTable<Resources>(fetchResources)
const refreshTable = useCallback(() => {
setFilters(prev => ({ ...prev }))
}, [])
const handleStatusChange = useCallback(
async (resource: Resources, newStatusValue: string) => {
const newActive = newStatusValue === "0"
if (newActive === resource.active) return
setUpdatingId(resource.id)
try {
await updateResource({
id: resource.id,
active: newActive,
})
toast.success("更新成功", {
description: `资源状态已更新为${newActive ? "启用" : "禁用"}`,
})
refreshTable()
} catch (error) {
console.error("更新状态失败:", error)
toast.error("更新失败", {
description: error instanceof Error ? error.message : "请稍后重试",
})
} finally {
setUpdatingId(null)
}
},
[refreshTable],
)
const onFilter = handleSubmit(data => {
const result: FilterParams = {}
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.resource_no?.trim()) result.resource_no = data.resource_no.trim()
if (data.status && data.status !== "all") {
result.active = data.status === "0"
}
if (data.type && data.type !== "all") {
result.mode = Number(data.type)
}
if (data.expired && data.expired !== "all") {
result.expired = data.expired === "1"
}
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
const columns = useMemo(
() => [
{
header: "会员号",
accessorFn: (row: Resources) => row.user?.phone || "",
},
{
header: "套餐",
cell: ({ row }: { row: { original: Resources } }) => {
const resourceNo = row.original.resource_no
const name = getName(row.original)
const expireAt = getExpireAt(row.original)
return (
<div className="flex flex-col gap-1">
<div>{name}</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">{resourceNo}</span>
<ExpireBadge expireAt={expireAt} />
</div>
</div>
)
},
},
{
header: "类型",
cell: ({ row }: { row: { original: Resources } }) => {
return <ResourceTypeBadge resource={row.original} />
},
},
{
header: "IP时效",
cell: ({ row }: { row: { original: Resources } }) => {
const detail = getResourceDetail(row.original)
const live = detail?.live
if (live === undefined) return "-"
return <span>{isLong ? `${live}小时` : `${live}分钟`}</span>
},
},
{
header: "使用情况",
cell: ({ row }: { row: { original: Resources } }) => {
const detail = getResourceDetail(row.original)
const type = getResourceType(row.original)
if (!detail) return <span>-</span>
if (type === 1) {
// 包时
const todayUsage = getTodayUsage(detail.last_at, detail.daily || 0)
return (
<div className="flex gap-1">
<span>
{todayUsage}/{detail.quota}
</span>
</div>
)
} else {
// 包量
if (isLong) {
return (
<div className="flex gap-1">
{detail.used < detail.quota ? (
<span className="text-green-500"></span>
) : (
<span className="text-red-500"></span>
)}
<span>|</span>
<span>
{detail.used}/{detail.quota}
</span>
</div>
)
} else {
return (
<div className="flex gap-1">
<span>
{detail.used}/{detail.quota}
</span>
</div>
)
}
}
},
},
{
header: "最近使用时间",
cell: ({ row }: { row: { original: Resources } }) => {
const lastAt = getLastAt(row.original)
return lastAt ? formatDateTime(lastAt) : "暂未使用"
},
},
{
header: "开通时间",
cell: ({ row }: { row: { original: Resources } }) => {
return formatDateTime(row.original.created_at)
},
},
...(!isLong
? [
{
header: "到期时间",
cell: ({ row }: { row: { original: Resources } }) => {
return formatDateTime(getExpireAt(row.original))
},
},
]
: []),
{
id: "action",
meta: { pin: "right" },
header: "状态",
cell: ({ row }: { row: { original: Resources } }) => {
const resource = row.original
const isLoading = updatingId === resource.id
const currentActive = resource.active
return (
<div className="flex items-center gap-2">
<Select
value={currentActive ? "0" : "1"}
onValueChange={val => handleStatusChange(resource, val)}
disabled={isLoading}
>
<SelectTrigger className="min-w-20">
<SelectValue placeholder="状态" />
</SelectTrigger>
<SelectContent className="min-w-(--radix-select-trigger-width)">
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
{isLoading && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
)}
</div>
)
},
},
],
[isLong, updatingId, handleStatusChange],
)
return (
<Suspense>
<DataTable<Resources>
{...table}
columns={[
{ header: "ID", accessorKey: "id" },
{ header: "套餐编号", accessorKey: "resource_no" },
{ header: "状态", accessorKey: "active" },
{ header: "类型", accessorKey: "type" },
{ header: "创建时间", accessorKey: "created_at" },
{ header: "更新时间", accessorKey: "updated_at" },
]}
/>
</Suspense>
<div className="flex flex-col gap-3 overflow-hidden">
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg flex-none">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="resource_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入套餐号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="type"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="expired"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-32">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense fallback={<div className="text-center p-4">...</div>}>
<DataTable<Resources>
{...table}
columns={columns}
classNames={{
root: "flex-auto overflow-hidden",
}}
/>
</Suspense>
</div>
)
}

View File

@@ -0,0 +1,213 @@
import { useCallback, useEffect, useState } from "react"
import { toast } from "sonner"
import { getAllPermissions } from "@/actions/permission"
import { updateRole } from "@/actions/role"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
import type { Role } from "@/models/role"
type TreeNode = {
id: number
name: string
description: string
children: TreeNode[]
}
function PermissionRow({
node,
depth,
selected,
onToggle,
}: {
node: TreeNode
depth: number
selected: Set<number>
onToggle: (id: number, checked: boolean) => void
}) {
const hasChildren = node.children.length > 0
return (
<>
<div className={cn("flex items-center gap-2 h-8", hasChildren && "mt-2")}>
<div style={{ width: depth * 16 }} />
<Checkbox
id={`perm-${node.id}`}
checked={selected.has(node.id)}
onCheckedChange={checked => onToggle(node.id, checked === true)}
/>
<label
htmlFor={`perm-${node.id}`}
className={cn(
"cursor-pointer select-none text-sm size-full flex items-center",
hasChildren && "font-bold",
)}
>
{node.description}
</label>
</div>
{node.children.map(child => (
<PermissionRow
key={child.id}
node={child}
depth={depth + 1}
selected={selected}
onToggle={onToggle}
/>
))}
</>
)
}
export function AssignPermissions(props: {
role: Role
onSuccess?: () => void
}) {
const [open, setOpen] = useState(false)
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [nodes, setNodes] = useState<TreeNode[]>([])
const [selected, setSelected] = useState<Set<number>>(new Set())
const fetchPermissions = useCallback(async () => {
setLoading(true)
try {
const resp = await getAllPermissions()
if (!resp.success) throw new Error(resp.message)
const data = resp.data ?? []
const map = new Map<number, TreeNode>()
data.forEach(p => {
map.set(p.id, {
id: p.id,
name: p.name,
description: p.description,
children: [],
})
})
const roots: TreeNode[] = []
data.forEach(p => {
const node = map.get(p.id)
if (!node) return
if (!p.parent_id) {
roots.push(node)
} else {
map.get(p.parent_id)?.children.push(node)
}
})
setNodes(roots)
} catch (error) {
toast.error(error instanceof Error ? error.message : "获取权限列表失败")
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (open) fetchPermissions()
}, [open, fetchPermissions])
const handleToggle = useCallback((id: number, checked: boolean) => {
setSelected(prev => {
const next = new Set(prev)
if (checked) {
next.add(id)
} else {
next.delete(id)
}
return next
})
}, [])
const handleSubmit = async () => {
setSubmitting(true)
try {
const resp = await updateRole({
id: props.role.id,
permissions: Array.from(selected),
})
if (resp.success) {
toast.success("权限分配成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message ?? "权限分配失败")
}
} catch (error) {
toast.error(error instanceof Error ? error.message : "接口请求错误")
} finally {
setSubmitting(false)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
setSelected(new Set((props.role.permissions ?? []).map(p => p.id)))
} else {
setSelected(new Set())
setNodes([])
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle> · {props.role.name}</DialogTitle>
</DialogHeader>
<div className="max-h-[60vh] overflow-y-auto pr-1">
{loading ? (
<div className="py-8 text-center text-sm text-muted-foreground">
...
</div>
) : nodes.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
</div>
) : (
<div className="flex flex-col">
{nodes.map(node => (
<PermissionRow
key={node.id}
node={node}
depth={0}
selected={selected}
onToggle={handleToggle}
/>
))}
</div>
)}
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button onClick={handleSubmit} disabled={submitting || loading}>
{submitting ? "保存中..." : "保存"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,123 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { createRole } from "@/actions/role"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
const schema = z.object({
name: z.string().min(1, "请输入角色名称"),
description: z.string().optional(),
})
export function CreateRole(props: { onSuccess?: () => void }) {
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
name: "",
description: "",
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await createRole(data)
if (resp.success) {
form.reset()
toast.success("角色创建成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const [open, setOpen] = useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button></Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="role-create" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="role-create-name"></FieldLabel>
<Input
id="role-create-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="description"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="role-create-description">
</FieldLabel>
<Textarea
id="role-create-description"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="role-create">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,224 @@
"use client"
import { Suspense, useState } from "react"
import { toast } from "sonner"
import { deleteRole, getPageRole, updateRole } from "@/actions/role"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card"
import type { Permission } from "@/models/permission"
import type { Role } from "@/models/role"
import { AssignPermissions } from "./assign-permissions"
import { CreateRole } from "./create"
import { UpdateRole } from "./update"
export default function RolesPage() {
const table = useDataTable((page, size) => getPageRole({ page, size }))
return (
<Page>
{/* 操作栏 */}
<div className="flex justify-between items-stretch">
<div className="flex gap-3">
<CreateRole onSuccess={table.refresh} />
</div>
</div>
{/* 数据表 */}
<Suspense>
<DataTable
{...table}
columns={[
{ header: "名称", accessorKey: "name" },
{ header: "描述", accessorKey: "description" },
{
header: "状态",
accessorFn: row => (row.active ? "启用" : "停用"),
},
{
header: "权限",
cell: ({ row }) => (
<PermissionsCell permissions={row.original.permissions ?? []} />
),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ({ row }) => (
<div className="flex gap-2">
<UpdateRole role={row.original} onSuccess={table.refresh} />
<AssignPermissions
role={row.original}
onSuccess={table.refresh}
/>
<ToggleActiveButton
role={row.original}
onSuccess={table.refresh}
/>
<DeleteButton role={row.original} onSuccess={table.refresh} />
</div>
),
},
]}
/>
</Suspense>
</Page>
)
}
function PermissionsCell({ permissions }: { permissions: Permission[] }) {
if (!permissions || permissions.length === 0) {
return <span className="text-muted-foreground text-xs"></span>
}
const preview = permissions.slice(0, 3)
const rest = permissions.length - preview.length
return (
<HoverCard>
<HoverCardTrigger asChild>
<div className="flex flex-wrap gap-1 cursor-default max-w-52">
{preview.map(p => (
<Badge key={p.id} variant="secondary">
{p.description}
</Badge>
))}
{rest > 0 && <Badge variant="outline">+{rest}</Badge>}
</div>
</HoverCardTrigger>
<HoverCardContent className="w-72" align="start">
<p className="text-xs font-medium text-muted-foreground mb-2">
{permissions.length}
</p>
<div className="flex flex-wrap gap-1.5">
{permissions.map(p => (
<Badge key={p.id} variant="secondary">
{p.description}
</Badge>
))}
</div>
</HoverCardContent>
</HoverCard>
)
}
function ToggleActiveButton({
role,
onSuccess,
}: {
role: Role
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await updateRole({ id: role.id, active: !role.active })
if (resp.success) {
toast.success(role.active ? "已停用" : "已启用")
onSuccess?.()
} else {
toast.error(resp.message ?? "操作失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="secondary" disabled={loading}>
{role.active ? "停用" : "启用"}
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle>
{role.active ? "停用" : "启用"}
</AlertDialogTitle>
<AlertDialogDescription>
{role.active ? "停用" : "启用"}{role.name}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={handleConfirm}></AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
function DeleteButton({
role,
onSuccess,
}: {
role: Role
onSuccess?: () => void
}) {
const [loading, setLoading] = useState(false)
const handleConfirm = async () => {
setLoading(true)
try {
const resp = await deleteRole(role.id)
if (resp.success) {
toast.success("删除成功")
onSuccess?.()
} else {
toast.error(resp.message ?? "删除失败")
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
} finally {
setLoading(false)
}
}
return (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button size="sm" variant="destructive" disabled={loading}>
</Button>
</AlertDialogTrigger>
<AlertDialogContent size="sm">
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
{role.name}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={handleConfirm}>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View File

@@ -0,0 +1,135 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import z from "zod"
import { updateRole } from "@/actions/role"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import type { Role } from "@/models/role"
const schema = z.object({
name: z.string().min(1, "请输入角色名称"),
description: z.string().optional(),
})
export function UpdateRole(props: { role: Role; onSuccess?: () => void }) {
const [open, setOpen] = useState(false)
const form = useForm({
resolver: zodResolver(schema),
defaultValues: {
name: props.role.name,
description: props.role.description ?? "",
},
})
const onSubmit = async (data: z.infer<typeof schema>) => {
try {
const resp = await updateRole({ id: props.role.id, ...data })
if (resp.success) {
toast.success("角色修改成功")
props.onSuccess?.()
setOpen(false)
} else {
toast.error(resp.message)
}
} catch (error) {
const message = error instanceof Error ? error.message : error
toast.error(`接口请求错误: ${message}`)
}
}
const handleOpenChange = (value: boolean) => {
if (value) {
form.reset({
name: props.role.name,
description: props.role.description ?? "",
})
}
setOpen(value)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button size="sm" variant="secondary">
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
<form id="role-update" onSubmit={form.handleSubmit(onSubmit)}>
<FieldGroup>
<Controller
control={form.control}
name="name"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="role-update-name"></FieldLabel>
<Input
id="role-update-name"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
control={form.control}
name="description"
render={({ field, fieldState }) => (
<Field>
<FieldLabel htmlFor="role-update-description">
</FieldLabel>
<Textarea
id="role-update-description"
{...field}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</form>
<DialogFooter>
<DialogClose asChild>
<Button variant="ghost"></Button>
</DialogClose>
<Button type="submit" form="role-update">
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

14
src/app/(root)/scopes.tsx Normal file
View File

@@ -0,0 +1,14 @@
"use client"
import { useSetAtom } from "jotai"
import { scopesAtom } from "@/lib/stores/scopes"
import type { Admin } from "@/models/admin"
export default function SetScopes(props: {
admin: Admin & { scopes: string[] }
}) {
const setScopes = useSetAtom(scopesAtom)
console.log("用户权限", props.admin.scopes)
setScopes(props.admin.scopes)
return null
}

View File

@@ -1,5 +0,0 @@
"use client"
export default function SecurityPage() {
return <div>~</div>
}

View File

@@ -1,129 +1,373 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { CheckCircle, Clock, XCircle } from "lucide-react"
import { Suspense } from "react"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { getPageTrade } from "@/actions/trade"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import type { Trade } from "@/models/trade"
type FilterValues = {
user_phone?: string
inner_no?: string
method?: number
platform?: number
status?: number
created_at_start?: Date
created_at_end?: Date
}
const filterSchema = z
.object({
user_phone: z
.string()
.optional()
.transform(val => val?.trim()),
inner_no: z
.string()
.optional()
.transform(val => val?.trim()),
method: z.string().optional(),
platform: z.string().optional(),
status: z.string().optional(),
created_at_start: z.string().optional(),
created_at_end: z.string().optional(),
})
.superRefine((data, ctx) => {
if (data.created_at_start && data.created_at_end) {
const start = new Date(data.created_at_start)
const end = new Date(data.created_at_end)
if (end < start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "结束时间不能早于开始时间",
path: ["created_at_end"],
})
}
}
})
type FilterSchema = z.infer<typeof filterSchema>
export default function TradePage() {
const table = useDataTable<Trade>((page, size) =>
getPageTrade({ page, size }),
const [filters, setFilters] = useState<FilterValues>({})
const { control, handleSubmit, reset } = useForm<FilterSchema>({
resolver: zodResolver(filterSchema),
defaultValues: {
user_phone: "",
inner_no: "",
method: "all",
platform: "all",
status: "all",
created_at_start: "",
created_at_end: "",
},
})
const fetchTrades = useCallback(
(page: number, size: number) => {
return getPageTrade({ page, size, ...filters })
},
[filters],
)
const table = useDataTable<Trade>(fetchTrades)
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.user_phone?.trim()) result.user_phone = data.user_phone.trim()
if (data.inner_no?.trim()) result.inner_no = data.inner_no.trim()
if (data.method && data.method !== "all")
result.method = Number(data.method)
if (data.platform && data.platform !== "all")
result.platform = Number(data.platform)
if (data.status && data.status !== "all")
result.status = Number(data.status)
if (data.created_at_start)
result.created_at_start = new Date(data.created_at_start)
if (data.created_at_end)
result.created_at_end = new Date(data.created_at_end)
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<Suspense>
<DataTable<Trade>
{...table}
columns={[
{ header: "ID", accessorKey: "id" },
{ header: "套餐号", accessorKey: "inner_no" },
{
header: "支付方式",
accessorKey: "method",
cell: ({ row }) => {
const methodMap: Record<number, string> = {
1: "支付宝",
2: "微信",
3: "其他",
4: "支付宝",
5: "微信",
}
return (
<div>{methodMap[row.original.method as number] || "未知"}</div>
)
},
},
{
header: "支付金额",
accessorKey: "payment",
cell: ({ row }) => {
const payment =
typeof row.original.payment === "string"
? parseFloat(row.original.payment)
: row.original.payment || 0
return (
<div className="flex gap-1">
<span
className={
payment > 0 ? "text-green-500" : "text-orange-500"
}
>
{payment.toFixed(2)}
</span>
</div>
)
},
},
{
header: "支付平台",
accessorKey: "platform",
cell: ({ row }) => {
const platform = row.original.platform
if (!platform) return <span>-</span>
return (
<div className="flex items-center gap-2">
{platform === 1 ? (
<span></span>
) : platform === 2 ? (
<span></span>
) : (
<span>-</span>
)}
</div>
)
},
},
// { header: "已退款", accessorKey: "refunded" },
{
header: "支付状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
<Page>
{/* 筛选表单 */}
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="user_phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入会员号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
switch (status) {
case 0:
return (
<div className="flex items-center gap-2 text-yellow-600">
<Clock className="h-4 w-4" />
<span></span>
</div>
)
case 1:
return (
<div className="flex items-center gap-2 text-green-600">
<CheckCircle className="h-4 w-4" />
<span></span>
</div>
)
case 2:
return (
<div className="flex items-center gap-2 text-gray-500">
<XCircle className="h-4 w-4" />
<span></span>
</div>
)
default:
return <span className="text-gray-400">-</span>
}
<Controller
name="inner_no"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入订单号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="method"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
<SelectItem value="3"></SelectItem>
<SelectItem value="4"></SelectItem>
<SelectItem value="5"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="platform"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid} className="w-24">
<FieldLabel></FieldLabel>
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="全部" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="0"></SelectItem>
<SelectItem value="1"></SelectItem>
<SelectItem value="2"></SelectItem>
</SelectContent>
</Select>
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_start"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
<Controller
name="created_at_end"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input type="date" {...field} />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
table.pagination.onPageChange(1)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<Trade>
{...table}
columns={[
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
},
{ header: "购买套餐", accessorKey: "subject" },
{ header: "类型", accessorKey: "type" },
{
header: "创建时间",
accessorKey: "created_at",
cell: ({ row }) =>
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
header: "更新时间",
accessorKey: "updated_at",
cell: ({ row }) =>
format(new Date(row.original.updated_at), "yyyy-MM-dd HH:mm"),
},
]}
/>
</Suspense>
{ header: "会员号", accessorFn: row => row.user?.phone || "" },
{ header: "订单号", accessorKey: "inner_no" },
{ header: "购买套餐", accessorKey: "subject" },
{
header: "支付金额",
accessorKey: "payment",
cell: ({ row }) => {
const payment =
typeof row.original.payment === "string"
? parseFloat(row.original.payment)
: row.original.payment || 0
return (
<div className="flex gap-1">
<span
className={
payment > 0 ? "text-green-500" : "text-orange-500"
}
>
{payment.toFixed(2)}
</span>
</div>
)
},
},
{
header: "支付状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
switch (status) {
case 0:
return (
<div className="flex items-center gap-2 text-yellow-600">
<Clock className="h-4 w-4" />
<span></span>
</div>
)
case 1:
return (
<div className="flex items-center gap-2 text-green-600">
<CheckCircle className="h-4 w-4" />
<span></span>
</div>
)
case 2:
return (
<div className="flex items-center gap-2 text-gray-500">
<XCircle className="h-4 w-4" />
<span></span>
</div>
)
default:
return <span className="text-gray-400">-</span>
}
},
},
{
header: "支付平台",
accessorKey: "platform",
cell: ({ row }) => {
const platform = row.original.platform
if (!platform) return <span>-</span>
return (
<div className="flex items-center gap-2">
{platform === 1 ? (
<span></span>
) : platform === 2 ? (
<span></span>
) : (
<span>-</span>
)}
</div>
)
},
},
{
header: "支付渠道",
accessorKey: "method",
cell: ({ row }) => {
const methodMap: Record<number, string> = {
1: "支付宝",
2: "微信",
3: "商福通",
4: "商福通渠道支付宝",
5: "商福通渠道微信",
}
return (
<div>
{methodMap[row.original.method as number] || "未知"}
</div>
)
},
},
{ header: "渠道订单号", accessorKey: "outer_no" },
]}
/>
</Suspense>
</Page>
)
}

View File

@@ -1,24 +1,105 @@
"use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { Suspense } from "react"
import { bindAdmin, getPageUsers } from "@/actions/user"
import { Suspense, useCallback, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
import { bindAdmin, getPageUserPage } from "@/actions/user"
import { Auth } from "@/components/auth"
import { DataTable, useDataTable } from "@/components/data-table"
import { Page } from "@/components/page"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { useFetch } from "@/hooks/data"
import { ScopeUserWriteBind } from "@/lib/scopes"
import type { User } from "@/models/user"
interface FilterValues {
phone?: string
}
const filterSchema = z.object({
phone: z.string().optional(),
})
type FormValues = z.infer<typeof filterSchema>
export default function UserPage() {
const table = useDataTable<User>((page, size) => getPageUsers({ page, size }))
const [filters, setFilters] = useState<FilterValues>({})
const [loading, setLoading] = useState(false)
const { control, handleSubmit, reset } = useForm<FormValues>({
resolver: zodResolver(filterSchema),
defaultValues: {
phone: "",
},
})
const fetchUsers = useCallback(
(page: number, size: number) => getPageUserPage({ page, size, ...filters }),
[filters],
)
const table = useDataTable<User>(fetchUsers)
const bind = useFetch(table, (id: number) => bindAdmin({ id }), {
done: "用户已认领",
fail: "用户认领失败",
})
const onFilter = handleSubmit(data => {
const result: FilterValues = {}
if (data.phone?.trim()) result.phone = data.phone.trim()
setFilters(result)
table.pagination.onPageChange(1)
})
return (
<div>
<Page>
<form onSubmit={onFilter} className="bg-card p-4 rounded-lg">
<div className="flex flex-wrap items-end gap-4">
<Controller
name="phone"
control={control}
render={({ field, fieldState }) => (
<Field
data-invalid={fieldState.invalid}
className="w-40 flex-none"
>
<FieldLabel></FieldLabel>
<Input {...field} placeholder="请输入手机号" />
<FieldError>{fieldState.error?.message}</FieldError>
</Field>
)}
/>
</div>
<FieldGroup className="flex-row justify-start mt-4 gap-2">
<Button type="submit"></Button>
<Button
type="button"
variant="outline"
onClick={() => {
reset()
setFilters({})
setLoading(false)
}}
>
</Button>
</FieldGroup>
</form>
<Suspense>
<DataTable<User>
{...table}
status={loading ? "load" : "done"}
columns={[
{ header: "账号", accessorKey: "username" },
{ header: "手机", accessorKey: "phone" },
@@ -28,60 +109,68 @@ export default function UserPage() {
header: "余额",
accessorKey: "balance",
cell: ({ row }) => {
const balance =
typeof row.original.balance === "string"
? parseFloat(row.original.balance)
: row.original.balance || 0
const balance = Number(row.original.balance) || 0
return (
<div className="flex gap-1">
<span
className={
balance > 0 ? "text-green-500" : "text-orange-500"
}
>
{balance.toFixed(2)}
</span>
</div>
<span
className={
balance > 0 ? "text-green-500" : "text-orange-500"
}
>
{balance.toFixed(2)}
</span>
)
},
},
{
header: "认证状态",
header: "实名状态",
accessorKey: "id_type",
cell: ({ row }) => (
<Badge
variant={row.original.id_type === 1 ? "default" : "secondary"}
className={
row.original.id_type === 1
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
}
>
{row.original.id_type === 1 ? "已认证" : "未认证"}
</Badge>
),
},
{
header: "客户来源",
accessorKey: "source",
cell: ({ row }) => {
const status = row.original.id_type
return (
<Badge
variant={status === 1 ? "default" : "secondary"}
className={
status === 1
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
}
>
{status === 1 ? "已认证" : "未认证"}
</Badge>
)
const sourceMap: Record<number, string> = {
0: "官网注册",
1: "管理员添加",
2: "代理商注册",
3: "代理商添加",
}
return sourceMap[row.original.source] ?? "未知"
},
},
{
header: "账号状态",
accessorKey: "status",
cell: ({ row }) => {
const status = row.original.status
return status === 1 ? "正常" : ""
},
cell: ({ row }) => (row.original.status === 1 ? "正常" : "禁用"),
},
{ header: "联系方式", accessorKey: "contact_wechat" },
{
header: "管理员",
cell: ({ row }) => row.original.admin?.name,
},
{
header: "最后登录时间",
accessorKey: "last_login",
cell: ({ row }) =>
format(new Date(row.original.last_login), "yyyy-MM-dd HH:mm"),
row.original.last_login
? format(
new Date(row.original.last_login),
"yyyy-MM-dd HH:mm",
)
: "",
},
{
header: "最后登录IP",
accessorKey: "last_login_ip",
cell: ({ row }) => row.original.last_login_ip || "",
},
{
header: "创建时间",
@@ -90,20 +179,24 @@ export default function UserPage() {
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ctx => (
<Button
size={"sm"}
onClick={() => bind(ctx.row.original.id)}
disabled={!!ctx.row.original.admin_id}
>
{ctx.row.original.admin_id ? "已认领" : "认领"}
</Button>
<Auth scope={ScopeUserWriteBind}>
<Button
size="sm"
onClick={() => bind(ctx.row.original.id)}
disabled={!!ctx.row.original.admin_id}
>
{ctx.row.original.admin_id ? "已认领" : "认领"}
</Button>
</Auth>
),
},
]}
/>
</Suspense>
</div>
</Page>
)
}

View File

@@ -3,122 +3,122 @@
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.13 0.028 261.692);
--card: oklch(1 0 0);
--card-foreground: oklch(0.13 0.028 261.692);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.13 0.028 261.692);
--primary: oklch(0.7 0.12 265);
--primary-foreground: oklch(0.985 0.002 247.839);
--secondary: oklch(0.967 0.003 264.542);
--secondary-foreground: oklch(0.21 0.034 264.665);
--muted: oklch(0.967 0.003 264.542);
--muted-foreground: oklch(0.551 0.027 264.364);
--accent: oklch(0.967 0.003 264.542);
--accent-foreground: oklch(0.21 0.034 264.665);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.928 0.006 264.531);
--input: oklch(0.928 0.006 264.531);
--ring: oklch(0.7 0.12 265);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0.002 247.839);
--sidebar-foreground: oklch(0.13 0.028 261.692);
--sidebar-primary: oklch(0.21 0.034 264.665);
--sidebar-primary-foreground: oklch(0.985 0.002 247.839);
--sidebar-accent: oklch(0.967 0.003 264.542);
--sidebar-accent-foreground: oklch(0.21 0.034 264.665);
--sidebar-border: oklch(0.928 0.006 264.531);
--sidebar-ring: oklch(0.707 0.022 261.325);
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.13 0.028 261.692);
--card: oklch(1 0 0);
--card-foreground: oklch(0.13 0.028 261.692);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.13 0.028 261.692);
--primary: oklch(0.7 0.12 265);
--primary-foreground: oklch(0.985 0.002 247.839);
--secondary: oklch(0.967 0.003 264.542);
--secondary-foreground: oklch(0.21 0.034 264.665);
--muted: oklch(0.967 0.003 264.542);
--muted-foreground: oklch(0.551 0.027 264.364);
--accent: oklch(0.967 0.003 264.542);
--accent-foreground: oklch(0.21 0.034 264.665);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.928 0.006 264.531);
--input: oklch(0.928 0.006 264.531);
--ring: oklch(0.7 0.12 265);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0.002 247.839);
--sidebar-foreground: oklch(0.13 0.028 261.692);
--sidebar-primary: oklch(0.21 0.034 264.665);
--sidebar-primary-foreground: oklch(0.985 0.002 247.839);
--sidebar-accent: oklch(0.967 0.003 264.542);
--sidebar-accent-foreground: oklch(0.21 0.034 264.665);
--sidebar-border: oklch(0.928 0.006 264.531);
--sidebar-ring: oklch(0.707 0.022 261.325);
}
.dark {
--background: oklch(0.13 0.028 261.692);
--foreground: oklch(0.985 0.002 247.839);
--card: oklch(0.21 0.034 264.665);
--card-foreground: oklch(0.985 0.002 247.839);
--popover: oklch(0.21 0.034 264.665);
--popover-foreground: oklch(0.985 0.002 247.839);
--primary: oklch(0.928 0.006 264.531);
--primary-foreground: oklch(0.21 0.034 264.665);
--secondary: oklch(0.278 0.033 256.848);
--secondary-foreground: oklch(0.985 0.002 247.839);
--muted: oklch(0.278 0.033 256.848);
--muted-foreground: oklch(0.707 0.022 261.325);
--accent: oklch(0.278 0.033 256.848);
--accent-foreground: oklch(0.985 0.002 247.839);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.551 0.027 264.364);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.034 264.665);
--sidebar-foreground: oklch(0.985 0.002 247.839);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0.002 247.839);
--sidebar-accent: oklch(0.278 0.033 256.848);
--sidebar-accent-foreground: oklch(0.985 0.002 247.839);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.551 0.027 264.364);
--background: oklch(0.13 0.028 261.692);
--foreground: oklch(0.985 0.002 247.839);
--card: oklch(0.21 0.034 264.665);
--card-foreground: oklch(0.985 0.002 247.839);
--popover: oklch(0.21 0.034 264.665);
--popover-foreground: oklch(0.985 0.002 247.839);
--primary: oklch(0.928 0.006 264.531);
--primary-foreground: oklch(0.21 0.034 264.665);
--secondary: oklch(0.278 0.033 256.848);
--secondary-foreground: oklch(0.985 0.002 247.839);
--muted: oklch(0.278 0.033 256.848);
--muted-foreground: oklch(0.707 0.022 261.325);
--accent: oklch(0.278 0.033 256.848);
--accent-foreground: oklch(0.985 0.002 247.839);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.551 0.027 264.364);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.21 0.034 264.665);
--sidebar-foreground: oklch(0.985 0.002 247.839);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0.002 247.839);
--sidebar-accent: oklch(0.278 0.033 256.848);
--sidebar-accent-foreground: oklch(0.985 0.002 247.839);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.551 0.027 264.364);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@@ -36,7 +36,6 @@ export default function LoginPage() {
})
const router = useRouter()
const onSubmit = async (data: Schema) => {
try {
const resp = await login(data)
@@ -46,6 +45,7 @@ export default function LoginPage() {
// 登录成功后跳转到首页
router.push("/")
router.refresh()
} catch (e) {
toast.error("登录失败", {
description: e instanceof Error ? e.message : "未知错误",

View File

@@ -0,0 +1,13 @@
import { useAtomValue } from "jotai"
import type { ReactNode } from "react"
import { scopesAtom } from "@/lib/stores/scopes"
export function Auth(props: { scope: string; children: ReactNode }) {
const scopes = useAtomValue(scopesAtom)
if (!scopes.length) return props.children
const hasScope = scopes.some(s => props.scope.startsWith(s))
if (!hasScope) return null
return props.children
}

View File

@@ -1,17 +1,20 @@
import {
type AccessorKeyColumnDef,
type Column,
type ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table"
import { Loader } from "lucide-react"
import type { CSSProperties } from "react"
import { Pagination, type PaginationProps } from "@/components/ui/pagination"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
Table as TableRoot,
TableRow,
} from "@/components/ui/table"
import { cn } from "@/lib/utils"
@@ -20,11 +23,13 @@ export type DataTableProps<T> = {
data: T[]
status: "load" | "done" | "fail"
columns: ColumnDef<T>[]
pagination: PaginationProps
pagination?: PaginationProps
classNames?: {
root?: string
headRow?: string
dataRow?: string
}
serial?: boolean
}
export function DataTable<T extends Record<string, unknown>>(
@@ -32,29 +37,83 @@ export function DataTable<T extends Record<string, unknown>>(
) {
const table = useReactTable({
data: props.data,
columns: props.columns,
columns: [
{
id: "serial",
header: "#",
cell: ({ row }) => row.index + 1,
},
...props.columns,
],
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
rowCount: props.pagination.total,
rowCount: props.pagination?.total,
state: {
pagination: {
pagination: props.pagination && {
pageIndex: props.pagination.page,
pageSize: props.pagination.size,
},
columnFilters: [],
},
initialState: {
columnPinning: {
left: props.columns
.map(column =>
(column.meta as Record<string, unknown>)?.pin === "left"
? column.id || (column as AccessorKeyColumnDef<T>).accessorKey
: undefined,
)
.filter(Boolean) as string[],
right: props.columns
.map(column =>
(column.meta as Record<string, unknown>)?.pin === "right"
? column.id || (column as AccessorKeyColumnDef<T>).accessorKey
: undefined,
)
.filter(Boolean) as string[],
},
},
})
const pinStyle = (column: Column<T>, header?: boolean) => {
const pinned = column.getIsPinned()
if (!pinned) return {}
return {
left: {
left: column.getStart(pinned),
boxShadow: header
? "inset -1px -1px var(--border)"
: "inset -1px 0 var(--border)",
} as CSSProperties,
right: {
right: column.getAfter(pinned),
boxShadow: header
? "inset 1px -1px var(--border)"
: "inset 1px 0 var(--border)",
} as CSSProperties,
}[pinned]
}
return (
<div className="flex flex-col gap-3">
<div
className={cn(
"flex-auto flex flex-col gap-3 overflow-hidden",
props.classNames?.root,
)}
>
{/* 数据表 */}
<div className="rounded-md relative bg-card">
<TableRoot>
<div className="flex-auto overflow-hidden relative">
<Table className="max-w-full max-h-full">
<TableHeader>
{table.getHeaderGroups().map(group => (
<TableRow key={group.id}>
{group.headers.map(header => (
<TableHead key={header.id} colSpan={header.colSpan}>
<TableHead
key={header.id}
colSpan={header.colSpan}
className="sticky top-0 bg-card z-20 shadow-[inset_0_-1px_var(--border)]"
style={pinStyle(header.column, true)}
>
{header.isPlaceholder
? null
: flexRender(
@@ -93,7 +152,11 @@ export function DataTable<T extends Record<string, unknown>>(
className={cn("h-14", props.classNames?.dataRow)}
>
{row.getVisibleCells().map(cell => (
<TableCell key={cell.id}>
<TableCell
key={cell.id}
className="sticky bg-card z-10"
style={pinStyle(cell.column)}
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
@@ -104,9 +167,9 @@ export function DataTable<T extends Record<string, unknown>>(
))
)}
</TableBody>
</TableRoot>
</Table>
{props.status === "load" && (
<div className="absolute inset-0 bg-white/10 backdrop-blur-xs flex items-center justify-center gap-2 transition">
<div className="absolute inset-0 bg-white/10 backdrop-blur-xs flex items-center justify-center gap-2 transition z-50">
<Loader className="animate-spin" />
<span></span>
</div>
@@ -114,7 +177,9 @@ export function DataTable<T extends Record<string, unknown>>(
</div>
{/* 分页器 */}
<Pagination {...props.pagination} />
{props.pagination && (
<Pagination {...props.pagination} className="flex-none self-center" />
)}
</div>
)
}

View File

@@ -14,11 +14,11 @@ export function useDataTable<T>(
const [size, setSize] = useState(10)
const [total, setTotal] = useState(0)
const refresh = useCallback(
async (page: number, size: number) => {
const _refresh = useCallback(
async (_page: number, _size: number) => {
setStatus("load")
try {
const resp = await fetch(page, size)
const resp = await fetch(_page, _size)
if (!resp.success) {
throw new Error("获取数据失败")
}
@@ -37,18 +37,19 @@ export function useDataTable<T>(
[fetch, setStatus],
)
const onPageChange = (page: number) => {
setPage(page)
}
const onPageChange = useCallback(
(page: number) => _refresh(page, size),
[_refresh, size],
)
const onSizeChange = (size: number) => {
setPage(1)
setSize(size)
}
const onSizeChange = useCallback(
(size: number) => _refresh(1, size),
[_refresh],
)
useEffect(() => {
refresh(page, size).then()
}, [refresh, page, size])
_refresh(1, size)
}, [_refresh, size])
return {
data,
@@ -61,6 +62,8 @@ export function useDataTable<T>(
onPageChange,
onSizeChange,
},
refresh,
refresh: (_page?: number, _size?: number) => {
_refresh(_page ?? page, _size ?? size)
},
}
}

10
src/components/page.tsx Normal file
View File

@@ -0,0 +1,10 @@
import type { ReactNode } from "react"
import { cn } from "@/lib/utils"
export function Page(props: { className?: string; children: ReactNode }) {
return (
<div className={cn("h-full flex flex-col p-6 gap-4", props.className)}>
{props.children}
</div>
)
}

View File

@@ -0,0 +1,62 @@
import type { ReactNode } from "react"
import { Badge } from "@/components/ui/badge"
import { ProductCode } from "@/lib/base"
interface SkuCodeBadgeProps {
productCode: ProductCode
skuCode: string
}
export function SkuCodeBadge({
productCode,
skuCode,
}: SkuCodeBadgeProps): ReactNode {
switch (productCode) {
case ProductCode.Short:
case ProductCode.Long:
return <ParsedSkuCodeBadge skuCode={skuCode} />
default:
return <Badge variant="outline">{skuCode}</Badge>
}
}
function ParsedSkuCodeBadge({ skuCode }: { skuCode: string }): ReactNode {
const params = new URLSearchParams(skuCode)
const modeStr = params.get("mode")
let mode: string | undefined
let modeClass: string | undefined
switch (modeStr) {
case "time":
mode = "包时"
modeClass = "bg-green-50"
break
case "quota":
mode = "包量"
modeClass = "bg-blue-50"
break
}
const live = params.get("live")
const expire = params.get("expire")
if (!mode || !live || !expire) {
return (
<Badge variant="secondary" className="bg-red-50">
{skuCode}
</Badge>
)
}
return (
<div className="flex flex-wrap gap-1">
<Badge variant="secondary" className={modeClass}>
{mode}
</Badge>
<Badge variant="secondary">{live} </Badge>
{expire !== "0" && (
<Badge variant="secondary">{expire} </Badge>
)}
</div>
)
}

View File

@@ -0,0 +1,198 @@
import type { ChangeEvent } from "react"
import {
type Control,
type Path,
type UseControllerReturn,
useController,
} from "react-hook-form"
import { ProductCode } from "@/lib/base"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
FieldLegend,
} from "../ui/field"
import { Input } from "../ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "../ui/select"
export function ProductCodeField<
T extends {
code: string
},
>(props: { control: Control<T>; name: Path<T>; code: ProductCode }) {
const rt = useController(props)
switch (props.code) {
case ProductCode.Short:
return <ProductShortCode {...rt} />
case ProductCode.Long:
return <ProductLongCode {...rt} />
}
return null
}
function ProductShortCode<T extends { code: string }>(
props: UseControllerReturn<T>,
) {
const { field, fieldState } = props
const params = new URLSearchParams(field.value)
const mode = params.get("mode") || "quota"
const live = params.get("live") || "0"
const expire = params.get("expire") || "0"
const setParams = (data: {
mode?: string
live?: string
expire?: string
}) => {
const newParams = new URLSearchParams()
newParams.set("mode", data.mode || mode)
newParams.set("live", data.live || live)
newParams.set("expire", data.expire || expire)
console.log(newParams.toString())
field.onChange(newParams.toString())
}
const onModeChange = (value: string) => {
setParams({ mode: value })
}
const onLiveChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
value = value.substring(1, value.length)
}
if (!/^([0-9]+)$/.test(value)) return
setParams({ live: value })
}
const onExpireChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
value = value.substring(1, value.length)
}
if (!/^([0-9]+)$/.test(value)) return
setParams({ expire: value })
}
return (
<FieldLegend>
<FieldLegend></FieldLegend>
<FieldGroup>
<Field>
<FieldLabel></FieldLabel>
<Select defaultValue={mode} onValueChange={onModeChange}>
<SelectTrigger>
<SelectValue placeholder="请选择套餐类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value="time"></SelectItem>
<SelectItem value="quota"></SelectItem>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel></FieldLabel>
<Input type="number" value={live} onChange={onLiveChange} />
</Field>
{params.get("mode") === "time" && (
<Field>
<FieldLabel></FieldLabel>
<Input type="number" value={expire} onChange={onExpireChange} />
</Field>
)}
{fieldState.error && <FieldError errors={[fieldState.error]} />}
</FieldGroup>
</FieldLegend>
)
}
function ProductLongCode<T extends { code: string }>(
props: UseControllerReturn<T>,
) {
const { field, fieldState } = props
const params = new URLSearchParams(field.value)
const mode = params.get("mode") || "quota"
const live = params.get("live") || "0"
const expire = params.get("expire") || "0"
const setParams = (data: {
mode?: string
live?: string
expire?: string
}) => {
const newParams = new URLSearchParams()
newParams.set("mode", data.mode || mode)
newParams.set("live", data.live || live)
newParams.set("expire", data.expire || expire)
console.log(newParams.toString())
field.onChange(newParams.toString())
}
const onModeChange = (value: string) => {
if (value === "quota") {
setParams({ mode: value, expire: "0" })
} else {
setParams({ mode: value })
}
}
const onLiveChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
value = value.substring(1, value.length)
}
if (!/^([0-9]+)$/.test(value)) return
setParams({ live: value })
}
const onExpireChange = (e: ChangeEvent<HTMLInputElement>) => {
let value = e.target.value || "0"
if (value.length > 1 && value[0] === "0") {
value = value.substring(1, value.length)
}
if (!/^([0-9]+)$/.test(value)) return
setParams({ expire: value })
}
return (
<FieldLegend>
<FieldLegend></FieldLegend>
<FieldGroup>
<Field>
<FieldLabel></FieldLabel>
<Select defaultValue={mode} onValueChange={onModeChange}>
<SelectTrigger>
<SelectValue placeholder="请选择套餐类型" />
</SelectTrigger>
<SelectContent>
<SelectItem value="time"></SelectItem>
<SelectItem value="quota"></SelectItem>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel></FieldLabel>
<Input type="number" value={live} onChange={onLiveChange} />
</Field>
{params.get("mode") === "time" && (
<Field>
<FieldLabel></FieldLabel>
<Input type="number" value={expire} onChange={onExpireChange} />
</Field>
)}
{fieldState.error && <FieldError errors={[fieldState.error]} />}
</FieldGroup>
</FieldLegend>
)
}

View File

@@ -0,0 +1,195 @@
"use client"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import type * as React from "react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[size=default]:sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className,
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className,
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className,
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -1,6 +1,6 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -22,7 +22,7 @@ const badgeVariants = cva(
defaultVariants: {
variant: "default",
},
}
},
)
function Badge({

View File

@@ -1,6 +1,6 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -13,7 +13,7 @@ const buttonVariants = cva(
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
"border bg-background hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
@@ -33,7 +33,7 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
},
)
function Button({

View File

@@ -0,0 +1,157 @@
"use client"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import type * as React from "react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -1,11 +1,10 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { useMemo } from "react"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
@@ -14,7 +13,7 @@ function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
className,
)}
{...props}
/>
@@ -34,7 +33,7 @@ function FieldLegend({
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
className,
)}
{...props}
/>
@@ -47,7 +46,7 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className
className,
)}
{...props}
/>
@@ -75,7 +74,7 @@ const fieldVariants = cva(
defaultVariants: {
orientation: "vertical",
},
}
},
)
function Field({
@@ -100,7 +99,7 @@ function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
className,
)}
{...props}
/>
@@ -118,7 +117,7 @@ function FieldLabel({
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
className,
)}
{...props}
/>
@@ -131,7 +130,7 @@ function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
className,
)}
{...props}
/>
@@ -146,7 +145,7 @@ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
className,
)}
{...props}
/>
@@ -166,7 +165,7 @@ function FieldSeparator({
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
className,
)}
{...props}
>
@@ -201,10 +200,10 @@ function FieldError({
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
...new Map(errors.map(error => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
if (uniqueErrors?.length === 1) {
return uniqueErrors[0]?.message
}
@@ -212,7 +211,7 @@ function FieldError({
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
error?.message && <li key={index}>{error.message}</li>,
)}
</ul>
)

View File

@@ -0,0 +1,44 @@
"use client"
import { HoverCard as HoverCardPrimitive } from "radix-ui"
import type * as React from "react"
import { cn } from "@/lib/utils"
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
)
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</HoverCardPrimitive.Portal>
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }

View File

@@ -1,4 +1,4 @@
import * as React from "react"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -11,7 +11,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
className,
)}
{...props}
/>

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -14,7 +14,7 @@ function Label({
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
className,
)}
{...props}
/>

View File

@@ -121,13 +121,11 @@ function Pagination({
const paginationItems = generatePaginationItems()
return (
<div
className={`flex flex-wrap items-center justify-end gap-4 ${className || ""}`}
>
<div className={`flex flex-wrap items-center gap-4 ${className || ""}`}>
<div className="flex-none flex items-center gap-2 text-sm text-muted-foreground">
{total}
<Select value={size.toString()} onValueChange={handlePageSizeChange}>
<SelectTrigger className="h-8 w-20 bg-card">
<SelectTrigger className="h-8 w-20">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -195,7 +193,6 @@ function PaginationLayout({
}: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("flex-none", className)}

View File

@@ -1,8 +1,8 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -38,7 +38,7 @@ function SelectTrigger({
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -65,7 +65,7 @@ function SelectContent({
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
className,
)}
position={position}
align={align}
@@ -76,7 +76,7 @@ function SelectContent({
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
)}
>
{children}
@@ -110,7 +110,7 @@ function SelectItem({
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
className,
)}
{...props}
>
@@ -149,7 +149,7 @@ function SelectScrollUpButton({
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>
@@ -167,7 +167,7 @@ function SelectScrollDownButton({
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
className,
)}
{...props}
>

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -18,7 +18,7 @@ function Separator({
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
className,
)}
{...props}
/>

View File

@@ -1,6 +1,6 @@
"use client"
import * as React from "react"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -8,11 +8,11 @@ function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
className={cn("bg-card rounded-lg relative overflow-auto", className)}
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
className="w-full caption-bottom text-sm"
{...props}
/>
</div>
@@ -23,7 +23,7 @@ function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
className={cn("[&_tr]:border-b-0", className)}
{...props}
/>
)
@@ -45,7 +45,7 @@ function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
className,
)}
{...props}
/>
@@ -58,7 +58,7 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
className,
)}
{...props}
/>
@@ -71,7 +71,7 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
className,
)}
{...props}
/>
@@ -84,7 +84,7 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) {
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
className,
)}
{...props}
/>

View File

@@ -1,34 +1,56 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cva, type VariantProps } from "class-variance-authority"
import { Tabs as TabsPrimitive } from "radix-ui"
import type * as React from "react"
import { cn } from "@/lib/utils"
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
data-orientation={orientation}
orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
className,
)}
{...props}
/>
)
}
const tabsListVariants = cva(
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
},
)
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
@@ -42,8 +64,11 @@ function TabsTrigger({
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:-bottom-1.25 group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
className,
)}
{...props}
/>
@@ -63,4 +88,4 @@ function TabsContent({
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }

View File

@@ -0,0 +1,18 @@
import type * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
className,
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -1,7 +1,7 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import type * as React from "react"
import { cn } from "@/lib/utils"
@@ -47,7 +47,7 @@ function TooltipContent({
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
className,
)}
{...props}
>

View File

@@ -1,9 +1,4 @@
import {
type Dispatch,
type SetStateAction,
useCallback,
useState,
} from "react"
import { useCallback, useState } from "react"
import { toast } from "sonner"
import type { useDataTable } from "@/components/data-table"
import type { ApiResponse } from "@/lib/api"
@@ -49,3 +44,24 @@ export function useFetch<TArgs extends unknown[], TResult>(
],
)
}
type Action = <P extends unknown[], R>(...args: P) => Promise<R>
export function useAction(action: Action) {
const [status, setStatus] = useStatus()
const func = useCallback(
async (...args: Parameters<Action>) => {
try {
setStatus("load")
await action(...args)
setStatus("done")
} catch (e) {
setStatus("fail")
throw e
}
},
[action, setStatus],
)
return [func, status]
}

View File

@@ -1,3 +1,10 @@
export const BASE_URL = process.env.API_BASE_URL
export const CLIENT_ID = process.env.CLIENT_ID
export const CLIENT_SECRET = process.env.CLIENT_SECRET
// 产品代码枚举
export enum ProductCode {
All = "all",
Short = "short",
Long = "long",
}

92
src/lib/scopes.ts Normal file
View File

@@ -0,0 +1,92 @@
// 权限
export const ScopePermission = "permission"
export const ScopePermissionRead = "permission:read" // 读取权限列表
export const ScopePermissionWrite = "permission:write" // 写入权限
// 管理员角色
export const ScopeAdminRole = "admin_role"
export const ScopeAdminRoleRead = "admin_role:read" // 读取管理员角色列表
export const ScopeAdminRoleWrite = "admin_role:write" // 写入管理员角色
// 管理员
export const ScopeAdmin = "admin"
export const ScopeAdminRead = "admin:read" // 读取管理员列表
export const ScopeAdminWrite = "admin:write" // 写入管理员
// 产品
export const ScopeProduct = "product"
export const ScopeProductRead = "product:read" // 读取产品列表
export const ScopeProductWrite = "product:write" // 写入产品
// 产品套餐
export const ScopeProductSku = "product_sku"
export const ScopeProductSkuRead = "product_sku:read" // 读取产品套餐列表
export const ScopeProductSkuWrite = "product_sku:write" // 写入产品套餐
export const ScopeProductSkuWriteStatus = "product_sku:write:status" // 更改产品套餐状态
// 折扣
export const ScopeDiscount = "discount"
export const ScopeDiscountRead = "discount:read" // 读取折扣列表
export const ScopeDiscountWrite = "discount:write" // 写入折扣
// 用户套餐
export const ScopeResource = "resource"
export const ScopeResourceRead = "resource:read" // 读取用户套餐列表
export const ScopeResourceWrite = "resource:write" // 写入用户套餐
export const ScopeResourceShort = "resource:short" // 短效动态套餐
export const ScopeResourceShortRead = "resource:short:read" // 读取用户短效动态套餐列表
export const ScopeResourceShortReadOfUser = "resource:short:read:of_user" // 读取指定用户的短效动态套餐列表
export const ScopeResourceLong = "resource:long" // 长效动态套餐
export const ScopeResourceLongRead = "resource:long:read" // 读取用户长效动态套餐列表
export const ScopeResourceLongReadOfUser = "resource:long:read:of_user" // 读取指定用户的长效动态套餐列表
// 用户
export const ScopeUser = "user"
export const ScopeUserRead = "user:read" // 读取用户列表
export const ScopeUserReadOne = "user:read:one" // 读取单个用户
export const ScopeUserReadNotBind = "user:read:not_bind" // 读取未绑定管理员的用户列表
export const ScopeUserWrite = "user:write" // 写入用户
export const ScopeUserWriteBalance = "user:write:balance" // 写入用户余额
export const ScopeUserWriteBalanceInc = "user:write:balance:inc" // 增加用户余额
export const ScopeUserWriteBalanceDec = "user:write:balance:dec" // 减少用户余额
export const ScopeUserWriteBind = "user:write:bind" // 用户认领
// 优惠券
export const ScopeCoupon = "coupon"
export const ScopeCouponRead = "coupon:read" // 读取优惠券列表
export const ScopeCouponWrite = "coupon:write" // 写入优惠券
// 批次
export const ScopeBatch = "batch"
export const ScopeBatchRead = "batch:read" // 读取批次列表
export const ScopeBatchReadOfUser = "batch:read:of_user" // 读取指定用户的批次列表
export const ScopeBatchWrite = "batch:write" // 写入批次
// IP
export const ScopeChannel = "channel"
export const ScopeChannelRead = "channel:read" // 读取 IP 列表
export const ScopeChannelReadOfUser = "channel:read:of_user" // 读取指定用户的 IP 列表
export const ScopeChannelWrite = "channel:write" // 写入 IP
// 交易
export const ScopeTrade = "trade"
export const ScopeTradeRead = "trade:read" // 读取交易列表
export const ScopeTradeReadOfUser = "trade:read:of_user" // 读取指定用户的交易列表
export const ScopeTradeWrite = "trade:write" // 写入交易
// 账单
export const ScopeBill = "bill"
export const ScopeBillRead = "bill:read" // 读取账单列表
export const ScopeBillReadOfUser = "bill:read:of_user" // 读取指定用户的账单列表
export const ScopeBillWrite = "bill:write" // 写入账单
// 余额变动
export const ScopeBalanceActivity = "balance_activity"
export const ScopeBalanceActivityRead = "balance_activity:read" // 读取余额变动列表
export const ScopeBalanceActivityReadOfUser = "balance_activity:read:of_user" // 读取指定用户的余额变动列表
// 代理
export const ScopeProxy = "proxy"
export const ScopeProxyRead = "proxy:read" // 读取代理列表
export const ScopeProxyWrite = "proxy:write" // 写入代理
export const ScopeProxyWriteStatus = "proxy:write:status" // 更改代理状态

5
src/lib/stores/scopes.ts Normal file
View File

@@ -0,0 +1,5 @@
import { atom } from "jotai"
const scopesAtom = atom<string[]>([])
export { scopesAtom }

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