Compare commits
197
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
009dc3cca0 | ||
|
|
573113eb3b | ||
|
|
b548b05874 | ||
|
|
23a85278cb | ||
|
|
96777a948f | ||
|
|
c2b023c9fe | ||
|
|
4c35da9ef6 | ||
|
|
30c43aa8d7 | ||
|
|
a22d3ce0f1 | ||
|
|
359c553452 | ||
|
|
2e61167500 | ||
|
|
54c58551ae | ||
|
|
67391acb16 | ||
|
|
2a395aa126 | ||
|
|
e4fed702c4 | ||
|
|
49aa79f3b9 | ||
|
|
64e20e6aed | ||
|
|
19c0868c5d | ||
|
|
1c6b30fac0 | ||
|
|
6702b8a5b9 | ||
|
|
a35f1d6770 | ||
|
|
6194b664ee | ||
|
|
1caa429cad | ||
|
|
f99fe8d4f7 | ||
|
|
b4a8e0e1f1 | ||
|
|
86c3e79121 | ||
|
|
cabc29c18b | ||
|
|
452cd71035 | ||
|
|
f09a61e5fb | ||
|
|
afc58f7bf4 | ||
|
|
b01ca1fe09 | ||
|
|
689de560bb | ||
|
|
8f7d91310b | ||
|
|
96bd4ad2c8 | ||
|
|
adbd1c6aba | ||
|
|
6ffdbcce84 | ||
|
|
f6f561f2e2 | ||
|
|
ee9cfb0433 | ||
|
|
407ffa17b2 | ||
|
|
ba4ec28763 | ||
|
|
b9b067213f | ||
|
|
52b368068e | ||
|
|
7964d61cab | ||
|
|
4a605f6482 | ||
|
|
d61e6d5ee1 | ||
|
|
7274bd42f5 | ||
|
|
02a5af5e3b | ||
|
|
e06904272a | ||
|
|
d681fd1345 | ||
|
|
bdd78523b5 | ||
|
|
2db49fc955 | ||
|
|
a9fd8e8a47 | ||
|
|
12f5419f21 | ||
|
|
debf662138 | ||
|
|
184f101a86 | ||
|
|
4157d90e9f | ||
|
|
028519a710 | ||
|
|
44b60b5b46 | ||
|
|
ae19e59703 | ||
|
|
2e709aa4ff | ||
|
|
870cb4acec | ||
|
|
9c874734af | ||
|
|
966633d1cc | ||
|
|
dcbebdf01b | ||
|
|
f1c765f8cc | ||
|
|
14fda5395b | ||
|
|
91befd63a7 | ||
|
|
f5a3dd796b | ||
|
|
e60d10b103 | ||
|
|
60036587a6 | ||
|
|
b37c350096 | ||
|
|
a3d1bdfb14 | ||
|
|
266bf236b8 | ||
|
|
e14b65b586 | ||
|
|
e0ab023557 | ||
|
|
dc426774ac | ||
|
|
404e25584e | ||
|
|
1514215729 | ||
|
|
120a9efee4 | ||
|
|
356f891c9e | ||
|
|
0646f5effd | ||
|
|
d264758dee | ||
|
|
83012ad37f | ||
|
|
54f10d894a | ||
|
|
8cdd3f61cb | ||
|
|
46c3232da4 | ||
|
|
a53afb219c | ||
|
|
4adf2d60aa | ||
|
|
adc227f110 | ||
|
|
a8431216e3 | ||
|
|
857ba45541 | ||
|
|
faa96a3bea | ||
|
|
42dc77b1f9 | ||
|
|
4b135b852b | ||
|
|
3c668ccff6 | ||
|
|
34ee5ed619 | ||
|
|
9ff2f6339f | ||
|
|
e652109744 | ||
|
|
4423d528b1 | ||
|
|
d067f0b989 | ||
|
|
08b4b61f90 | ||
|
|
713c9e4e30 | ||
|
|
863b232a73 | ||
|
|
5a67a17e17 | ||
|
|
ce0793505f | ||
|
|
12e1bff8b4 | ||
|
|
15bd000816 | ||
|
|
7f13e595b6 | ||
|
|
098d0fafee | ||
|
|
b66c39724c | ||
|
|
ae0c26434e | ||
|
|
116318df74 | ||
|
|
bdb9a5b474 | ||
|
|
a92e4da043 | ||
|
|
bc1a01848d | ||
|
|
0bbdb27f6d | ||
|
|
2c0e39bae8 | ||
|
|
4ca4abff7b | ||
|
|
d0185caa0e | ||
|
|
6257859b83 | ||
|
|
38549760aa | ||
|
|
6a8c763dec | ||
|
|
c088caf816 | ||
|
|
3dd489066c | ||
|
|
b9824a8312 | ||
|
|
40409707cc | ||
|
|
9472151103 | ||
|
|
e82f15f1fb | ||
|
|
eaa6ae0815 | ||
|
|
3a686a8151 | ||
|
|
3c4578c804 | ||
|
|
fe3badfe3e | ||
|
|
aee5f45d96 | ||
|
|
68b436ac62 | ||
|
|
23bfc04884 | ||
|
|
7112840362 | ||
|
|
06d982d220 | ||
|
|
a865dda1c3 | ||
|
|
2e76aafd0d | ||
|
|
23d3cdbf84 | ||
|
|
e4544a011f | ||
|
|
6b79478414 | ||
|
|
cf50c285f4 | ||
|
|
0bc113af04 | ||
|
|
61b79db9f7 | ||
|
|
55be48069f | ||
|
|
afd4dab567 | ||
|
|
f82dd51d95 | ||
|
|
17bd383229 | ||
|
|
020bf3fe5a | ||
|
|
17c1afd195 | ||
|
|
c83c181a12 | ||
|
|
a279a1ec0d | ||
|
|
c63c623df5 | ||
|
|
b1bdb91fdb | ||
|
|
35b9c7b8a4 | ||
|
|
263a68c98d | ||
|
|
4149cc4426 | ||
|
|
19f9bfa1a0 | ||
|
|
24cf4bbd65 | ||
|
|
ab54235819 | ||
|
|
d74e1aee85 | ||
|
|
26e2e632d5 | ||
|
|
2bb1614a3c | ||
|
|
5856b76de9 | ||
|
|
3e859c3848 | ||
|
|
f7eab5d8fa | ||
|
|
d31c35f098 | ||
|
|
be091f093d | ||
|
|
1ef4a1fe0b | ||
|
|
654c444c18 | ||
|
|
903a423ed5 | ||
|
|
1dd29b68fc | ||
|
|
0411aa37c5 | ||
|
|
c515f00319 | ||
|
|
e1aa418680 | ||
|
|
b5098ac248 | ||
|
|
96740834d6 | ||
|
|
27f180cec0 | ||
|
|
027227d253 | ||
|
|
1d8f775226 | ||
|
|
31209ecb8b | ||
|
|
242efe8ee7 | ||
|
|
61d428a2df | ||
|
|
8997348847 | ||
|
|
6b970ccf19 | ||
|
|
45d316dcbf | ||
|
|
67df831bfe | ||
|
|
34bd2f937b | ||
|
|
0e574fe12c | ||
|
|
1e724e9731 | ||
|
|
0ce30e53a4 | ||
|
|
be2c1e3c81 | ||
|
|
8486d90001 | ||
|
|
2285fb0a6d | ||
|
|
7dac43436a | ||
|
|
6ff12e6a27 |
@@ -0,0 +1,12 @@
|
||||
# 仓库内文本统一以 LF 存储,避免 Windows/WSL 混用产生全量行尾差异。
|
||||
# 行尾差异会淹没真实改动,也会让 gitea.env 之类的配置在 bash 中带上 \r。
|
||||
* text=auto eol=lf
|
||||
|
||||
*.py text eol=lf
|
||||
*.md text eol=lf
|
||||
*.json text eol=lf
|
||||
*.ps1 text eol=crlf
|
||||
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.zip binary
|
||||
@@ -1,9 +1,6 @@
|
||||
## 基本信息
|
||||
|
||||
- 类型:需求 / 缺陷 / 重构
|
||||
- 任务类型:单项目 / 协同
|
||||
- 主项目:Sense / Brain / Bell / contracts / 根级
|
||||
- 主 agent:
|
||||
- 所属 Epic:#
|
||||
- 所属 MVP / 版本:#
|
||||
- 阶段:
|
||||
@@ -21,20 +18,8 @@
|
||||
- 仅影响的子项目 / 交付单元:
|
||||
- 是否跨子项目:是 / 否
|
||||
- 是否修改共享接口或契约:是 / 否;唯一事实来源:
|
||||
- write_paths:
|
||||
- 各子项目需要执行的验证:
|
||||
|
||||
## 协同接口
|
||||
|
||||
<!-- 单项目工单填写“不适用”;协同工单必须完整填写。 -->
|
||||
|
||||
- 生产者:
|
||||
- 消费者:
|
||||
- 契约/共享事实源:
|
||||
- 兼容策略:不适用 / 向后兼容 / 发布新版本
|
||||
- 被阻塞或需要适配的工单:
|
||||
- 集成顺序:
|
||||
|
||||
## 原始需求
|
||||
|
||||
- 来源:用户对话 / Gitea / 其他
|
||||
@@ -68,6 +53,22 @@
|
||||
|---|---|---|---|
|
||||
| | | | 是 / 否 |
|
||||
|
||||
## 设计与原型门禁
|
||||
|
||||
<!-- 先判断是否属于纯显示文案豁免,再选择最低成本、足以确认的设计证据。 -->
|
||||
|
||||
- 修改类型:纯显示文案 / 小范围 UI / 新组件 / 新页面或独立用户功能 / 重大交互或导航 / 非 UI / 恢复既有行为的 Bug
|
||||
- 所需设计证据:无 / 标注截图 / 低保真图 / 已确认原型 / 架构、API、数据、状态或流程设计 / 原设计或复现证据
|
||||
- 可编辑设计源、线上原型链接和访问检查:
|
||||
- 审核版本、revision、复制版本或确认日期及识别方式:
|
||||
- 本地 HTML 导出:未要求 / 用户明确要求 / 项目规则要求
|
||||
- 本地 HTML 路径、版本和资源检查(仅显式导出时填写):
|
||||
- 状态:无 / 草稿 / 已确认 / 已废弃
|
||||
- 确认人、确认时间和覆盖范围:
|
||||
- 无需 UI 原型或无需任何原型的原因:
|
||||
|
||||
<!-- 新页面、独立用户功能、重大交互或导航变化默认通过可访问且版本明确的线上原型审核;只有用户或项目规则明确要求时才导出 prototypes/<工单号>/<版本>/index.html。原型和文字需求未确认前不得编写生产代码。 -->
|
||||
|
||||
## 文档影响
|
||||
|
||||
<!-- 至少选择一项;不影响长期文档时必须写明原因。 -->
|
||||
@@ -88,6 +89,15 @@
|
||||
- [ ] 新增交付文档,受众与页面:
|
||||
- [ ] 需要目标岗位或客户代表验证:是 / 否;验证方式:
|
||||
|
||||
## 任务记录与可选快照
|
||||
|
||||
- 单次任务事实来源:当前 Gitea 工单正文与评论
|
||||
- [ ] 默认不创建任务快照
|
||||
- [ ] 用户明确要求专项快照;用途和范围:
|
||||
- [ ] 项目专用规则要求任务快照;规则入口:
|
||||
|
||||
<!-- 工单正文保存确认基线;重要变化、最终证据和验收结论通过评论追加。只有长期事实变化时才更新 Wiki 和同步镜像。 -->
|
||||
|
||||
## 验收标准
|
||||
|
||||
- [ ] <!-- 填写 -->
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.codex/gitea.env
|
||||
gitea.env
|
||||
.codex/*.log
|
||||
.codex/config.toml
|
||||
__pycache__/
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
# Agent 开发规则
|
||||
|
||||
本仓库采用 DevHarness 工作流:Gitea 工单是任务过程的事实来源,Gitea Wiki 是长期开发文档和任务归档的事实来源,Git 是代码与版本绑定资料的变更记录,`docs/` 只保存 Wiki 的只读镜像。人负责确认方案与验收,Agent 负责检查、实现、测试和留下证据。
|
||||
本仓库采用 DevHarness 工作流:Gitea 工单是单次任务需求、变化、实现、测试、提交和验收的事实来源,Gitea Wiki 是长期开发文档的事实来源,Git 是代码与版本绑定资料的变更记录。`docs/` 默认保存核心 Wiki 的只读镜像,`docs/task/` 只保存人工明确要求的专项或历史兼容快照。人负责确认方案与验收,Agent 负责检查、实现、测试和留下证据。
|
||||
|
||||
开始工作前先阅读 [项目档案](docs/00-project-profile.md) 和任务涉及目录中的 `AGENTS.md`。目录越深的规则越具体,但不得削弱上级安全规则。
|
||||
开始工作前先阅读任务涉及目录中的 `AGENTS.md`。目录越深的规则越具体,但不得削弱上级安全规则。
|
||||
|
||||
[项目档案](docs/00-project-profile.md) 按需阅读,不作为每次任务的固定前置。出现下列情况之一时必须读:需要环境、配置或凭据来源;需要确认目录边界;需要判断子项目与交付单元划分;需要 DevHarness 来源与基线;需要项目专用验收要求。只为查命令不必打开项目档案。
|
||||
|
||||
## 常用命令
|
||||
|
||||
所有命令默认从仓库根目录执行,与项目档案保持一致。
|
||||
|
||||
| 用途 | 命令 |
|
||||
|---|---|
|
||||
| 查看工作区 | `git status --short --branch` |
|
||||
| 检查模板结构 | `python dev_scripts/harness.py check --strict` |
|
||||
| 运行单元测试 | `python -m unittest discover -s tests -v` |
|
||||
| 导出核心 Wiki 镜像 | `python dev_scripts/harness.py sync` |
|
||||
| 检查核心 Wiki 镜像 | `python dev_scripts/harness.py sync --check` |
|
||||
| 创建可选任务快照 | `python dev_scripts/harness.py archive 123 "修复登录超时"` |
|
||||
| 增量导出已有快照 | `python dev_scripts/harness.py export` |
|
||||
| 全量导出已有快照 | `python dev_scripts/harness.py export --all` |
|
||||
|
||||
## 1. 永久规则
|
||||
|
||||
@@ -18,14 +35,15 @@
|
||||
|
||||
新功能、缺陷修复、重构以及任何用户可感知或改变程序行为的修改,必须先建立单元任务工单。
|
||||
|
||||
以下小改动可以直接提交,不要求工单和任务归档:
|
||||
以下小改动可以直接提交,不要求工单:
|
||||
|
||||
- 只改错别字、注释或文档措辞;
|
||||
- 只做格式化、导入排序或不跨文件的内部变量改名;
|
||||
- 补充类型标注或文档字符串且不改变行为;
|
||||
- 删除已经确认无人使用的死代码。
|
||||
- 只修改用户看到的界面显示文案,并且满足本文件“工单与设计证据双门禁”的全部豁免条件。
|
||||
|
||||
只要涉及接口、数据库、状态、权限、安全、并发、用户界面,或者无法确定是否改变行为,就必须建工单。
|
||||
除严格符合界面显示文案豁免的修改外,只要涉及接口、数据库、状态、权限、安全、并发、用户界面,或者无法确定是否改变行为,就必须建工单。代码组件名、类名、变量、国际化键、API 字段和数据库字段不是显示文案,不适用豁免。
|
||||
|
||||
## 3. 需求到实施
|
||||
|
||||
@@ -37,24 +55,61 @@
|
||||
6. 开始实施前检查分支和工作区,明确哪些现有改动不属于本任务。
|
||||
7. 严格按工单范围实现;新发现的问题先记录,不顺手混入当前任务。
|
||||
8. 执行与风险相称的测试,把关键结果和未验证部分更新到工单。实施过程中出现计划外、当前无法解除的问题时才标记“阻塞”。
|
||||
9. 长期文档必须先修改 Wiki、读取确认,再运行 `python dev_scripts/sync_wiki_docs.py` 导出本地镜像;不得直接编辑 `docs/` 后反向覆盖 Wiki。
|
||||
9. 只有长期事实变化时才修改 Wiki、读取确认,再运行 `python dev_scripts/harness.py sync` 导出本地镜像;没有长期文档影响时在工单说明原因并跳过 Wiki 同步。不得直接编辑镜像后反向覆盖 Wiki。
|
||||
|
||||
工单正文保存用户确认的任务基线;根因、范围、方案、风险或阻塞发生重要变化时追加评论。完成实现后用一条评论集中记录最终差异、测试、未验证内容、提交哈希和文档影响;用户验收后再追加验收时间与结论,不重复覆盖或抄写已有证据。
|
||||
|
||||
Gitea 不可用时,输出完整工单草稿并说明阻塞。未经用户明确授权,不得默认绕过建单。
|
||||
|
||||
### Gitea 交互与工单最小读取
|
||||
|
||||
- 所有 Gitea 工单和 Wiki 的查询、创建、更新、评论、状态变更及关闭操作,优先使用项目已配置的 Gitea MCP。
|
||||
- MCP 不可用或不支持所需操作时才回退 Gitea API,并在当前工单记录回退原因;初始化阶段尚无工单时记录到初始化工单草稿,建单后补回。凭据只从环境或 MCP 安全配置读取。
|
||||
- 首次接手任务时读取工单确认基线和完成当前判断所需的评论,不因节省 Token 跳过范围、依赖、安全、验收或重要变更。
|
||||
- 同一任务、同一会话且关键前提未变化时,复用仍有效的工单事实,优先关注当前状态、最新评论和首个未完成步骤,不重复分析已经确认且仍有效的内容。
|
||||
- 会话、代码、配置、依赖、凭据、远端状态或关键前提变化,任务基线不清楚,或最新评论声明历史需求、方案、范围、风险或验收发生变化时,重新读取必要历史;无法判断影响范围时读取完整工单。
|
||||
- 连接器不支持评论分页或增量读取时允许读取完整工单,但不得把“已读取全文”误当成需要重新分析全部历史,也不得为规避完整读取而新增本地工单、缓存或第二事实来源。
|
||||
- 正确性、安全规则和已确认范围优先于 Token 优化;读取边界存在不确定时补读必要证据。
|
||||
|
||||
### 新项目 Wiki 初始化门禁
|
||||
|
||||
- 从本模板创建新项目时,先创建 Gitea 远端仓库并启用工单和 Wiki,再配置 `wiki-docs.json`;不得把模板自带的本地 `docs/` 当作新项目 Wiki 已初始化的证据。
|
||||
- 优先使用项目已配置的 Gitea MCP 查询和写入 Wiki;MCP 不可用或不支持所需写操作时,才使用 Gitea API,并在初始化工单记录回退原因。凭据只从环境或 MCP 安全配置读取。
|
||||
- 先查询线上页面列表;`Home` 不存在时必须先创建 `Home`,在线回读正文并记录 revision,然后再逐页创建或更新其他核心映射页面。
|
||||
- 每个核心页面写入后必须在线回读并取得 revision。页面缺失、回读失败或没有 revision 时停止初始化,不得开始产品代码。
|
||||
- 产品编码前必须运行 `python dev_scripts/harness.py sync --verify`;全部成功才表示线上 Wiki 和核心镜像初始化完成。
|
||||
|
||||
### 工单与设计证据双门禁
|
||||
|
||||
- 纯界面显示文案只有在不改变业务含义、流程、权限、状态、接口、数据、法律/安全/支付/单位等高风险含义、国际化键、程序标识符、布局和可访问性,且没有任何不确定时,才免工单和原型;修改后执行最小界面检查。
|
||||
- 新页面、独立用户功能、重大交互或导航变化,必须先用 Quant-UX 或其他合适工具制作可审阅原型;用户确认原型、文字需求和覆盖范围后,才能建立或放行实现工单并编写生产代码。
|
||||
- 上述完整原型形成待审核版本后,默认直接通过 Quant-UX 或其他设计工具的线上链接审核,不要求每次导出本地 HTML。工单必须记录可访问链接、版本/revision 或确认日期、审核版本识别方式、确认人、确认时间和覆盖范围;线上链接无法访问或无法区分版本时停止审核,等待用户确认等效方案。
|
||||
- 只有用户明确要求 `导出原型 #N`、`导出全部原型`,或项目专用规则明确要求离线交付时,才导出到 `prototypes/<工单号>/<版本>/index.html`。已确认的本地快照不得原位覆盖;版本目录内资源使用相对路径,导出后检查入口、主要交互和资源完整性,但不自动提交。
|
||||
- 现有界面的小范围样式或布局调整使用标注截图、低保真图或明确复用的现有规范;新组件记录状态、错误和边界。两者只要不符合纯文案豁免就必须建单。
|
||||
- 后端、接口、数据处理和定时任务不强制 UI 原型,但必须先确认架构、API、数据、状态或流程设计;恢复既有确认行为的 Bug 可以复用原设计、截图、复现步骤或已有验收证据。
|
||||
- 需要设计证据的工单记录链接或路径、版本/revision 或日期、状态、确认人、确认时间和覆盖范围;没有 UI 原型时记录替代技术设计或原因。
|
||||
- 页面结构、主要流程、状态、权限、异常处理或验收结果变化时,必须更新原型或文字需求并重新确认后再继续正式编码。
|
||||
- 草稿原型可以用于讨论;写入 Git/Wiki、多人协作或单独实施时建立设计任务。草稿和经明确授权的隔离技术验证都不得直接作为生产实现。
|
||||
- 设计工具无法生成用户明确要求的可用 HTML 时,在工单记录限制并停止该导出或离线交付,等待用户确认等效方案;线上原型可访问且版本明确时不因此阻塞线上审核。纯显示文案、小范围 UI、非 UI 需求和恢复既有行为的 Bug 不强制建立完整线上原型或导出 HTML。
|
||||
|
||||
### 自然语言快捷指令
|
||||
|
||||
快捷指令只是本工作流的自然语言别名,不得绕过方案确认、前置依赖、安全规则、工单范围、Wiki 主源、必要验证或人工验收:
|
||||
|
||||
- `只分析`:只读检查并给出方案;不建单、不修改,停在等待确认。
|
||||
- `建工单`:根据已确认方案创建单元任务工单;建单后停止,不修改代码。
|
||||
- `执行工单 #N`:检查工单和依赖,实施、测试、提交、归档、推送并回写证据;停在“待验收”。
|
||||
- `执行工单 #N`:检查工单和依赖,实施、测试、提交、推送并回写证据;仅在明确要求时创建任务快照;停在“待验收”。
|
||||
- `建工单并做`:依次建单和执行,`建工单,做`、`建工单,做` 含义相同;停在“待验收”。
|
||||
- `继续工单 #N`:核对工单、Git 和 Wiki 证据,从首个未完成步骤继续,不重复仍然有效的检查。
|
||||
- `继续工单 #N`:优先核对当前状态、最新评论、Git 和必要 Wiki 证据,从首个未完成步骤继续;关键前提未变化时不重复读取和分析仍有效的内容。
|
||||
- `检查工单 #N`:只读核对范围、验收、测试和证据并输出报告;不自动修复。
|
||||
- `同步文档`:读取 Wiki、导出 `docs/` 并检查一致性;不修改 Wiki、不自动提交。
|
||||
- `#N 验收通过`:仅在用户明确验收后,更新归档、同步并提交镜像、推送、同步父工单并关闭任务。
|
||||
- `同步文档`:读取 Wiki、导出核心 `docs/` 并检查一致性,不处理任务归档;不修改 Wiki、不自动提交。
|
||||
- `导出原型 #N`:人工触发导出指定工单已确认的原型版本,按工单和版本写入 `prototypes/`;不扩展范围、不自动提交。
|
||||
- `导出全部原型`:人工触发导出当前项目已明确范围内的全部已确认原型;不自动提交。
|
||||
- `导出任务归档`:人工触发 `python dev_scripts/harness.py export`,只导出新增或 revision 已变化的任务归档;不删除本地文件、不自动提交。
|
||||
- `导出全部任务归档`:人工触发 `python dev_scripts/harness.py export --all`,读取并导出全部线上任务归档;不删除本地文件、不自动提交。
|
||||
- `#N 验收通过`:仅在用户明确验收后,在工单追加验收结论;按需更新真实变化的长期 Wiki,推送、同步父工单并关闭任务;不创建或导出任务归档。
|
||||
|
||||
方案未确认或前置依赖未满足时,实施类指令必须停在对应门禁;除 `#N 验收通过` 外,快捷指令不得关闭待验收工单。Gitea 工单不导出全文,本地只保存 Wiki 任务归档镜像。详细语义见 [开发工作流](docs/01-workflow.md)。
|
||||
方案未确认或前置依赖未满足时,实施类指令必须停在对应门禁;除 `#N 验收通过` 外,快捷指令不得关闭待验收工单。原型和任务快照的导出必须由用户明确提出或项目专用规则明确要求,其他指令不得隐式执行。Gitea 工单不导出全文,`docs/task/` 只是可能不完整的专项或历史兼容快照。详细语义见 [开发工作流](docs/01-workflow.md)。
|
||||
|
||||
### 需求记录与流转
|
||||
|
||||
@@ -62,13 +117,13 @@ Gitea 不可用时,输出完整工单草稿并说明阻塞。未经用户明
|
||||
- 工单中的目标、非目标、已确认方案、验收标准和文档影响构成确认后的正式任务需求。
|
||||
- 影响范围、接口、数据、风险或验收的需求变化必须记录日期、内容、原因和用户确认;会改变已确认结果时先更新工单并等待再次确认。
|
||||
- 不复制完整聊天,不保存 Agent 内部推理,不写入密码、令牌、个人数据或生产数据;包含敏感信息的原话必须删除敏感部分或改写为脱敏摘要。
|
||||
- 长期有效的产品需求、业务规则和系统边界进入对应 Wiki 主题页并导出 `docs/`;完成结果进入 Wiki 任务归档并导出 `docs/task/`。Gitea 工单全文不导出到仓库。
|
||||
- 长期有效的产品需求、业务规则和系统边界进入对应 Wiki 主题页并导出核心 `docs/`;单次任务的完成结果和验收保留在工单正文与评论。只有用户明确要求专项快照或项目专用规则要求时才创建 Wiki 任务快照并按需导出 `docs/task/`。Gitea 工单全文不导出到仓库。
|
||||
|
||||
详细记录边界见 [开发工作流](docs/01-workflow.md) 与 [业务规则和术语](docs/03-business-rules-and-glossary.md)。
|
||||
|
||||
### 效率与范围控制
|
||||
|
||||
本节只用于减少无关工作和重复检查,不得削弱安全规则、已确认方案、工单范围、必要测试、Wiki 同步、Git 提交和验收归档要求。
|
||||
本节只用于减少无关工作和重复检查,不得削弱安全规则、已确认方案、工单范围、必要测试、必要的长期文档同步、Git 提交和人工验收要求。
|
||||
|
||||
#### 严格控制范围
|
||||
|
||||
@@ -120,19 +175,22 @@ Gitea 不可用时,输出完整工单草稿并说明阻塞。未经用户明
|
||||
- 实现提交信息引用工单号,例如:`fix: 修复登录超时 (#123)`。
|
||||
- 不为流程制造空提交。
|
||||
- 优先运行项目档案中记录的格式检查、静态检查、单元测试和必要的集成测试。
|
||||
- 不能验证的真机、生产、迁移或并发行为必须写入工单和归档。
|
||||
- 不能验证的真机、生产、迁移或并发行为必须写入工单;存在明确要求的任务快照时再同步记录。
|
||||
- Windows 环境优先使用当前已配置的 PowerShell;可选择时优先 PowerShell 7 `pwsh.exe`,不得仅为设置编码重复启动一层 PowerShell。
|
||||
- 文本文件读写在命令支持时显式指定 UTF-8;文件解码和控制台输出分别处理,只有出现真实乱码或已知宿主非 UTF-8 时才设置当前进程的输出编码或 Python UTF-8 环境变量。
|
||||
- 不得默认使用 `-ExecutionPolicy Bypass`;只有可信 `.ps1`确实被执行策略阻止且没有更小替代方案时,才对该次进程使用并在工单记录原因。
|
||||
|
||||
## 7. 完成、验收和归档
|
||||
## 7. 完成和验收
|
||||
|
||||
1. 逐项完成验收、测试和实现提交,并把最终方案、差异、结果、提交及遗留问题写回工单。
|
||||
1. 逐项完成验收、测试和实现提交,在工单追加最终证据评论,记录最终方案、差异、结果、提交、遗留问题和文档影响。
|
||||
2. 工单保持“待验收”,用户没有明确验收通过前不得关闭。
|
||||
3. 运行 `python dev_scripts/new_task_archive.py <编号> "<短标题>"`,先创建 Wiki 归档,再登记并导出本地镜像。
|
||||
4. 读取确认 Wiki,运行 `python dev_scripts/sync_wiki_docs.py --check`;归档镜像单独提交,并把页面、revision、路径和提交哈希写回工单。
|
||||
5. 用户验收通过后关闭单元工单,并同步更新 MVP 和 Epic。
|
||||
3. 有长期文档影响时,读取确认 Wiki,运行 `python dev_scripts/harness.py sync --check` 检查核心镜像,并把页面 revision 和镜像提交哈希写回工单;没有长期文档影响时不运行 Wiki 同步。
|
||||
4. 用户验收通过后,在工单追加验收时间和结论,关闭单元工单,并同步更新 MVP 和 Epic;没有真实变化的 Wiki 不重复更新或检查。
|
||||
5. 默认不创建任务归档。只有用户明确要求专项快照或项目专用规则明确要求时,才运行 `python dev_scripts/harness.py archive <编号> "<短标题>"`;`export` 和 `export --all` 同样必须显式触发。
|
||||
|
||||
MVP 内所有单元任务通过后才能做 MVP 集成验收;MVP 通过后才能关闭 MVP。Epic 的全部范围完成后才能关闭 Epic。
|
||||
|
||||
详细归档顺序和字段见 [开发工作流](docs/01-workflow.md)。
|
||||
详细证据回写、可选快照和文档同步边界见 [开发工作流](docs/01-workflow.md)。
|
||||
|
||||
## 8. 可维护性
|
||||
|
||||
@@ -153,8 +211,9 @@ MVP 内所有单元任务通过后才能做 MVP 集成验收;MVP 通过后才
|
||||
|
||||
- 每个单元任务必须在工单中选择“无长期文档影响并说明原因”或列出需要更新的 Wiki 页面。
|
||||
- 启动、测试、部署、排错命令,模块入口、目录职责、主要调用路径,配置、API、数据结构、状态、业务规则、安全边界、日志位置发生变化时,必须更新对应 Wiki。
|
||||
- 部署命令变化时,有常驻服务的项目更新自己的 `Deployment-and-Operations` 页面(由 [部署文档模板](docs/templates/deployment.md) 复制建立);没有常驻服务的项目记录为无部署文档影响,不创建空的部署页。
|
||||
- 普通内部重构只有在入口、行为、配置和验证方式均未改变时,才可以记录为不影响长期文档。
|
||||
- 必需核心页面及结构以 `python dev_scripts/check_harness.py --strict` 和 [新项目文档初始化](docs/07-new-project-documentation-setup.md) 为准;稳定文档与任务归档的分工见 [开发工作流](docs/01-workflow.md)。
|
||||
- 必需核心页面及结构以 `python dev_scripts/harness.py check --strict` 和 [新项目文档初始化](docs/07-new-project-documentation-setup.md) 为准;稳定文档与可选历史快照的分工见 [开发工作流](docs/01-workflow.md)。
|
||||
|
||||
## 9. 引导提交例外
|
||||
|
||||
@@ -164,11 +223,20 @@ MVP 内所有单元任务通过后才能做 MVP 集成验收;MVP 通过后才
|
||||
|
||||
## 10. 项目专用规则
|
||||
|
||||
### YoVision 分支治理
|
||||
|
||||
- `explore` 是旧实现的只读聚合快照,不接受新功能、修复或文档演进;需要恢复旧行为时从其来源提交读取证据,不在该分支续写产品。
|
||||
- `main` 是用户审核基线,禁止直接开发、直接提交或未经用户明确审核的合并。
|
||||
- 新任务分支必须从当前 `dev` 创建,完成后通过 PR 合回 `dev`;不得把功能分支直接合入 `main`。
|
||||
- `dev` 完成集成测试后仍不能自动进入 `main`;只有用户明确表示审核/验收通过,Agent 才能执行 `dev → main`。
|
||||
- 紧急修复也必须建单并取得用户对分支与合并路径的明确授权,不默认绕过 `dev`。
|
||||
|
||||
<!-- 在项目初始化时填写不可违反的技术、安全和业务约束。复杂子项目请在其目录中增加 AGENTS.md。 -->
|
||||
|
||||
- 长期开发文档以 Gitea Wiki 为事实来源,`docs/` 是显式映射生成的只读镜像。
|
||||
- Wiki 与镜像的固定顺序是:修改 Wiki → 读取确认 → 导出 `docs` → 校验差异 → 提交镜像。
|
||||
- 同步配置只允许写入 `docs/` 下的 Markdown;发现镜像有未提交修改时必须停止。
|
||||
- 长期开发文档以 Gitea Wiki 为事实来源,单次任务证据以 Gitea 工单为事实来源;`docs/` 默认保存显式映射生成的核心只读镜像,`docs/task/` 是人工明确要求的专项或历史兼容快照,可能不完整或不是最新状态。
|
||||
- 核心 Wiki 与镜像的固定顺序是:修改 Wiki → 读取确认 → 导出核心 `docs` → 校验差异 → 提交镜像。
|
||||
- 默认不创建任务归档;`archive`、`导出任务归档` 或 `导出全部任务归档` 必须由用户明确提出或项目专用规则明确要求,且不得自动传播删除或重命名。
|
||||
- 同步配置只允许写入 `docs/` 下的 Markdown;发现核心镜像有未提交修改时必须停止。
|
||||
- Gitea 凭据只通过进程环境或 MCP 安全配置提供,不得写入仓库。
|
||||
- `dev_scripts/` 只存放 DevHarness 自身工具;业务项目的通用脚本必须使用独立目录,不得混放。
|
||||
- 本仓库包含 `Sense/`、`Brain/`、`Bell/` 三个独立开发与交付单元;Sense 与 Bell 是认证、数据、部署和发布完全独立的销售产品,Brain 是无界面推理交付单元。
|
||||
@@ -180,6 +248,30 @@ MVP 内所有单元任务通过后才能做 MVP 集成验收;MVP 通过后才
|
||||
- 16 路是默认交付配额,不得成为数据库、数组、循环、分页、批处理或单机容量的硬上限。
|
||||
- 开始子项目工作前还必须读取对应目录的 `AGENTS.md`;共享契约工作读取 `contracts/AGENTS.md`。
|
||||
|
||||
### go-admin / go-admin-ui 精简与复用
|
||||
|
||||
- Sense、Bell 使用 go-admin 和 go-admin-ui 时遵循“最小可见、最小启用”:只呈现当前产品需要的菜单、路由、权限和接口,不把框架演示或无关管理能力暴露给用户。
|
||||
- 快速交付阶段优先使用配置、菜单权限或路由开关隐藏不用模块。隐藏只移除用户入口,不等于禁用;权限或安全相关能力必须同时关闭前端入口与后端访问能力。
|
||||
- 永久删除默认模块必须单独建立清理工单,先核对代码依赖、数据库对象、权限记录、构建影响、框架升级影响和回退方式,不在业务页面工单中顺手删除。
|
||||
- 新页面优先复用现有布局、表格、表单、弹窗、上传、权限控制和请求封装;现有组件无法满足明确需求时才新增组件,并在工单中说明复用缺口。
|
||||
- 新组件必须沿用项目现有的颜色、字号、间距、状态反馈、交互方式、命名和目录结构;不得引入与整体风格冲突的独立视觉体系。
|
||||
- 不为单个页面直接改变底层公共组件的全局行为。确需全局修改或同时影响 Sense、Bell 时,必须单独建单并明确受影响页面、兼容方式和回归验证;跨产品影响按协同工单处理。
|
||||
- UI 验收至少检查:没有多余入口、没有可见但不可用的失效入口、没有重复实现已有组件,并且视觉与交互保持一致。
|
||||
|
||||
### Sense/Bell GoAdmin 技术基线
|
||||
|
||||
- `goadmin-baseline.json` 是 Sense、Bell 共用的 GoAdmin 上游与工具链版本事实来源;上游 URL 加完整 commit 是可复现标识,tag、`package.json` version、本机目录内容或本机已安装版本都不能替代 commit。
|
||||
- `D:\github\goadmin\go-admin`、`go-admin-ui`、`go-admin-doc` 是当前机器的只读参考副本。Agent 可以读取和验证,不得在这些目录开发、修改或提交 yovision 产品代码。
|
||||
- “基于 go-admin / go-admin-ui 二次开发”必须表现为从 `goadmin-baseline.json` 指定的两个完整上游 commit 导入或派生产品源码,并保留可核对的目录结构、框架启动链、通用认证/RBAC、菜单路由、请求封装及许可证来源;仅采用 Go、Vue、Element Plus、相似目录、页面外观或交互不算满足基线。
|
||||
- 禁止用自建 `net/http`、自建认证/RBAC/会话框架或自制管理端外壳替代 go-admin/go-admin-ui 后仍声称是 GoAdmin 二次开发。确有上游能力无法满足时,必须在独立工单中说明缺口、保留上游扩展边界并等待用户确认。
|
||||
- 每个 Sense/Bell 骨架、基础能力或框架相关工单开始实施前,必须读取任务相关的冻结 `go-admin-doc` 内容,并在工单中记录参考的文档主题或文件、继承的上游路径以及计划隐藏/禁用的默认模块。
|
||||
- 初始化验收必须包含来源证据:上游 URL/commit、实际导入路径、保留的 MIT 文件、相对上游的裁剪/修改清单和构建测试;缺少任一项不得标记为 GoAdmin 骨架完成。
|
||||
- Sense、Bell 必须从同一冻结基线分别初始化,保留独立代码、配置、构建、测试、版本和发布;不得通过共同修改参考仓库形成隐藏的共享实现。
|
||||
- 复制或派生上游代码时必须保留对应 MIT 许可证和版权声明,并记录实际复制来源的 commit。
|
||||
- `go-admin-doc` 只用于理解上游框架用法;yovision 的 Gitea Wiki、`AGENTS.md` 和 `goadmin-baseline.json` 仍是本项目事实来源。
|
||||
- 变更任一上游 commit、Go、Node 或 pnpm 版本必须建立 Sense/Bell 协同升级工单,验证两个产品后再更新基线;不得在单端业务工单中静默升级。
|
||||
- 当前冻结后端要求 Go 1.26.5;本机 Go 1.23.0 不满足要求,安装隔离的正确工具链并完成构建验证前,不得声称后端基线可构建。
|
||||
|
||||
### 三项目并行建单顺序
|
||||
|
||||
客户交付需要 Sense、Brain、Bell 并行推进时,固定使用以下顺序:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Bell 独立纵切验收
|
||||
|
||||
本验收只使用 Bell 自身、临时 PostgreSQL 和项目内合成事件,不启动或调用 Sense、Brain,不连接默认 5432、生产数据库或客户数据。
|
||||
|
||||
## 固定工具链
|
||||
|
||||
```powershell
|
||||
$env:GOTOOLCHAIN='go1.26.5'
|
||||
go version
|
||||
node --version
|
||||
corepack pnpm@9.15.1 --version
|
||||
```
|
||||
|
||||
预期分别为 Go 1.26.5、Node 22.22.1、pnpm 9.15.1。
|
||||
|
||||
## 源码验证
|
||||
|
||||
```powershell
|
||||
Set-Location Bell\server
|
||||
$env:GOTOOLCHAIN='go1.26.5'
|
||||
go test ./... -count=1
|
||||
go vet ./...
|
||||
go build ./...
|
||||
|
||||
Set-Location ..\ui
|
||||
corepack pnpm@9.15.1 install --frozen-lockfile
|
||||
corepack pnpm@9.15.1 lint
|
||||
corepack pnpm@9.15.1 test:unit --runInBand
|
||||
corepack pnpm@9.15.1 build:prod
|
||||
```
|
||||
|
||||
## Windows 包和隔离 E2E
|
||||
|
||||
```powershell
|
||||
Set-Location <仓库根目录>
|
||||
Bell\scripts\build\build-windows.bat
|
||||
pwsh -NoProfile -File Bell\scripts\build\test-package.ps1 -PackageRoot Bell\dist\bell-windows-amd64
|
||||
pwsh -NoProfile -File Bell\scripts\test-independent-e2e.ps1 -PreparedPackageRoot Bell\dist\bell-windows-amd64
|
||||
```
|
||||
|
||||
E2E 自动完成并清理:临时 PostgreSQL、随机数据库/HTTP 端口、随机管理员/处置员凭据、迁移、健康检查、登录/RBAC、最小 Bell 菜单、规则、合成 Event/Receipt 幂等、Alert、20 路并发 ack、越权/缺参拒绝、close 重放幂等、两条生命周期时间线、冷重启、Windows stop 和日志泄密检查。原始包保持生产配置并先通过审计;业务自动化只把临时包副本切换为 `dev` 测试模式。生产验证码的获取、正确登录、错误及重放拒绝由 #138 的 `Bell/server/tests/bell_production_login/run-postgres.ps1` 覆盖,不暴露或识别验证码答案。
|
||||
|
||||
浏览器验收打开脚本输出的临时 `base_url`,检查:
|
||||
|
||||
- 匿名访问跳转登录页,并显示验证码输入;测试模式可填写任意非空验证码,生产验证码行为由 #138 回归覆盖;
|
||||
- 登录后保留 GoAdmin 侧栏、顶部导航和标签页;
|
||||
- 管理员显示 Bell 必要业务菜单,包括预警管理、事件查询、规则配置;处置员仅显示预警处理所需入口;
|
||||
- 预警详情可显示关联事件、处理人、现场结果和两条处理时间线;
|
||||
- 不显示开发工具、定时任务、系统监控等无关入口。
|
||||
|
||||
## 仓库闭环
|
||||
|
||||
```powershell
|
||||
python dev_scripts/harness.py check --strict
|
||||
git diff --check
|
||||
git status --short --branch
|
||||
```
|
||||
|
||||
浏览器人工/工具检查、真实生产数据库、客户网络和长期负载不由 API 单测替代;未执行的项目必须在工单证据中明确说明。
|
||||
@@ -14,3 +14,21 @@
|
||||
- 每个工单必须写明任务类型、主项目 `Bell`、主 agent、精确 `write_paths`、独立运行方式、测试命令和在 Sense/Brain 未启动时使用合成或第三方事件的验收标准。
|
||||
- 首轮并行建单只创建 Bell 独立工单;发现需要外部事件/证据契约、producer identity、Sense connector、根级部署或端到端测试时,停止扩写本工单,向主 agent 提交协同需求摘要。
|
||||
- 协同需求摘要至少包含生产者、消费者、接口目的、候选事实源、阻塞的 Bell 工单和建议验证;Bell agent 不直接创建契约实现或取得 `contracts/`、`Sense/`、`Brain/` 的写入权。
|
||||
|
||||
## go-admin / go-admin-ui 约束
|
||||
|
||||
- Bell 管理面只启用事件预警、告警处置和通知运维所需的默认能力;框架演示页和无关管理模块优先通过配置、菜单权限或路由开关隐藏。
|
||||
- 涉及权限或安全的不用模块不能只隐藏菜单,必须同时验证前端入口和后端接口均不可访问;永久删除默认模块必须单独建立清理工单。
|
||||
- 新页面优先复用 Bell/go-admin-ui 已有的布局、表格、表单、弹窗、上传、权限控制和请求封装;新增组件前在工单中说明现有组件为何不能满足需求。
|
||||
- 新增组件沿用 Bell 现有颜色、字号、间距、状态反馈、交互方式、命名和目录结构,并验证没有多余入口、失效入口或重复组件。
|
||||
- 修改底层公共组件的全局行为时,必须单独建单并列出所有受影响页面;同时影响 Sense 或共享基线时升级为协同工单。
|
||||
|
||||
## GoAdmin 技术基线
|
||||
|
||||
- 初始化或升级 Bell 前必须读取根 `goadmin-baseline.json`,按其中的 go-admin、go-admin-ui commit 和 Go/Node/pnpm 精确版本实施。
|
||||
- Bell 必须由冻结 go-admin 后端与 go-admin-ui 前端源码直接派生;旧 `explore` 实现只能用于业务语义对照,禁止把其中自研认证、RBAC、会话、HTTP 平台或前端外壳复制为新基础。
|
||||
- 开始每个骨架、认证权限、菜单路由、代码生成、ORM 或通用 UI 工单前,必须读取任务相关的冻结 go-admin-doc,并把参考主题/文件及采用方式写回工单。
|
||||
- 骨架验收必须证明上游来源、继承路径、许可证、裁剪清单和相对上游差异;只有相似技术栈或视觉不能通过验收。
|
||||
- `D:\github\goadmin` 下的仓库仅可只读参考;Bell 产品代码只能写入 `Bell/` 或工单授权路径,不得在参考仓库原地开发。
|
||||
- 派生上游代码必须保留 MIT 许可证和版权声明;上游 `go-admin-doc` 只作框架用法参考,不覆盖 yovision Wiki 和本目录规则。
|
||||
- 变更冻结基线必须升级为 Sense/Bell 协同工单;Bell 可以独立发布,但不得单独漂移上游或工具链版本。
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Bell GoAdmin 来源清单
|
||||
|
||||
Bell 的后端与管理端是从冻结 GoAdmin 完整应用源码派生的独立产品副本,不在本机参考仓库中开发。
|
||||
|
||||
| 组件 | 上游 | 冻结 commit | Bell 导入路径 | 许可证 |
|
||||
|---|---|---|---|---|
|
||||
| go-admin | https://github.com/go-admin-team/go-admin.git | `f06540883b41d03782bb6b2c4150f298f328c6b6` | `Bell/server/` | MIT,见 `go-admin-LICENSE.md` 及 `Bell/server/LICENSE.md` |
|
||||
| go-admin-ui | https://github.com/go-admin-team/go-admin-ui.git | `67d393d713877572fab0b897296a4c1d525fc81d` | `Bell/ui/` | MIT,见 `go-admin-ui-LICENSE` 及 `Bell/ui/LICENSE` |
|
||||
| go-admin-doc | https://github.com/go-admin-team/go-admin-doc.git | `424855aacf6905f3fde860c3331385cb25529a0d` | 只读参考,不导入产品源码 | MIT |
|
||||
|
||||
## 导入排除项
|
||||
|
||||
- 三个上游仓库的 `.git/`:避免嵌套仓库;来源由上表完整 commit 固定。
|
||||
- `go-admin/go-admin-db.db`:上游跟踪的本地演示 SQLite 数据库,不属于产品源码,且 Bell 正式数据库为 PostgreSQL。
|
||||
- `go-admin/static/uploadfile/`:上游跟踪的运行期演示上传图片与日志,不属于产品源码,也不得作为 Bell 运行数据导入。
|
||||
- `go-admin-ui/node_modules/`:本机生成依赖目录,不属于上游跟踪源码;依赖由 `pnpm-lock.yaml` 重建。
|
||||
- 日志、构建产物和本机未跟踪文件未导入。
|
||||
|
||||
除上述排除项外,冻结提交中的应用源码、Cobra 命令、Gin/GORM/Casbin/JWT 链、迁移、Router、Store、Axios、Layout、Element Plus 组件及测试均保留。默认模块源码也保留,Bell 只通过菜单可见性和路由注册进行收敛。
|
||||
|
||||
## Bell 相对上游的首轮差异
|
||||
|
||||
- 对冻结源码导入后由完整基线差异检查报告的尾随空白、文件末尾多余空行做机械规范化;该项仅改变空白,不改变程序逻辑、配置语义或许可证内容。
|
||||
- 生产配置固定使用 Bell 独立 PostgreSQL、端口和命名空间;数据库 URL 与 JWT secret 必须从 `BELL_*` 进程环境提供。
|
||||
- 初始管理员必须在迁移时显式提供,仓库不保存默认账号、密码或可用 secret;登录页不预填凭据。
|
||||
- JWT realm 与前端 token key 使用 Bell 独立名称,只接受 Authorization header,不复用 Sense Cookie/token。
|
||||
- 保留用户、角色、菜单、认证和审计基础能力;隐藏部门、岗位、字典、参数、日志、代码生成、任务及监控等骨架阶段无关菜单。
|
||||
- 保留 jobs/other 源码作为扩展边界,但不注册其后端路由,因此隐藏入口不能通过直接访问绕过。
|
||||
- PostgreSQL 迁移继续使用上游 Cobra/GORM migration 链,并由环境输入创建一次性初始管理员。
|
||||
|
||||
## 已阅读的冻结 go-admin-doc
|
||||
|
||||
- `docs/guide/index.md`:确认 Gin、GORM、Casbin、JWT 与内置模块边界。
|
||||
- `docs/intro/cmd/server.md`、`docs/intro/cmd/migrate.md`:保留 Cobra `server` / `migrate` 启动链和显式配置文件入口。
|
||||
- `docs/intro/advanced/config.md`、`router.md`、`api.md`:沿用配置加载、Router 注册、中间件和 API 分层方式。
|
||||
- `docs/intro/advanced/models.md`、`dto.md`、`service.md`、`db.md`:保留 Model/DTO/Service/GORM 结构,并采用文档列出的 PostgreSQL 驱动。
|
||||
- 冻结 go-admin-ui 的 `README.md`、`src/router/**`、`src/store/**`、`src/api/**`、`src/layout/**`:保留 Router/Store/请求封装/Layout/动态菜单与按钮权限链。
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 go-admin-team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 wenjianzhang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Bell Windows 运行说明
|
||||
|
||||
Bell Windows 包包含独立后端、GoAdmin 管理端静态资源和启动、停止、检查脚本。正式运行需要独立 PostgreSQL;包内不提供默认账号、密码、JWT secret 或数据库。
|
||||
|
||||
## 配置
|
||||
|
||||
编辑 `config\bell.env`:
|
||||
|
||||
```text
|
||||
BELL_HOST=127.0.0.1
|
||||
BELL_PORT=18090
|
||||
BELL_WEB_HOST=127.0.0.1
|
||||
BELL_WEB_PORT=18091
|
||||
BELL_DATABASE_URL=host=127.0.0.1 port=5432 user=bell dbname=bell sslmode=disable
|
||||
BELL_JWT_SECRET=<至少 32 字符的独立随机值>
|
||||
BELL_BOOTSTRAP_USERNAME=<仅首次迁移使用>
|
||||
BELL_BOOTSTRAP_PASSWORD=<仅首次迁移使用,至少 8 字符>
|
||||
BELL_AUTO_MIGRATE=true
|
||||
BELL_SYNTHETIC_EVENTS_ENABLED=false
|
||||
```
|
||||
|
||||
不要把真实配置提交到 Git。首次迁移成功后,建议从进程环境中移除 `BELL_BOOTSTRAP_PASSWORD`;它不会写入明文数据库。
|
||||
|
||||
## 启动、检查和停止
|
||||
|
||||
```bat
|
||||
check-bell.bat
|
||||
start-bell.bat
|
||||
check-bell.bat -Running
|
||||
stop-bell.bat
|
||||
```
|
||||
|
||||
浏览器访问 `http://127.0.0.1:18091/`。`BELL_PORT` 是仅供本机 Web 网关访问的后端端口;`BELL_WEB_PORT` 是用户访问入口。启动脚本默认先执行幂等数据库迁移,再启动后端和 Web 网关;任一步失败都会返回非零退出码。
|
||||
|
||||
`stop-bell.bat` 只按包内 PID 文件和启动命令行核对后停止本包进程树,不按端口终止未知进程。运行日志位于 `runtime\logs`,不得包含密码、JWT 或登录 token。
|
||||
|
||||
## 构建和包审计
|
||||
|
||||
从仓库根目录运行:
|
||||
|
||||
```powershell
|
||||
Bell\scripts\build\build-windows.bat
|
||||
pwsh -NoProfile -File Bell\scripts\build\test-package.ps1 -PackageRoot Bell\dist\bell-windows-amd64
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
- `Bell\dist\bell-windows-amd64\`
|
||||
- `Bell\dist\bell-windows-amd64.zip`
|
||||
|
||||
包内 `VERSION.txt`、`MANIFEST.sha256` 和 `LICENSES\` 分别记录源码提交、工具链、文件摘要、GoAdmin 来源及 MIT 许可证。
|
||||
|
||||
## 常见错误
|
||||
|
||||
- `BELL_DATABASE_URL is required`:设置独立 PostgreSQL 连接串。
|
||||
- `PostgreSQL is unreachable`:启动 PostgreSQL,并检查地址和端口。
|
||||
- `BELL_JWT_SECRET must contain...`:生成至少 32 字符、只供 Bell 使用的随机值。
|
||||
- `port ... is already in use`:停止已有 Bell,或修改后端/Web 端口。
|
||||
- `Bell database migration failed`:检查数据库是否存在、用户权限及迁移日志;不要删除已有 Event、Alert 或生命周期事实。
|
||||
@@ -0,0 +1,48 @@
|
||||
# Bell
|
||||
|
||||
Bell 是独立部署的预警管理产品。本目录从冻结的 go-admin/go-admin-ui 完整源码派生;来源与裁剪证据见 `LICENSES/SOURCES.md`。
|
||||
|
||||
## 固定工具链
|
||||
|
||||
- Go `1.26.5`:`$env:GOTOOLCHAIN='go1.26.5'`
|
||||
- Node `22.22.1`
|
||||
- pnpm `9.15.1`:`corepack pnpm@9.15.1`
|
||||
|
||||
## 必需环境变量
|
||||
|
||||
```text
|
||||
BELL_DATABASE_URL=<独立 PostgreSQL DSN>
|
||||
BELL_JWT_SECRET=<至少 32 字符的独立随机值>
|
||||
BELL_BOOTSTRAP_USERNAME=<仅首次迁移使用>
|
||||
BELL_BOOTSTRAP_PASSWORD=<仅首次迁移使用,至少 8 字符>
|
||||
```
|
||||
|
||||
可选 `BELL_HOST`、`BELL_PORT` 覆盖默认监听 `127.0.0.1:18090`。不要把这些值写入仓库。
|
||||
|
||||
## 迁移与启动
|
||||
|
||||
```powershell
|
||||
Set-Location Bell/server
|
||||
$env:GOTOOLCHAIN='go1.26.5'
|
||||
go run . migrate -c config/settings.yml
|
||||
go run . server -c config/settings.yml
|
||||
```
|
||||
|
||||
前端:
|
||||
|
||||
```powershell
|
||||
Set-Location Bell/ui
|
||||
corepack pnpm@9.15.1 install --frozen-lockfile
|
||||
corepack pnpm@9.15.1 dev
|
||||
```
|
||||
|
||||
生产构建使用 `corepack pnpm@9.15.1 build:prod`。生产环境不会生成或接受仓库默认管理员、默认 JWT secret 或默认数据库连接串。
|
||||
|
||||
## Windows 交付与独立验收
|
||||
|
||||
- Windows 构建:`Bell\scripts\build\build-windows.bat`
|
||||
- 包审计:`pwsh -NoProfile -File Bell\scripts\build\test-package.ps1 -PackageRoot Bell\dist\bell-windows-amd64`
|
||||
- 隔离 E2E:`pwsh -NoProfile -File Bell\scripts\test-independent-e2e.ps1 -PreparedPackageRoot Bell\dist\bell-windows-amd64`
|
||||
- 包内启动、检查和停止:`start-bell.bat`、`check-bell.bat -Running`、`stop-bell.bat`
|
||||
|
||||
完整配置、排错和验收标准见 `README-WINDOWS.md` 与 `ACCEPTANCE.md`。隔离 E2E 使用临时 PostgreSQL、随机端口和随机凭据,不启动或调用 Sense、Brain。
|
||||
@@ -0,0 +1,11 @@
|
||||
# Bell production environment. Copy values into process environment or this file.
|
||||
BELL_HOST=127.0.0.1
|
||||
BELL_PORT=18090
|
||||
BELL_WEB_HOST=127.0.0.1
|
||||
BELL_WEB_PORT=18091
|
||||
BELL_DATABASE_URL=
|
||||
BELL_JWT_SECRET=
|
||||
BELL_BOOTSTRAP_USERNAME=
|
||||
BELL_BOOTSTRAP_PASSWORD=
|
||||
BELL_AUTO_MIGRATE=true
|
||||
BELL_SYNTHETIC_EVENTS_ENABLED=false
|
||||
@@ -0,0 +1,13 @@
|
||||
param([Parameter(Mandatory = $true)][string]$WebRoot)
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = [IO.Path]::GetFullPath($WebRoot)
|
||||
$index = Join-Path $root 'index.html'
|
||||
if (-not (Test-Path -LiteralPath $index -PathType Leaf)) { throw 'web/index.html is missing.' }
|
||||
$html = Get-Content -LiteralPath $index -Raw -Encoding UTF8
|
||||
$references = [regex]::Matches($html, '(?:src|href)=["''](?<path>/[^"''?#]+)') | ForEach-Object { $_.Groups['path'].Value.TrimStart('/').Replace('/', '\') }
|
||||
foreach ($relative in $references | Sort-Object -Unique) {
|
||||
if ($relative -match '^https?:') { continue }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $root $relative) -PathType Leaf)) { throw "web asset referenced by index.html is missing: $relative" }
|
||||
}
|
||||
Write-Host "Bell web asset check passed: $root"
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal
|
||||
where pwsh.exe >nul 2>nul
|
||||
if %errorlevel% equ 0 (pwsh.exe -NoProfile -File "%~dp0build-windows.ps1" %*) else (powershell.exe -NoProfile -File "%~dp0build-windows.ps1" %*)
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,88 @@
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$bellRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
|
||||
$repositoryRoot = Split-Path $bellRoot -Parent
|
||||
$serverRoot = Join-Path $bellRoot 'server'
|
||||
$uiRoot = Join-Path $bellRoot 'ui'
|
||||
$distRoot = Join-Path $bellRoot 'dist'
|
||||
$target = Join-Path $distRoot 'bell-windows-amd64'
|
||||
$archive = Join-Path $distRoot 'bell-windows-amd64.zip'
|
||||
$staging = Join-Path $distRoot ('.bell-windows-amd64.staging-' + $PID)
|
||||
|
||||
function Assert-ChildPath([string]$Parent,[string]$Child) {
|
||||
$parentPath = [IO.Path]::GetFullPath($Parent).TrimEnd('\') + '\'
|
||||
$childPath = [IO.Path]::GetFullPath($Child)
|
||||
if (-not $childPath.StartsWith($parentPath,[StringComparison]::OrdinalIgnoreCase)) { throw "Unsafe build path outside $Parent`: $Child" }
|
||||
}
|
||||
function Get-FileSha256([string]$Path) {
|
||||
$sha = [Security.Cryptography.SHA256]::Create(); $stream = [IO.File]::OpenRead($Path)
|
||||
try { return ([BitConverter]::ToString($sha.ComputeHash($stream))).Replace('-','') } finally { $stream.Dispose(); $sha.Dispose() }
|
||||
}
|
||||
Assert-ChildPath $bellRoot $distRoot; Assert-ChildPath $distRoot $target; Assert-ChildPath $distRoot $archive; Assert-ChildPath $distRoot $staging
|
||||
|
||||
$savedToolchain = $env:GOTOOLCHAIN
|
||||
$env:GOTOOLCHAIN = 'go1.26.5'
|
||||
try {
|
||||
Push-Location $serverRoot
|
||||
try { $goVersion = (& go env GOVERSION).Trim() } finally { Pop-Location }
|
||||
$nodeVersion = (& node --version).Trim().TrimStart('v')
|
||||
$pnpmVersion = (& corepack pnpm@9.15.1 --version).Trim()
|
||||
if ($goVersion -ne 'go1.26.5') { throw "Go 1.26.5 is required; found $goVersion." }
|
||||
if ($nodeVersion -ne '22.22.1') { throw "Node 22.22.1 is required; found $nodeVersion." }
|
||||
if ($pnpmVersion -ne '9.15.1') { throw "pnpm 9.15.1 is required; found $pnpmVersion." }
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $distRoot | Out-Null
|
||||
if (Test-Path -LiteralPath $staging) { Remove-Item -LiteralPath $staging -Recurse -Force }
|
||||
New-Item -ItemType Directory -Path $staging | Out-Null
|
||||
Push-Location $uiRoot
|
||||
try {
|
||||
& corepack pnpm@9.15.1 install --frozen-lockfile
|
||||
if ($LASTEXITCODE -ne 0) { throw 'pnpm install failed.' }
|
||||
& corepack pnpm@9.15.1 run build:prod
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell UI production build failed.' }
|
||||
# The frozen Vue CLI differential build references a module runtime
|
||||
# that ScriptExt removes from disk. The complete legacy bundle is
|
||||
# present, so make that reproducible bundle the package entry point.
|
||||
$builtIndex = Join-Path $uiRoot 'dist\index.html'
|
||||
$html = Get-Content -LiteralPath $builtIndex -Raw -Encoding UTF8
|
||||
$html = [regex]::Replace($html, '<script[^>]+type="module"[^>]*></script>', '')
|
||||
$html = $html.Replace(' nomodule', '')
|
||||
[IO.File]::WriteAllText($builtIndex, $html, (New-Object Text.UTF8Encoding($false)))
|
||||
} finally { Pop-Location }
|
||||
|
||||
$oldGOOS,$oldGOARCH,$oldCGO = $env:GOOS,$env:GOARCH,$env:CGO_ENABLED
|
||||
try {
|
||||
$env:GOOS='windows'; $env:GOARCH='amd64'; $env:CGO_ENABLED='0'
|
||||
Push-Location $serverRoot
|
||||
try { & go build -trimpath -ldflags '-s -w' -o (Join-Path $staging 'bell.exe') .; if ($LASTEXITCODE -ne 0) { throw 'Bell server Windows build failed.' } } finally { Pop-Location }
|
||||
} finally { $env:GOOS,$env:GOARCH,$env:CGO_ENABLED=$oldGOOS,$oldGOARCH,$oldCGO }
|
||||
|
||||
Copy-Item -LiteralPath (Join-Path $uiRoot 'dist') -Destination (Join-Path $staging 'web') -Recurse
|
||||
New-Item -ItemType Directory -Path (Join-Path $staging 'scripts\runtime'),(Join-Path $staging 'config'),(Join-Path $staging 'LICENSES') | Out-Null
|
||||
Copy-Item -Path (Join-Path $bellRoot 'scripts\runtime\*.ps1') -Destination (Join-Path $staging 'scripts\runtime')
|
||||
foreach ($name in @('start-bell','stop-bell','check-bell')) { Copy-Item -LiteralPath (Join-Path $bellRoot "scripts\runtime\$name.bat") -Destination (Join-Path $staging "$name.bat") }
|
||||
Copy-Item -LiteralPath (Join-Path $bellRoot 'config\bell.env.example') -Destination (Join-Path $staging 'config\bell.env.example')
|
||||
Copy-Item -LiteralPath (Join-Path $bellRoot 'config\bell.env.example') -Destination (Join-Path $staging 'config\bell.env')
|
||||
Copy-Item -LiteralPath (Join-Path $serverRoot 'config\settings.yml') -Destination (Join-Path $staging 'config\settings.yml')
|
||||
Copy-Item -LiteralPath (Join-Path $serverRoot 'config\db.sql') -Destination (Join-Path $staging 'config\db.sql')
|
||||
Copy-Item -LiteralPath (Join-Path $serverRoot 'config\pg.sql') -Destination (Join-Path $staging 'config\pg.sql')
|
||||
Copy-Item -LiteralPath (Join-Path $bellRoot 'README-WINDOWS.md') -Destination (Join-Path $staging 'README-WINDOWS.md')
|
||||
Copy-Item -LiteralPath (Join-Path $bellRoot 'LICENSES') -Destination $staging -Recurse -Force
|
||||
Copy-Item -LiteralPath (Join-Path $serverRoot 'LICENSE.md') -Destination (Join-Path $staging 'LICENSES\Bell-server-LICENSE.md')
|
||||
Copy-Item -LiteralPath (Join-Path $uiRoot 'LICENSE') -Destination (Join-Path $staging 'LICENSES\Bell-ui-LICENSE')
|
||||
$commit = (& git -C $repositoryRoot rev-parse HEAD).Trim()
|
||||
[IO.File]::WriteAllLines((Join-Path $staging 'VERSION.txt'),@("source_commit=$commit",'go=1.26.5','node=22.22.1','pnpm=9.15.1'),(New-Object Text.UTF8Encoding($false)))
|
||||
& (Join-Path $PSScriptRoot 'test-package.ps1') -PackageRoot $staging
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell package audit failed.' }
|
||||
$manifest = foreach ($file in Get-ChildItem -LiteralPath $staging -Recurse -File | Sort-Object FullName) { "$(Get-FileSha256 $file.FullName) $($file.FullName.Substring($staging.Length+1).Replace('\','/'))" }
|
||||
[IO.File]::WriteAllLines((Join-Path $staging 'MANIFEST.sha256'),$manifest,(New-Object Text.UTF8Encoding($false)))
|
||||
if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force }
|
||||
Move-Item -LiteralPath $staging -Destination $target
|
||||
if (Test-Path -LiteralPath $archive) { Remove-Item -LiteralPath $archive -Force }
|
||||
Compress-Archive -LiteralPath $target -DestinationPath $archive -CompressionLevel Optimal
|
||||
Write-Host "Bell Windows package: $target"
|
||||
Write-Host "Bell Windows archive: $archive"
|
||||
} finally {
|
||||
$env:GOTOOLCHAIN = $savedToolchain
|
||||
if (Test-Path -LiteralPath $staging) { Remove-Item -LiteralPath $staging -Recurse -Force }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
param([Parameter(Mandatory = $true)][string]$PackageRoot)
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = [IO.Path]::GetFullPath($PackageRoot)
|
||||
if (-not (Test-Path -LiteralPath $root -PathType Container)) { throw "Package directory not found: $root" }
|
||||
$required = @(
|
||||
'bell.exe','start-bell.bat','stop-bell.bat','check-bell.bat','README-WINDOWS.md',
|
||||
'config\bell.env','config\bell.env.example','config\settings.yml','config\db.sql','config\pg.sql','web\index.html',
|
||||
'scripts\runtime\bell-common.ps1','scripts\runtime\bell-web.ps1',
|
||||
'LICENSES\SOURCES.md','LICENSES\go-admin-LICENSE.md','LICENSES\go-admin-ui-LICENSE',
|
||||
'VERSION.txt'
|
||||
)
|
||||
foreach ($relative in $required) { if (-not (Test-Path -LiteralPath (Join-Path $root $relative))) { throw "Package is missing required path: $relative" } }
|
||||
& (Join-Path $PSScriptRoot 'assert-web-assets.ps1') -WebRoot (Join-Path $root 'web')
|
||||
$forbiddenDirectories = Get-ChildItem -LiteralPath $root -Recurse -Directory | Where-Object { $_.Name -in @('node_modules','.git','dist','.cache') }
|
||||
if ($forbiddenDirectories) { throw "Package contains forbidden build directory: $($forbiddenDirectories[0].FullName)" }
|
||||
$forbiddenFiles = Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object { $_.Extension -in @('.db','.sqlite','.sqlite3','.dump','.bak') }
|
||||
if ($forbiddenFiles) { throw "Package contains database or backup data: $($forbiddenFiles[0].FullName)" }
|
||||
$config = Get-Content -LiteralPath (Join-Path $root 'config\bell.env') -Raw -Encoding UTF8
|
||||
foreach ($secret in @('BELL_DATABASE_URL','BELL_JWT_SECRET','BELL_BOOTSTRAP_USERNAME','BELL_BOOTSTRAP_PASSWORD')) {
|
||||
if ($config -match "(?m)^$secret[ \t]*=[ \t]*[^ \t\r\n]") { throw "Package contains a non-empty credential field: $secret" }
|
||||
}
|
||||
$sources = Get-Content -LiteralPath (Join-Path $root 'LICENSES\SOURCES.md') -Raw -Encoding UTF8
|
||||
foreach ($commit in @('f06540883b41d03782bb6b2c4150f298f328c6b6','67d393d713877572fab0b897296a4c1d525fc81d','424855aacf6905f3fde860c3331385cb25529a0d')) {
|
||||
if (-not $sources.Contains($commit)) { throw "Package source evidence is missing commit $commit" }
|
||||
}
|
||||
$version = Get-Content -LiteralPath (Join-Path $root 'VERSION.txt') -Raw -Encoding UTF8
|
||||
foreach ($entry in @('go=1.26.5','node=22.22.1','pnpm=9.15.1')) { if (-not $version.Contains($entry)) { throw "Package version evidence is missing $entry" } }
|
||||
$textExtensions = @('.md','.txt','.env','.example','.ps1','.bat','.yml','.yaml','.json','.html','.js','.css')
|
||||
foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object { $textExtensions -contains $_.Extension.ToLowerInvariant() }) {
|
||||
$content = [string](Get-Content -LiteralPath $file.FullName -Raw -ErrorAction SilentlyContinue)
|
||||
if ($content -match '(?i)(admin123|password123|BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY)') { throw "Package contains a forbidden default credential or private key marker: $($file.FullName)" }
|
||||
}
|
||||
Write-Host "Bell package audit passed: $root"
|
||||
@@ -0,0 +1,117 @@
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$script:BellAllowedEnvironment = @(
|
||||
'BELL_HOST', 'BELL_PORT', 'BELL_WEB_HOST', 'BELL_WEB_PORT',
|
||||
'BELL_DATABASE_URL', 'BELL_JWT_SECRET', 'BELL_BOOTSTRAP_USERNAME',
|
||||
'BELL_BOOTSTRAP_PASSWORD', 'BELL_AUTO_MIGRATE',
|
||||
'BELL_SYNTHETIC_EVENTS_ENABLED'
|
||||
)
|
||||
|
||||
function Get-BellPackageRoot {
|
||||
param([string]$ScriptDirectory = $PSScriptRoot)
|
||||
return [IO.Path]::GetFullPath((Join-Path $ScriptDirectory '..\..'))
|
||||
}
|
||||
function Import-BellEnvironment {
|
||||
param([Parameter(Mandatory = $true)][string]$Path)
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Bell configuration file not found: $Path" }
|
||||
$lineNumber = 0
|
||||
foreach ($rawLine in Get-Content -LiteralPath $Path -Encoding UTF8) {
|
||||
$lineNumber++
|
||||
$line = $rawLine.Trim()
|
||||
if ($line.Length -eq 0 -or $line.StartsWith('#')) { continue }
|
||||
$separator = $line.IndexOf('=')
|
||||
if ($separator -lt 1) { throw "Invalid Bell configuration at line $lineNumber. Expected NAME=value." }
|
||||
$name = $line.Substring(0, $separator).Trim()
|
||||
if ($script:BellAllowedEnvironment -notcontains $name) { throw "Unsupported Bell configuration key at line ${lineNumber}: $name" }
|
||||
$value = $line.Substring($separator + 1)
|
||||
if ($value.Length -ge 2) {
|
||||
$first, $last = $value[0], $value[$value.Length - 1]
|
||||
if (($first -eq '"' -and $last -eq '"') -or ($first -eq "'" -and $last -eq "'")) { $value = $value.Substring(1, $value.Length - 2) }
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name, 'Process'))) {
|
||||
[Environment]::SetEnvironmentVariable($name, $value, 'Process')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Get-BellEnvironmentValue {
|
||||
param([Parameter(Mandatory = $true)][string]$Name, [string]$Default = '')
|
||||
$value = [Environment]::GetEnvironmentVariable($Name, 'Process')
|
||||
if ([string]::IsNullOrWhiteSpace($value)) { return $Default }
|
||||
return $value
|
||||
}
|
||||
|
||||
function Test-BellTcpEndpoint {
|
||||
param([Parameter(Mandatory = $true)][string]$HostName, [Parameter(Mandatory = $true)][int]$Port, [int]$TimeoutMilliseconds = 2000)
|
||||
$client = [Net.Sockets.TcpClient]::new()
|
||||
try { return $client.ConnectAsync($HostName, $Port).Wait($TimeoutMilliseconds) -and $client.Connected } catch { return $false } finally { $client.Dispose() }
|
||||
}
|
||||
|
||||
function Test-BellListenPortAvailable {
|
||||
param([Parameter(Mandatory = $true)][string]$HostName, [Parameter(Mandatory = $true)][int]$Port)
|
||||
$ip = if ($HostName -eq '0.0.0.0') { [Net.IPAddress]::Any } elseif ($HostName -in @('127.0.0.1', 'localhost')) { [Net.IPAddress]::Loopback } else { [Net.IPAddress]::Parse($HostName) }
|
||||
$listener = [Net.Sockets.TcpListener]::new($ip, $Port)
|
||||
try { $listener.Start(); return $true } catch { return $false } finally { try { $listener.Stop() } catch {} }
|
||||
}
|
||||
|
||||
function Get-BellDatabaseEndpoint {
|
||||
param([Parameter(Mandatory = $true)][string]$Connection)
|
||||
if ($Connection -match '^postgres(?:ql)?://') {
|
||||
$uri = [Uri]$Connection
|
||||
return [pscustomobject]@{ Host = $uri.Host; Port = $(if ($uri.IsDefaultPort) { 5432 } else { $uri.Port }); Database = $uri.AbsolutePath.TrimStart('/') }
|
||||
}
|
||||
$values = @{}
|
||||
foreach ($match in [regex]::Matches($Connection, '(?:^|\s)(?<key>[A-Za-z_][A-Za-z0-9_]*)=(?<value>''(?:[^'']|'''')*''|"(?:[^"]|"")*"|[^\s]+)')) {
|
||||
$value = $match.Groups['value'].Value.Trim("'", '"')
|
||||
$values[$match.Groups['key'].Value.ToLowerInvariant()] = $value
|
||||
}
|
||||
if ($values.Count -eq 0) { throw 'BELL_DATABASE_URL must be a PostgreSQL URI or keyword connection string.' }
|
||||
return [pscustomobject]@{ Host = $(if ($values.host) { $values.host } else { '127.0.0.1' }); Port = $(if ($values.port) { [int]$values.port } else { 5432 }); Database = [string]$values.dbname }
|
||||
}
|
||||
|
||||
function Get-BellPort {
|
||||
param([string]$Name, [int]$Default)
|
||||
$text = Get-BellEnvironmentValue -Name $Name -Default $Default.ToString()
|
||||
$port = 0
|
||||
if (-not [int]::TryParse($text, [ref]$port) -or $port -lt 1 -or $port -gt 65535) { throw "$Name must be an integer between 1 and 65535." }
|
||||
return $port
|
||||
}
|
||||
|
||||
function Initialize-BellRuntime {
|
||||
param([Parameter(Mandatory = $true)][string]$PackageRoot, [switch]$AllowOccupiedPorts)
|
||||
Import-BellEnvironment -Path (Join-Path $PackageRoot 'config\bell.env')
|
||||
$hostName = Get-BellEnvironmentValue -Name 'BELL_HOST' -Default '127.0.0.1'
|
||||
$webHost = Get-BellEnvironmentValue -Name 'BELL_WEB_HOST' -Default '127.0.0.1'
|
||||
if ($hostName -notin @('127.0.0.1', 'localhost') -or $webHost -notin @('127.0.0.1', 'localhost')) { throw 'BELL_HOST and BELL_WEB_HOST must be loopback addresses.' }
|
||||
$port = Get-BellPort -Name 'BELL_PORT' -Default 18090
|
||||
$webPort = Get-BellPort -Name 'BELL_WEB_PORT' -Default 18091
|
||||
if ($port -eq $webPort) { throw 'BELL_PORT and BELL_WEB_PORT must be different.' }
|
||||
if (-not $AllowOccupiedPorts) {
|
||||
if (-not (Test-BellListenPortAvailable -HostName $hostName -Port $port)) { throw "Bell backend port $hostName`:$port is already in use." }
|
||||
if (-not (Test-BellListenPortAvailable -HostName $webHost -Port $webPort)) { throw "Bell web port $webHost`:$webPort is already in use." }
|
||||
}
|
||||
$databaseURL = Get-BellEnvironmentValue -Name 'BELL_DATABASE_URL'
|
||||
if ([string]::IsNullOrWhiteSpace($databaseURL)) { throw 'BELL_DATABASE_URL is required.' }
|
||||
$database = Get-BellDatabaseEndpoint -Connection $databaseURL
|
||||
if ([string]::IsNullOrWhiteSpace($database.Database)) { throw 'BELL_DATABASE_URL must name a database.' }
|
||||
if (-not (Test-BellTcpEndpoint -HostName $database.Host -Port $database.Port)) { throw "PostgreSQL is unreachable at $($database.Host):$($database.Port)." }
|
||||
$jwt = Get-BellEnvironmentValue -Name 'BELL_JWT_SECRET'
|
||||
if ($jwt.Length -lt 32 -or $jwt.StartsWith('__BELL_')) { throw 'BELL_JWT_SECRET must contain at least 32 non-default characters.' }
|
||||
$webRoot = Join-Path $PackageRoot 'web'
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $webRoot 'index.html') -PathType Leaf)) { throw "Bell web assets are missing: $webRoot" }
|
||||
return [pscustomobject]@{
|
||||
Host = $hostName; Port = $port; WebHost = $webHost; WebPort = $webPort;
|
||||
BackendUrl = "http://$hostName`:$port"; WebUrl = "http://$webHost`:$webPort";
|
||||
SettingsPath = (Join-Path $PackageRoot 'config\settings.yml'); WebRoot = $webRoot
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-BellHealth {
|
||||
param([Parameter(Mandatory = $true)][string]$BaseUrl, [int]$Attempts = 100)
|
||||
for ($attempt = 0; $attempt -lt $Attempts; $attempt++) {
|
||||
try { $health = Invoke-RestMethod -Uri "$BaseUrl/healthz" -TimeoutSec 2 -NoProxy; if ($health.status -eq 'ok' -and $health.service -eq 'bell') { return } } catch {}
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
throw "Bell health check timed out: $BaseUrl/healthz"
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$WebRoot,
|
||||
[Parameter(Mandatory = $true)][string]$ListenHost,
|
||||
[Parameter(Mandatory = $true)][int]$ListenPort,
|
||||
[Parameter(Mandatory = $true)][string]$BackendUrl
|
||||
)
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$root = [IO.Path]::GetFullPath($WebRoot).TrimEnd('\') + '\'
|
||||
$listener = [Net.HttpListener]::new()
|
||||
$listener.Prefixes.Add("http://$ListenHost`:$ListenPort/")
|
||||
$handler = [Net.Http.HttpClientHandler]::new()
|
||||
$handler.UseProxy = $false
|
||||
$client = [Net.Http.HttpClient]::new($handler)
|
||||
$mime = @{ '.html'='text/html; charset=utf-8'; '.js'='application/javascript; charset=utf-8'; '.css'='text/css; charset=utf-8'; '.json'='application/json; charset=utf-8'; '.svg'='image/svg+xml'; '.png'='image/png'; '.jpg'='image/jpeg'; '.jpeg'='image/jpeg'; '.gif'='image/gif'; '.ico'='image/x-icon'; '.woff'='font/woff'; '.woff2'='font/woff2'; '.ttf'='font/ttf'; '.eot'='application/vnd.ms-fontobject' }
|
||||
|
||||
try {
|
||||
$listener.Start()
|
||||
Write-Host "Bell web listening at http://$ListenHost`:$ListenPort/"
|
||||
while ($listener.IsListening) {
|
||||
$context = $listener.GetContext()
|
||||
try {
|
||||
$request = $context.Request
|
||||
$response = $context.Response
|
||||
$path = $request.Url.AbsolutePath
|
||||
if ($path -eq '/healthz' -or $path.StartsWith('/api/')) {
|
||||
$target = "$BackendUrl$($request.Url.PathAndQuery)"
|
||||
$message = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::new($request.HttpMethod), $target)
|
||||
if ($request.HasEntityBody) {
|
||||
$memory = [IO.MemoryStream]::new()
|
||||
$request.InputStream.CopyTo($memory)
|
||||
$message.Content = [Net.Http.ByteArrayContent]::new($memory.ToArray())
|
||||
$memory.Dispose()
|
||||
}
|
||||
foreach ($key in $request.Headers.AllKeys) {
|
||||
if ($key -in @('Host','Content-Length')) { continue }
|
||||
$values = $request.Headers.GetValues($key)
|
||||
if (-not $message.Headers.TryAddWithoutValidation($key, $values) -and $null -ne $message.Content) { [void]$message.Content.Headers.TryAddWithoutValidation($key, $values) }
|
||||
}
|
||||
$upstream = $client.SendAsync($message).GetAwaiter().GetResult()
|
||||
$bytes = $upstream.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult()
|
||||
$response.StatusCode = [int]$upstream.StatusCode
|
||||
if ($upstream.Content.Headers.ContentType) { $response.ContentType = $upstream.Content.Headers.ContentType.ToString() }
|
||||
$response.ContentLength64 = $bytes.Length
|
||||
$response.OutputStream.Write($bytes, 0, $bytes.Length)
|
||||
$message.Dispose(); $upstream.Dispose()
|
||||
} else {
|
||||
$relative = [Uri]::UnescapeDataString($path.TrimStart('/')).Replace('/', '\')
|
||||
if ([string]::IsNullOrWhiteSpace($relative)) { $relative = 'index.html' }
|
||||
$file = [IO.Path]::GetFullPath((Join-Path $root $relative))
|
||||
if (-not $file.StartsWith($root, [StringComparison]::OrdinalIgnoreCase)) { $response.StatusCode = 403 }
|
||||
elseif (-not (Test-Path -LiteralPath $file -PathType Leaf)) {
|
||||
$file = Join-Path $root 'index.html'
|
||||
}
|
||||
if ($response.StatusCode -ne 403) {
|
||||
$bytes = [IO.File]::ReadAllBytes($file)
|
||||
$extension = [IO.Path]::GetExtension($file).ToLowerInvariant()
|
||||
$response.ContentType = $(if ($mime.ContainsKey($extension)) { $mime[$extension] } else { 'application/octet-stream' })
|
||||
$response.ContentLength64 = $bytes.Length
|
||||
$response.OutputStream.Write($bytes, 0, $bytes.Length)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
try { $context.Response.StatusCode = 502; $bytes = [Text.Encoding]::UTF8.GetBytes('Bell web gateway error'); $context.Response.ContentLength64 = $bytes.Length; $context.Response.OutputStream.Write($bytes,0,$bytes.Length) } catch {}
|
||||
} finally {
|
||||
try { $context.Response.OutputStream.Close() } catch {}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$client.Dispose(); $handler.Dispose(); try { $listener.Stop() } catch {}; $listener.Close()
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal
|
||||
where pwsh.exe >nul 2>nul
|
||||
if %errorlevel% equ 0 (pwsh.exe -NoProfile -File "%~dp0scripts\runtime\check-bell.ps1" %*) else (powershell.exe -NoProfile -File "%~dp0scripts\runtime\check-bell.ps1" %*)
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,12 @@
|
||||
param([switch]$Running)
|
||||
. (Join-Path $PSScriptRoot 'bell-common.ps1')
|
||||
try {
|
||||
$root = Get-BellPackageRoot
|
||||
$state = Initialize-BellRuntime -PackageRoot $root -AllowOccupiedPorts:$Running
|
||||
if ($Running) {
|
||||
Wait-BellHealth -BaseUrl $state.BackendUrl -Attempts 2
|
||||
Wait-BellHealth -BaseUrl $state.WebUrl -Attempts 2
|
||||
}
|
||||
Write-Host "Bell configuration check passed. PostgreSQL reachable; backend=$($state.BackendUrl); web=$($state.WebUrl)."
|
||||
exit 0
|
||||
} catch { Write-Error $_.Exception.Message; exit 1 }
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal
|
||||
where pwsh.exe >nul 2>nul
|
||||
if %errorlevel% equ 0 (pwsh.exe -NoProfile -File "%~dp0scripts\runtime\start-bell.ps1" %*) else (powershell.exe -NoProfile -File "%~dp0scripts\runtime\start-bell.ps1" %*)
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,41 @@
|
||||
param([switch]$SkipMigration)
|
||||
. (Join-Path $PSScriptRoot 'bell-common.ps1')
|
||||
|
||||
$backend = $null
|
||||
$pidFile = $null
|
||||
try {
|
||||
$root = Get-BellPackageRoot
|
||||
$state = Initialize-BellRuntime -PackageRoot $root
|
||||
$bell = Join-Path $root 'bell.exe'
|
||||
if (-not (Test-Path -LiteralPath $bell -PathType Leaf)) { throw "Bell executable not found: $bell" }
|
||||
$runtime = Join-Path $root 'runtime'
|
||||
$logs = Join-Path $runtime 'logs'
|
||||
New-Item -ItemType Directory -Force -Path $logs,(Join-Path $root 'temp\logs') | Out-Null
|
||||
$pidFile = Join-Path $runtime 'bell.pid'
|
||||
if (Test-Path -LiteralPath $pidFile) {
|
||||
$oldPid = 0
|
||||
if ([int]::TryParse((Get-Content -LiteralPath $pidFile -Raw).Trim(), [ref]$oldPid) -and (Get-Process -Id $oldPid -ErrorAction SilentlyContinue)) { throw "Bell appears to be running with process id $oldPid." }
|
||||
Remove-Item -LiteralPath $pidFile -Force
|
||||
}
|
||||
[IO.File]::WriteAllText($pidFile, "$PID", (New-Object Text.UTF8Encoding($false)))
|
||||
Push-Location $root
|
||||
try {
|
||||
$autoMigrate = (Get-BellEnvironmentValue -Name 'BELL_AUTO_MIGRATE' -Default 'true').ToLowerInvariant()
|
||||
if (-not $SkipMigration -and $autoMigrate -notin @('false','0','no')) {
|
||||
Write-Host 'Applying pending Bell database migrations...'
|
||||
& $bell migrate -c $state.SettingsPath
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell database migration failed.' }
|
||||
}
|
||||
$backend = Start-Process -FilePath $bell -ArgumentList @('server','-c',$state.SettingsPath) -WorkingDirectory $root -RedirectStandardOutput (Join-Path $logs 'bell.out.log') -RedirectStandardError (Join-Path $logs 'bell.err.log') -WindowStyle Hidden -PassThru
|
||||
Wait-BellHealth -BaseUrl $state.BackendUrl
|
||||
Write-Host "Bell is available at $($state.WebUrl)/"
|
||||
Write-Host 'Press Ctrl+C in this window or run stop-bell.bat to stop Bell.'
|
||||
& (Join-Path $PSScriptRoot 'bell-web.ps1') -WebRoot $state.WebRoot -ListenHost $state.WebHost -ListenPort $state.WebPort -BackendUrl $state.BackendUrl
|
||||
} finally { Pop-Location }
|
||||
} catch {
|
||||
Write-Error $_.Exception.Message
|
||||
exit 1
|
||||
} finally {
|
||||
if ($backend -and -not $backend.HasExited) { & taskkill.exe /PID $backend.Id /T /F 2>$null | Out-Null }
|
||||
if ($pidFile -and (Test-Path -LiteralPath $pidFile)) { Remove-Item -LiteralPath $pidFile -Force }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal
|
||||
where pwsh.exe >nul 2>nul
|
||||
if %errorlevel% equ 0 (pwsh.exe -NoProfile -File "%~dp0scripts\runtime\stop-bell.ps1" %*) else (powershell.exe -NoProfile -File "%~dp0scripts\runtime\stop-bell.ps1" %*)
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,17 @@
|
||||
. (Join-Path $PSScriptRoot 'bell-common.ps1')
|
||||
try {
|
||||
$root = Get-BellPackageRoot
|
||||
$pidFile = Join-Path $root 'runtime\bell.pid'
|
||||
if (-not (Test-Path -LiteralPath $pidFile -PathType Leaf)) { Write-Host 'Bell is not running (no pid file).'; exit 0 }
|
||||
$processId = 0
|
||||
if (-not [int]::TryParse((Get-Content -LiteralPath $pidFile -Raw).Trim(), [ref]$processId)) { throw 'Bell pid file is invalid.' }
|
||||
$process = Get-CimInstance Win32_Process -Filter "ProcessId = $processId" -ErrorAction SilentlyContinue
|
||||
if (-not $process) { Remove-Item -LiteralPath $pidFile -Force; Write-Host 'Removed stale Bell pid file.'; exit 0 }
|
||||
$rootPattern = [regex]::Escape($root)
|
||||
if ($process.Name -notmatch '^(pwsh|powershell)\.exe$' -or $process.CommandLine -notmatch 'start-bell\.ps1' -or $process.CommandLine -notmatch $rootPattern) { throw "Process $processId is not the Bell package launcher; it was not stopped." }
|
||||
& taskkill.exe /PID $processId /T /F | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Failed to stop the Bell process tree.' }
|
||||
Remove-Item -LiteralPath $pidFile -Force -ErrorAction SilentlyContinue
|
||||
Write-Host 'Bell backend and web process tree stopped.'
|
||||
exit 0
|
||||
} catch { Write-Error $_.Exception.Message; exit 1 }
|
||||
@@ -0,0 +1,190 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$PostgresBin = 'D:\pgsql17\bin'
|
||||
)
|
||||
|
||||
Set-StrictMode -Version 3.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$server = $null
|
||||
$pgStarted = $false
|
||||
$testRoot = Join-Path ([IO.Path]::GetTempPath()) ('yovision-bell-131-' + [guid]::NewGuid().ToString('N'))
|
||||
$pgData = Join-Path $testRoot 'postgres'
|
||||
$pgLog = Join-Path $testRoot 'postgres.log'
|
||||
$pgCtlOut = Join-Path $testRoot 'pg-ctl.out.log'
|
||||
$pgCtlErr = Join-Path $testRoot 'pg-ctl.err.log'
|
||||
$serverOut = Join-Path $testRoot 'bell.out.log'
|
||||
$serverErr = Join-Path $testRoot 'bell.err.log'
|
||||
$serverExe = Join-Path $testRoot 'bell-server.exe'
|
||||
$serverRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\server')).Path
|
||||
|
||||
function Get-FreeTcpPort {
|
||||
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
|
||||
try {
|
||||
$listener.Start()
|
||||
return ([Net.IPEndPoint]$listener.LocalEndpoint).Port
|
||||
} finally {
|
||||
$listener.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-Tcp([int]$Port, [bool]$Open, [int]$Attempts = 120) {
|
||||
for ($attempt = 0; $attempt -lt $Attempts; $attempt++) {
|
||||
$client = [Net.Sockets.TcpClient]::new()
|
||||
try {
|
||||
$connected = $client.ConnectAsync('127.0.0.1', $Port).Wait(250) -and $client.Connected
|
||||
} catch {
|
||||
$connected = $false
|
||||
} finally {
|
||||
$client.Dispose()
|
||||
}
|
||||
if ($connected -eq $Open) { return }
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
throw "TCP port $Port did not reach open=$Open"
|
||||
}
|
||||
|
||||
function Wait-Health([string]$BaseUrl) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri "$BaseUrl/healthz" -TimeoutSec 2 -NoProxy
|
||||
if ($health.status -eq 'ok' -and $health.service -eq 'bell') { return }
|
||||
} catch {}
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
throw 'Bell health endpoint did not become ready'
|
||||
}
|
||||
|
||||
function Start-Bell([string]$BaseUrl, [string]$Config = 'config/settings.demo.yml') {
|
||||
$script:server = Start-Process -FilePath $serverExe -ArgumentList @('server', '-c', $Config) -WorkingDirectory $serverRoot -RedirectStandardOutput $serverOut -RedirectStandardError $serverErr -WindowStyle Hidden -PassThru
|
||||
Wait-Health $BaseUrl
|
||||
}
|
||||
|
||||
function Stop-Bell {
|
||||
if ($null -ne $script:server -and -not $script:server.HasExited) {
|
||||
Stop-Process -Id $script:server.Id -Force
|
||||
$script:server.WaitForExit(5000) | Out-Null
|
||||
}
|
||||
$script:server = $null
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $testRoot | Out-Null
|
||||
$pgPort = Get-FreeTcpPort
|
||||
$bellPort = Get-FreeTcpPort
|
||||
$baseUrl = "http://127.0.0.1:$bellPort"
|
||||
$database = 'bell_131'
|
||||
$adminPassword = [guid]::NewGuid().ToString('N')
|
||||
|
||||
try {
|
||||
foreach ($required in @('initdb.exe', 'pg_ctl.exe', 'createdb.exe', 'psql.exe')) {
|
||||
$path = Join-Path $PostgresBin $required
|
||||
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Missing PostgreSQL tool: $path" }
|
||||
}
|
||||
|
||||
& (Join-Path $PostgresBin 'initdb.exe') -D $pgData -U postgres -A trust --encoding=UTF8 --no-locale | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'isolated PostgreSQL initdb failed' }
|
||||
$pgArguments = "-D `"$pgData`" -l `"$pgLog`" -o `"-p $pgPort -h 127.0.0.1`" start"
|
||||
Start-Process -FilePath (Join-Path $PostgresBin 'pg_ctl.exe') -ArgumentList $pgArguments -RedirectStandardOutput $pgCtlOut -RedirectStandardError $pgCtlErr -WindowStyle Hidden | Out-Null
|
||||
Wait-Tcp -Port $pgPort -Open $true
|
||||
$pgStarted = $true
|
||||
& (Join-Path $PostgresBin 'createdb.exe') -h 127.0.0.1 -p $pgPort -U postgres $database
|
||||
if ($LASTEXITCODE -ne 0) { throw 'isolated Bell database creation failed' }
|
||||
|
||||
$env:GOTOOLCHAIN = 'go1.26.5'
|
||||
$env:BELL_DATABASE_URL = "host=127.0.0.1 port=$pgPort user=postgres dbname=$database sslmode=disable"
|
||||
$env:BELL_JWT_SECRET = [guid]::NewGuid().ToString('N') + [guid]::NewGuid().ToString('N')
|
||||
$env:BELL_BOOTSTRAP_USERNAME = 'bell_131_admin'
|
||||
$env:BELL_BOOTSTRAP_PASSWORD = $adminPassword
|
||||
$env:BELL_HOST = '127.0.0.1'
|
||||
$env:BELL_PORT = $bellPort.ToString()
|
||||
$env:BELL_SYNTHETIC_EVENTS_ENABLED = 'true'
|
||||
|
||||
Push-Location $serverRoot
|
||||
try {
|
||||
go run . migrate -c config/settings.demo.yml *> (Join-Path $testRoot 'migrate.log')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell migration failed' }
|
||||
go build -o $serverExe .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell build failed' }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
Start-Bell $baseUrl
|
||||
$unauthorized = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -ContentType 'application/json' -Body '{}' -TimeoutSec 5 -NoProxy
|
||||
if ([int]$unauthorized.code -ne 401) { throw "unauthenticated request returned code $($unauthorized.code)" }
|
||||
|
||||
$loginBody = @{ username = 'bell_131_admin'; password = $adminPassword; code = '0'; uuid = '0' } | ConvertTo-Json -Compress
|
||||
$login = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/login" -ContentType 'application/json' -Body $loginBody -TimeoutSec 5 -NoProxy
|
||||
if ([int]$login.code -ne 200 -or [string]::IsNullOrWhiteSpace($login.token)) { throw 'Bell login failed' }
|
||||
$headers = @{ Authorization = "Bearer $($login.token)" }
|
||||
|
||||
$occurredAt = '2026-08-29T00:00:00Z'
|
||||
$eventBody = @{
|
||||
sourceEventId = 'acceptance-001'; eventType = 'danger_area_entered'; occurredAt = $occurredAt
|
||||
location = '东门'; severity = 'high'; evidenceRef = 'evidence/acceptance-001'
|
||||
attributes = @{ rule = 'area-01'; target = 'anonymous' }
|
||||
} | ConvertTo-Json -Depth 6 -Compress
|
||||
$created = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body $eventBody -TimeoutSec 10 -NoProxy
|
||||
if ([int]$created.code -ne 200 -or $created.data.duplicate -ne $false) { throw 'first synthetic event was not accepted as new' }
|
||||
$eventId = [string]$created.data.event.id
|
||||
$receiptId = [string]$created.data.receipt.id
|
||||
if ([string]::IsNullOrWhiteSpace($eventId) -or [string]::IsNullOrWhiteSpace($receiptId)) { throw 'event or receipt id missing' }
|
||||
|
||||
$replay = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body $eventBody -TimeoutSec 10 -NoProxy
|
||||
if ([int]$replay.code -ne 200 -or $replay.data.duplicate -ne $true -or $replay.data.event.id -ne $eventId) { throw 'idempotent replay failed' }
|
||||
|
||||
$concurrentBody = @{
|
||||
sourceEventId = 'acceptance-concurrent'; eventType = 'danger_area_entered'; occurredAt = $occurredAt
|
||||
location = '西门'; severity = 'medium'; evidenceRef = 'evidence/acceptance-concurrent'
|
||||
attributes = @{ rule = 'area-02'; target = 'anonymous' }
|
||||
} | ConvertTo-Json -Depth 6 -Compress
|
||||
$authHeader = [string]$headers.Authorization
|
||||
$concurrent = 1..12 | ForEach-Object -Parallel {
|
||||
$requestHeaders = @{ Authorization = $using:authHeader }
|
||||
Invoke-RestMethod -Method Post -Uri "$using:baseUrl/api/v1/bell/synthetic-events" -Headers $requestHeaders -ContentType 'application/json; charset=utf-8' -Body $using:concurrentBody -TimeoutSec 20 -NoProxy
|
||||
} -ThrottleLimit 12
|
||||
$concurrentIds = @($concurrent | ForEach-Object { [string]$_.data.event.id } | Sort-Object -Unique)
|
||||
$newCount = @($concurrent | Where-Object { $_.data.duplicate -eq $false }).Count
|
||||
if ($concurrent.Count -ne 12 -or $concurrentIds.Count -ne 1 -or $newCount -ne 1) { throw 'concurrent idempotency did not converge to one Event' }
|
||||
|
||||
$conflictObject = $eventBody | ConvertFrom-Json
|
||||
$conflictObject.severity = 'critical'
|
||||
$conflict = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ($conflictObject | ConvertTo-Json -Depth 6 -Compress) -TimeoutSec 10 -NoProxy
|
||||
if ([int]$conflict.code -ne 409) { throw "idempotency conflict returned code $($conflict.code)" }
|
||||
|
||||
$malformed = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -Headers $headers -ContentType 'application/json' -Body '{' -TimeoutSec 10 -NoProxy
|
||||
if ([int]$malformed.code -ne 400) { throw "malformed request returned code $($malformed.code)" }
|
||||
$oversized = @{ sourceEventId='too-large'; eventType='test'; occurredAt=$occurredAt; location='lab'; severity='low'; attributes=@{ blob=('x' * 70000) } } | ConvertTo-Json -Depth 5 -Compress
|
||||
$tooLarge = Invoke-RestMethod -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -Headers $headers -ContentType 'application/json' -Body $oversized -TimeoutSec 10 -NoProxy
|
||||
if ([int]$tooLarge.code -ne 400) { throw "oversized request returned code $($tooLarge.code)" }
|
||||
|
||||
$psql = Join-Path $PostgresBin 'psql.exe'
|
||||
$counts = & $psql -h 127.0.0.1 -p $pgPort -U postgres -d $database -Atc "select count(*) from bell_events; select count(*) from bell_event_receipts; select count(*) from bell_event_ingest_audits where outcome='accepted'; select count(*) from bell_event_ingest_audits where outcome='replay'; select count(*) from bell_event_ingest_audits where outcome='conflict';"
|
||||
if (($counts -join ',') -ne '2,2,2,12,1') { throw "unexpected Bell fact counts: $($counts -join ',')" }
|
||||
$payloadAuditCount = & $psql -h 127.0.0.1 -p $pgPort -U postgres -d $database -Atc "select count(*) from sys_opera_log where oper_url='/api/v1/bell/synthetic-events' and (oper_param like '%sourceEventId%' or json_result like '%acceptance-001%');"
|
||||
if ([int]$payloadAuditCount -ne 0) { throw 'generic GoAdmin audit retained synthetic event payload' }
|
||||
& $psql -h 127.0.0.1 -p $pgPort -U postgres -d $database -v ON_ERROR_STOP=1 -c "update bell_events set severity='low' where id='$eventId'" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { throw 'immutable Event update unexpectedly succeeded' }
|
||||
& $psql -h 127.0.0.1 -p $pgPort -U postgres -d $database -v ON_ERROR_STOP=1 -c "delete from bell_event_receipts where id='$receiptId'" 2>$null | Out-Null
|
||||
if ($LASTEXITCODE -eq 0) { throw 'immutable Receipt delete unexpectedly succeeded' }
|
||||
|
||||
Stop-Bell
|
||||
Start-Bell $baseUrl
|
||||
$afterRestart = Invoke-RestMethod -Uri "$baseUrl/api/v1/bell/events/$eventId" -Headers $headers -TimeoutSec 10 -NoProxy
|
||||
if ([int]$afterRestart.code -ne 200 -or $afterRestart.data.id -ne $eventId) { throw 'Event was not readable after Bell restart' }
|
||||
|
||||
Stop-Bell
|
||||
Start-Bell $baseUrl 'config/settings.yml'
|
||||
$productionSynthetic = Invoke-WebRequest -Method Post -Uri "$baseUrl/api/v1/bell/synthetic-events" -ContentType 'application/json' -Body '{}' -TimeoutSec 10 -NoProxy -SkipHttpErrorCheck
|
||||
if ([int]$productionSynthetic.StatusCode -ne 404) { throw "production synthetic route returned HTTP $($productionSynthetic.StatusCode)" }
|
||||
|
||||
Write-Output "BELL_131_SMOKE events=2 receipts=2 concurrent=12 audit=redacted immutable=true restart=true production_synthetic=404"
|
||||
} finally {
|
||||
Stop-Bell
|
||||
if ($pgStarted) {
|
||||
& (Join-Path $PostgresBin 'pg_ctl.exe') -D $pgData -m fast stop *> (Join-Path $testRoot 'pg-stop.log')
|
||||
}
|
||||
foreach ($name in @('BELL_DATABASE_URL','BELL_JWT_SECRET','BELL_BOOTSTRAP_USERNAME','BELL_BOOTSTRAP_PASSWORD','BELL_HOST','BELL_PORT','BELL_SYNTHETIC_EVENTS_ENABLED')) {
|
||||
Remove-Item "Env:$name" -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Verbose "Bell #131 temporary artifacts: $testRoot"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
param([string]$PostgresBin='D:\pgsql17\bin',[string]$PreparedPackageRoot='',[switch]$KeepTemporary,[switch]$BrowserHold)
|
||||
$arguments=@('-NoProfile','-File',(Join-Path $PSScriptRoot '..\tests\e2e\run-isolated-e2e.ps1'),'-PostgresBin',$PostgresBin)
|
||||
if(-not[string]::IsNullOrWhiteSpace($PreparedPackageRoot)){$arguments+=@('-PreparedPackageRoot',$PreparedPackageRoot)}
|
||||
if($KeepTemporary){$arguments+='-KeepTemporary'}
|
||||
if($BrowserHold){$arguments+='-BrowserHold'}
|
||||
& pwsh.exe @arguments
|
||||
exit $LASTEXITCODE
|
||||
@@ -0,0 +1,83 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$PostgresBin = 'D:\pgsql17\bin',
|
||||
[int]$PostgresPort = 55462,
|
||||
[int]$BellPort = 18092,
|
||||
[string]$Database = 'bell_62'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$serverProcess = $null
|
||||
$testRoot = Join-Path ([System.IO.Path]::GetTempPath()) 'yovision-bell-62-smoke'
|
||||
$serverExe = Join-Path $testRoot 'bell-server.exe'
|
||||
$stdout = Join-Path $testRoot 'bell-server.out.log'
|
||||
$stderr = Join-Path $testRoot 'bell-server.err.log'
|
||||
$serverRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\server')).Path
|
||||
$dropDb = Join-Path $PostgresBin 'dropdb.exe'
|
||||
$createDb = Join-Path $PostgresBin 'createdb.exe'
|
||||
$psql = Join-Path $PostgresBin 'psql.exe'
|
||||
|
||||
New-Item -ItemType Directory -Path $testRoot -Force | Out-Null
|
||||
|
||||
try {
|
||||
& $dropDb -h 127.0.0.1 -p $PostgresPort -U postgres --if-exists $Database
|
||||
if ($LASTEXITCODE -ne 0) { throw 'dropdb failed' }
|
||||
& $createDb -h 127.0.0.1 -p $PostgresPort -U postgres $Database
|
||||
if ($LASTEXITCODE -ne 0) { throw 'createdb failed' }
|
||||
|
||||
$smokePassword = [guid]::NewGuid().ToString('N')
|
||||
$env:GOTOOLCHAIN = 'go1.26.5'
|
||||
$env:BELL_DATABASE_URL = "host=127.0.0.1 port=$PostgresPort user=postgres dbname=$Database sslmode=disable"
|
||||
$env:BELL_JWT_SECRET = [guid]::NewGuid().ToString('N') + [guid]::NewGuid().ToString('N')
|
||||
$env:BELL_BOOTSTRAP_USERNAME = 'bell_smoke_admin'
|
||||
$env:BELL_BOOTSTRAP_PASSWORD = $smokePassword
|
||||
$env:BELL_HOST = '127.0.0.1'
|
||||
$env:BELL_PORT = $BellPort.ToString()
|
||||
|
||||
Push-Location $serverRoot
|
||||
try {
|
||||
go run . migrate -c config/settings.demo.yml *> (Join-Path $testRoot 'bell-migrate.log')
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell migration failed' }
|
||||
go build -o $serverExe .
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Bell server build failed' }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$serverProcess = Start-Process -FilePath $serverExe -ArgumentList @('server', '-c', 'config/settings.demo.yml') -WorkingDirectory $serverRoot -RedirectStandardOutput $stdout -RedirectStandardError $stderr -WindowStyle Hidden -PassThru
|
||||
$deadline = (Get-Date).AddSeconds(30)
|
||||
$health = $null
|
||||
do {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Uri "http://127.0.0.1:$BellPort/healthz" -TimeoutSec 2 -NoProxy
|
||||
break
|
||||
} catch {
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
if ($null -eq $health -or $health.service -ne 'bell') { throw 'Bell health check failed' }
|
||||
|
||||
$loginBody = @{ username = 'bell_smoke_admin'; password = $smokePassword; code = '0'; uuid = '0' } | ConvertTo-Json -Compress
|
||||
$login = Invoke-RestMethod -Method Post -Uri "http://127.0.0.1:$BellPort/api/v1/login" -ContentType 'application/json' -Body $loginBody -TimeoutSec 5 -NoProxy
|
||||
if ($login.code -ne 200 -or [string]::IsNullOrWhiteSpace($login.token)) { throw "Bell login failed with code $($login.code)" }
|
||||
|
||||
$headers = @{ Authorization = "Bearer $($login.token)" }
|
||||
$menus = Invoke-RestMethod -Uri "http://127.0.0.1:$BellPort/api/v1/menurole" -Headers $headers -TimeoutSec 5 -NoProxy
|
||||
if ($menus.code -ne 200) { throw "menu request failed with code $($menus.code)" }
|
||||
|
||||
$unauth = Invoke-WebRequest -Uri "http://127.0.0.1:$BellPort/api/v1/sys-user" -SkipHttpErrorCheck -TimeoutSec 5 -NoProxy
|
||||
$disabled = Invoke-WebRequest -Uri "http://127.0.0.1:$BellPort/api/v1/server-monitor" -Headers $headers -SkipHttpErrorCheck -TimeoutSec 5 -NoProxy
|
||||
$disabledAdmin = Invoke-WebRequest -Uri "http://127.0.0.1:$BellPort/api/v1/dept" -Headers $headers -SkipHttpErrorCheck -TimeoutSec 5 -NoProxy
|
||||
if ($unauth.Content -notmatch '401') { throw 'RBAC unauthenticated request was not rejected' }
|
||||
if ($disabled.StatusCode -ne 404) { throw "disabled route status was $($disabled.StatusCode)" }
|
||||
if ($disabledAdmin.StatusCode -ne 404) { throw "disabled admin route status was $($disabledAdmin.StatusCode)" }
|
||||
|
||||
$dbEvidence = & $psql -h 127.0.0.1 -p $PostgresPort -U postgres -d $Database -Atc "select count(*) from sys_migration; select count(*) from sys_user where username='bell_smoke_admin'; select count(*) from sys_menu where visible='0' and menu_id in (2,3,51,52); select count(*) from sys_menu where visible='1' and menu_id in (56,57,58,59,60,62,211,212,216,261,262,264,269,459,460,471,528,537,540);"
|
||||
Write-Output "SMOKE health=$($health.status) login=$($login.code) unauth_rejected=true disabled_routes=$($disabled.StatusCode)/$($disabledAdmin.StatusCode) db_evidence=$($dbEvidence -join ',')"
|
||||
} finally {
|
||||
if ($null -ne $serverProcess -and -not $serverProcess.HasExited) {
|
||||
Stop-Process -Id $serverProcess.Id -Force
|
||||
}
|
||||
Remove-Item Env:BELL_BOOTSTRAP_PASSWORD -ErrorAction SilentlyContinue
|
||||
Remove-Item Env:BELL_JWT_SECRET -ErrorAction SilentlyContinue
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: 🆕 Create new issue
|
||||
url: http://new-issue.go-admin.dev
|
||||
about: The issue which is not created via http://new-issue.go-admin.dev will be closed immediately.
|
||||
- name: 🆕 创建一个新 Issue
|
||||
url: http://new-issue.go-admin.dev
|
||||
about: 不是用 http://new-issue.go-admin.dev 创建的 issue 会被机器人自动关闭。
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<!--
|
||||
First of all, thank you for your contribution! 😄
|
||||
|
||||
For requesting to pull a new feature or bugfix, please send it from a feature/bugfix branch based on the `master` branch.
|
||||
|
||||
Before submitting your pull request, please make sure the checklist below is confirmed.
|
||||
|
||||
Your pull requests will be merged after one of the collaborators approve.
|
||||
|
||||
Thank you!
|
||||
|
||||
-->
|
||||
|
||||
[[中文版模板 / Chinese template](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE/pr_cn.md)]
|
||||
|
||||
### 🤔 This is a ...
|
||||
|
||||
- [ ] New feature
|
||||
- [ ] Bug fix
|
||||
- [ ] Site / documentation update
|
||||
- [ ] Demo update
|
||||
- [ ] Component style update
|
||||
- [ ] TypeScript definition update
|
||||
- [ ] Bundle size optimization
|
||||
- [ ] Performance optimization
|
||||
- [ ] Enhancement feature
|
||||
- [ ] Internationalization
|
||||
- [ ] Refactoring
|
||||
- [ ] Code style optimization
|
||||
- [ ] Test Case
|
||||
- [ ] Branch merge
|
||||
- [ ] Other (about what?)
|
||||
|
||||
### 🔗 Related issue link
|
||||
|
||||
<!--
|
||||
1. Put the related issue or discussion links here.
|
||||
-->
|
||||
|
||||
### 💡 Background and solution
|
||||
|
||||
<!--
|
||||
1. Describe the problem and the scenario.
|
||||
2. GIF or snapshot should be provided if includes UI/interactive modification.
|
||||
3. How to fix the problem, and list the final API implementation and usage sample if that is a new feature.
|
||||
-->
|
||||
|
||||
### 📝 Changelog
|
||||
|
||||
<!--
|
||||
Describe changes from the user side, and list all potential break changes or other risks.
|
||||
--->
|
||||
|
||||
| Language | Changelog |
|
||||
| ---------- | --------- |
|
||||
| 🇺🇸 English | |
|
||||
| 🇨🇳 Chinese | |
|
||||
|
||||
### ☑️ Self-Check before Merge
|
||||
|
||||
⚠️ Please check all items below before review. ⚠️
|
||||
|
||||
- [ ] Doc is updated/provided or not needed
|
||||
- [ ] Demo is updated/provided or not needed
|
||||
- [ ] TypeScript's definition is updated/provided or not needed
|
||||
- [ ] Changelog is provided or not needed
|
||||
@@ -0,0 +1,61 @@
|
||||
<!--
|
||||
首先,感谢你的贡献!😄
|
||||
|
||||
新特性请提交至 feature 分支,其余可提交至 master 分支。
|
||||
在维护者审核通过后会合并。
|
||||
请确保填写以下 pull request 的信息,谢谢!~
|
||||
-->
|
||||
|
||||
[[English Template / 英文模板](https://github.com/go-admin-team/go-admin/blob/master/.github/PULL_REQUEST_TEMPLATE.md)]
|
||||
|
||||
### 🤔 这个变动的性质是?
|
||||
|
||||
- [ ] 新特性提交
|
||||
- [ ] 日常 bug 修复
|
||||
- [ ] 站点、文档改进
|
||||
- [ ] 演示代码改进
|
||||
- [ ] 组件样式/交互改进
|
||||
- [ ] TypeScript 定义更新
|
||||
- [ ] 包体积优化
|
||||
- [ ] 性能优化
|
||||
- [ ] 功能增强
|
||||
- [ ] 国际化改进
|
||||
- [ ] 重构
|
||||
- [ ] 代码风格优化
|
||||
- [ ] 测试用例
|
||||
- [ ] 分支合并
|
||||
- [ ] 其他改动(是关于什么的改动?)
|
||||
|
||||
### 🔗 相关 Issue
|
||||
|
||||
<!--
|
||||
1. 描述相关需求的来源,如相关的 issue 讨论链接。
|
||||
-->
|
||||
|
||||
### 💡 需求背景和解决方案
|
||||
|
||||
<!--
|
||||
1. 要解决的具体问题。
|
||||
2. 列出最终的 API 实现和用法。
|
||||
3. 涉及UI/交互变动需要有截图或 GIF。
|
||||
-->
|
||||
|
||||
### 📝 更新日志
|
||||
|
||||
<!--
|
||||
从用户角度描述具体变化,以及可能的 breaking change 和其他风险。
|
||||
-->
|
||||
|
||||
| 语言 | 更新描述 |
|
||||
| ------- | -------- |
|
||||
| 🇺🇸 英文 | |
|
||||
| 🇨🇳 中文 | |
|
||||
|
||||
### ☑️ 请求合并前的自查清单
|
||||
|
||||
⚠️ 请自检并全部**勾选全部选项**。⚠️
|
||||
|
||||
- [ ] 文档已补充或无须补充
|
||||
- [ ] 代码演示已提供或无须提供
|
||||
- [ ] TypeScript 定义已补充或无须补充
|
||||
- [ ] Changelog 已提供或无须提供
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
env:
|
||||
IMAGE_NAME: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api # 镜像名称
|
||||
TAG: ${{ github.sha }}
|
||||
IMAGE_NAME_TAG: registry.ap-northeast-1.aliyuncs.com/go-admin/go-admin-api:${{ github.sha }}
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: 1.26.5
|
||||
|
||||
- name: Tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: Build
|
||||
run: env CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags "sqlite3,json1" --ldflags "-extldflags -static" -o main .
|
||||
|
||||
- name: Build the Docker image and push
|
||||
run: |
|
||||
docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
|
||||
echo "************ docker login end"
|
||||
docker build -t go-admin-api:latest .
|
||||
echo "************ docker build end"
|
||||
docker tag go-admin-api ${{ env.IMAGE_NAME_TAG }}
|
||||
echo "************ docker tag end"
|
||||
docker images
|
||||
echo "************ docker images end"
|
||||
docker push ${{ env.IMAGE_NAME_TAG }} # 推送
|
||||
echo "************ docker push end"
|
||||
|
||||
- name: Restart server # 第五步,重启服务
|
||||
uses: appleboy/ssh-action@0ff4204d59e8e51228ff73bce53f80d53301dee2 # v1.2.5
|
||||
env:
|
||||
GITHUB_SHA_X: ${GITHUB_SHA}
|
||||
with:
|
||||
host: ${{ secrets.SSH_HOST }} # 下面三个配置与上一步类似
|
||||
username: ${{ secrets.SSH_USERNAME }}
|
||||
key: ${{ secrets.DEPLOY_KEY }}
|
||||
# 重启的脚本,根据自身情况做相应改动,一般要做的是migrate数据库以及重启服务器
|
||||
script: |
|
||||
sudo docker rm -f go-admin-api
|
||||
sudo docker login --username=${{ secrets.DOCKER_USERNAME }} registry.ap-northeast-1.aliyuncs.com --password=${{ secrets.DOCKER_PASSWORD }}
|
||||
sudo docker run -d -p 8000:8000 --name go-admin-api ${{ env.IMAGE_NAME_TAG }}
|
||||
@@ -0,0 +1,51 @@
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'go' ]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@24c7eb380a2dc368f2d129e4c65e51d172983a1e # v4
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
name: build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, dev ]
|
||||
tags: [ 'v*', '[0-9]*' ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.26
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: 1.26.5
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Get dependencies
|
||||
run: go mod tidy
|
||||
- name: Build
|
||||
run: make build
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
flavor: |
|
||||
latest=auto
|
||||
tags: |
|
||||
type=schedule
|
||||
type=ref,event=tag
|
||||
type=sha,prefix=,format=long,enable=true,priority=100
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
context: .
|
||||
file: scripts/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
name: 'GitHub Actions Mirror'
|
||||
|
||||
on: [push, delete]
|
||||
|
||||
jobs:
|
||||
mirror_to_gitee:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: 'Mirror to gitee'
|
||||
uses: pixta-dev/repository-mirroring-action@674e65a7d483ca28dafaacba0d07351bdcc8bd75 # v1
|
||||
with:
|
||||
target_repo_url:
|
||||
git@gitee.com:go-admin-team/go-admin.git
|
||||
ssh_private_key:
|
||||
${{ secrets.GITEE_KEY }}
|
||||
mirror_to_gitlab:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: 'Mirror to gitlab'
|
||||
uses: pixta-dev/repository-mirroring-action@674e65a7d483ca28dafaacba0d07351bdcc8bd75 # v1
|
||||
with:
|
||||
target_repo_url:
|
||||
git@gitlab.com:go-admin-team/go-admin.git
|
||||
ssh_private_key:
|
||||
${{ secrets.GITLAB_KEY }}
|
||||
@@ -0,0 +1,25 @@
|
||||
.idea
|
||||
.vscode
|
||||
*/.DS_Store
|
||||
static/uploadfile
|
||||
main.exe
|
||||
*.exe
|
||||
go-admin
|
||||
go-admin.exe
|
||||
temp/
|
||||
!temp
|
||||
vendor
|
||||
config/settings.dev.yml
|
||||
config/settings.dev.*.yml
|
||||
config/settings.dev.*.yml.log
|
||||
temp/logs
|
||||
config/settings.dev.yml.log
|
||||
config/settings.b.dev.yml
|
||||
cmd/migrate/migration/version-local/*
|
||||
!cmd/migrate/migration/version-local/doc.go
|
||||
|
||||
config/settings.deva.yml
|
||||
go-admin-server
|
||||
CLAUDE.md
|
||||
.claude/
|
||||
config/settings.local.dev.yml
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM alpine
|
||||
|
||||
# ENV GOPROXY https://goproxy.cn/
|
||||
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
|
||||
|
||||
RUN apk update --no-cache
|
||||
RUN apk add --update gcc g++ libc6-compat
|
||||
RUN apk add --no-cache ca-certificates
|
||||
RUN apk add --no-cache tzdata
|
||||
ENV TZ Asia/Shanghai
|
||||
|
||||
COPY ./main /main
|
||||
COPY ./config/settings.demo.yml /config/settings.yml
|
||||
COPY ./go-admin-db.db /go-admin-db.db
|
||||
EXPOSE 8000
|
||||
RUN chmod +x /main
|
||||
CMD ["/main","server","-c", "/config/settings.yml"]
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM golang:alpine as builder
|
||||
|
||||
MAINTAINER lwnmengjing
|
||||
|
||||
ENV GOPROXY https://goproxy.cn/
|
||||
|
||||
WORKDIR /go/release
|
||||
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
RUN apk update && apk add tzdata
|
||||
|
||||
COPY go.mod ./go.mod
|
||||
RUN go mod tidy
|
||||
COPY . .
|
||||
RUN pwd && ls
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -a -installsuffix cgo -o go-admin .
|
||||
|
||||
FROM alpine
|
||||
|
||||
COPY --from=builder /go/release/go-admin /
|
||||
|
||||
COPY --from=builder /go/release/config/settings.yml /config/settings.yml
|
||||
|
||||
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["/go-admin","server","-c", "/config/settings.yml"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 go-admin-team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,54 @@
|
||||
PROJECT:=go-admin
|
||||
|
||||
.PHONY: build
|
||||
build:
|
||||
CGO_ENABLED=0 go build -ldflags="-w -s" -a -installsuffix "" -o go-admin .
|
||||
|
||||
# make build-linux
|
||||
build-linux:
|
||||
@docker build -t go-admin:latest .
|
||||
@echo "build successful"
|
||||
|
||||
build-sqlite:
|
||||
go build -tags sqlite3 -ldflags="-w -s" -a -installsuffix -o go-admin .
|
||||
|
||||
# make run
|
||||
run:
|
||||
# delete go-admin-api container
|
||||
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
|
||||
|
||||
# 启动方法一 run go-admin-api container docker-compose 启动方式
|
||||
# 进入到项目根目录 执行 make run 命令
|
||||
@docker-compose up -d
|
||||
|
||||
# 启动方式二 docker run 这里注意-v挂载的宿主机的地址改为部署时的实际决对路径
|
||||
#@docker run --name=go-admin -p 8000:8000 -v /home/code/go/src/go-admin/go-admin/config:/go-admin-api/config -v /home/code/go/src/go-admin/go-admin-api/static:/go-admin/static -v /home/code/go/src/go-admin/go-admin/temp:/go-admin-api/temp -d --restart=always go-admin:latest
|
||||
|
||||
@echo "go-admin service is running..."
|
||||
|
||||
# delete Tag=<none> 的镜像
|
||||
@docker image prune -f
|
||||
@docker ps -a | grep "go-admin"
|
||||
|
||||
stop:
|
||||
# delete go-admin-api container
|
||||
@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker-compose down; fi
|
||||
#@if [ $(shell docker ps -aq --filter name=go-admin --filter publish=8000) ]; then docker rm -f go-admin; fi
|
||||
#@echo "go-admin stop success"
|
||||
|
||||
|
||||
#.PHONY: test
|
||||
#test:
|
||||
# go test -v ./... -cover
|
||||
|
||||
#.PHONY: docker
|
||||
#docker:
|
||||
# docker build . -t go-admin:latest
|
||||
|
||||
# make deploy
|
||||
deploy:
|
||||
|
||||
#@git checkout master
|
||||
#@git pull origin master
|
||||
make build-linux
|
||||
make run
|
||||
@@ -0,0 +1,355 @@
|
||||
# go-admin
|
||||
|
||||
<img align="right" width="320" src="https://doc-image.zhangwj.com/img/go-admin.svg">
|
||||
|
||||
|
||||
[](https://github.com/go-admin-team/go-admin)
|
||||
[](https://github.com/go-admin-team/go-admin/releases)
|
||||
[](https://github.com/go-admin-team/go-admin)
|
||||
|
||||
[English](https://github.com/go-admin-team/go-admin/blob/master/README.md) | 简体中文
|
||||
|
||||
基于Gin + Vue + Element UI OR Arco Design OR Ant Design的前后端分离权限管理系统,系统初始化极度简单,只需要配置文件中,修改数据库连接,系统支持多指令操作,迁移指令可以让初始化数据库信息变得更简单,服务指令可以很简单的启动api服务
|
||||
|
||||
[在线文档](https://www.go-admin.pro)
|
||||
|
||||
[前端项目](https://github.com/go-admin-team/go-admin-ui)
|
||||
|
||||
[视频教程](https://space.bilibili.com/565616721/channel/detail?cid=125737)
|
||||
|
||||
## 🎬 在线体验
|
||||
|
||||
Element UI vue体验:[https://vue2.go-admin.dev](https://vue2.go-admin.dev/#/login)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
|
||||
Arco Design vue3 demo:[https://vue3.go-admin.dev](https://vue3.go-admin.dev/#/login)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
|
||||
antd体验:[https://antd.go-admin.pro](https://antd.go-admin.pro/)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
- 遵循 RESTful API 设计规范
|
||||
|
||||
- 基于 GIN WEB API 框架,提供了丰富的中间件支持(用户认证、跨域、访问日志、追踪ID等)
|
||||
|
||||
- 基于Casbin的 RBAC 访问控制模型
|
||||
|
||||
- JWT 认证
|
||||
|
||||
- 支持 Swagger 文档(基于swaggo)
|
||||
|
||||
- 基于 GORM 的数据库存储,可扩展多种类型数据库
|
||||
|
||||
- 配置文件简单的模型映射,快速能够得到想要的配置
|
||||
|
||||
- 代码生成工具
|
||||
|
||||
- 表单构建工具
|
||||
|
||||
- 多指令模式
|
||||
|
||||
- 多租户的支持
|
||||
|
||||
- TODO: 单元测试
|
||||
|
||||
## 🎁 内置
|
||||
|
||||
1. 多租户:系统默认支持多租户,按库分离,一个库一个租户。
|
||||
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
|
||||
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
|
||||
3. 岗位管理:配置系统用户所属担任职务。
|
||||
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识,接口权限等。
|
||||
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
|
||||
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
|
||||
7. 参数管理:对系统动态配置常用参数。
|
||||
8. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
|
||||
9. 登录日志:系统登录日志记录查询包含登录异常。
|
||||
1. 接口文档:根据业务代码自动生成相关的api接口文档。
|
||||
1. 代码生成:根据数据表结构生成对应的增删改查相对应业务,全程可视化操作,让基本业务可以零代码实现。
|
||||
1. 表单构建:自定义页面样式,拖拉拽实现页面布局。
|
||||
1. 服务监控:查看一些服务器的基本信息。
|
||||
1. 内容管理:demo功能,下设分类管理、内容管理。可以参考使用方便快速入门。
|
||||
1. 定时任务:自动化任务,目前支持接口调用和函数调用。
|
||||
|
||||
## 准备工作
|
||||
|
||||
你需要在本地安装 [go] [gin] [node](http://nodejs.org/) 和 [git](https://git-scm.com/)
|
||||
|
||||
同时配套了系列教程包含视频和文档,如何从下载完成到熟练使用,强烈建议大家先看完这些教程再来实践本项目!!!
|
||||
|
||||
### 轻松实现go-admin写出第一个应用 - 文档教程
|
||||
|
||||
[步骤一 - 基础内容介绍](https://doc.zhangwj.com/guide/intro/tutorial01.html)
|
||||
|
||||
[步骤二 - 实际应用 - 编写增删改查](https://doc.zhangwj.com/guide/intro/tutorial02.html)
|
||||
|
||||
### 手把手教你从入门到放弃 - 视频教程
|
||||
|
||||
[如何启动go-admin](https://www.bilibili.com/video/BV1z5411x7JG)
|
||||
|
||||
[使用生成工具轻松实现业务](https://www.bilibili.com/video/BV1Dg4y1i79D)
|
||||
|
||||
[v1.1.0版本代码生成工具-释放双手](https://www.bilibili.com/video/BV1N54y1i71P) [进阶]
|
||||
|
||||
[多命令启动方式讲解以及IDE配置](https://www.bilibili.com/video/BV1Fg4y1q7ph)
|
||||
|
||||
[go-admin菜单的配置说明](https://www.bilibili.com/video/BV1Wp4y1D715) [必看]
|
||||
|
||||
[如何配置菜单信息以及接口信息](https://www.bilibili.com/video/BV1zv411B7nG) [必看]
|
||||
|
||||
[go-admin权限配置使用说明](https://www.bilibili.com/video/BV1rt4y197d3) [必看]
|
||||
|
||||
[go-admin数据权限使用说明](https://www.bilibili.com/video/BV1LK4y1s71e) [必看]
|
||||
|
||||
**如有问题请先看上述使用文档和文章,若不能满足,欢迎 issue 和 pr ,视频教程和文档持续更新中**
|
||||
|
||||
## 📦 本地开发
|
||||
|
||||
### 环境要求
|
||||
|
||||
go 1.26.5
|
||||
|
||||
node版本: v22+(推荐 v24 LTS)
|
||||
|
||||
包管理器: pnpm v9+(UI 项目使用 pnpm)
|
||||
|
||||
### 开发目录创建
|
||||
|
||||
```bash
|
||||
|
||||
# 创建开发目录
|
||||
mkdir goadmin
|
||||
cd goadmin
|
||||
```
|
||||
|
||||
### 获取代码
|
||||
|
||||
> 重点注意:两个项目必须放在同一文件夹下;
|
||||
|
||||
```bash
|
||||
# 获取后端代码
|
||||
git clone https://github.com/go-admin-team/go-admin.git
|
||||
|
||||
# 获取前端代码
|
||||
git clone https://github.com/go-admin-team/go-admin-ui.git
|
||||
|
||||
```
|
||||
|
||||
### 启动说明
|
||||
|
||||
#### 服务端启动说明
|
||||
|
||||
```bash
|
||||
# 进入 go-admin 后端项目
|
||||
cd ./go-admin
|
||||
|
||||
# 更新整理依赖
|
||||
go mod tidy
|
||||
|
||||
# 编译项目
|
||||
go build
|
||||
|
||||
# 修改配置
|
||||
# 文件路径 go-admin/config/settings.yml
|
||||
vi ./config/settings.yml
|
||||
|
||||
# 1. 配置文件中修改数据库信息
|
||||
# 注意: settings.database 下对应的配置数据
|
||||
# 2. 确认log路径
|
||||
```
|
||||
|
||||
⚠️注意 在windows环境如果没有安装中CGO,会出现这个问题;
|
||||
|
||||
```bash
|
||||
E:\go-admin>go build
|
||||
# github.com/mattn/go-sqlite3
|
||||
cgo: exec /missing-cc: exec: "/missing-cc": file does not exist
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
D:\Code\go-admin>go build
|
||||
# github.com/mattn/go-sqlite3
|
||||
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
|
||||
```
|
||||
|
||||
[解决cgo问题进入](https://doc.go-admin.dev/zh-CN/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
|
||||
|
||||
|
||||
#### 初始化数据库,以及服务启动
|
||||
|
||||
``` bash
|
||||
# 首次配置需要初始化数据库资源信息
|
||||
# macOS or linux 下使用
|
||||
$ ./go-admin migrate -c config/settings.dev.yml
|
||||
|
||||
# ⚠️注意:windows 下使用
|
||||
$ go-admin.exe migrate -c config/settings.dev.yml
|
||||
|
||||
|
||||
# 启动项目,也可以用IDE进行调试
|
||||
# macOS or linux 下使用
|
||||
$ ./go-admin server -c config/settings.yml
|
||||
|
||||
|
||||
# ⚠️注意:windows 下使用
|
||||
$ go-admin.exe server -c config/settings.yml
|
||||
```
|
||||
|
||||
#### sys_api 表的数据如何添加
|
||||
|
||||
在项目启动时,使用`-a true` 系统会自动添加缺少的接口数据
|
||||
```bash
|
||||
./go-admin server -c config/settings.yml -a true
|
||||
```
|
||||
|
||||
#### 使用docker 编译启动
|
||||
|
||||
```shell
|
||||
# 编译镜像
|
||||
docker build -t go-admin .
|
||||
|
||||
# 启动容器,第一个go-admin是容器名字,第二个go-admin是镜像名称
|
||||
# -v 映射配置文件 本地路径:容器路径
|
||||
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
|
||||
```
|
||||
|
||||
#### 文档生成
|
||||
|
||||
```bash
|
||||
go generate
|
||||
```
|
||||
|
||||
#### 交叉编译
|
||||
|
||||
```bash
|
||||
# windows
|
||||
env GOOS=windows GOARCH=amd64 go build main.go
|
||||
|
||||
# or
|
||||
# linux
|
||||
env GOOS=linux GOARCH=amd64 go build main.go
|
||||
```
|
||||
|
||||
### UI交互端启动说明
|
||||
|
||||
```bash
|
||||
# 安装 pnpm(若未安装)
|
||||
npm install -g pnpm
|
||||
|
||||
# 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 国内网络可指定镜像源加速
|
||||
pnpm install --registry=https://registry.npmmirror.com
|
||||
|
||||
# 启动服务
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 📨 互动
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
|
||||
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
|
||||
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
|
||||
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>微信</td>
|
||||
<td>公众号🔥🔥🔥</td>
|
||||
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
|
||||
<td>哔哩哔哩🔥🔥🔥</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 💎 贡献者
|
||||
|
||||
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
|
||||
## JetBrains 开源证书支持
|
||||
|
||||
`go-admin` 项目一直以来都是在 JetBrains 公司旗下的 GoLand 集成开发环境中进行开发,基于 **free JetBrains Open Source license(s)** 正版免费授权,在此表达我的谢意。
|
||||
|
||||
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
|
||||
|
||||
## 🤝 特别感谢
|
||||
|
||||
1. [ant-design](https://github.com/ant-design/ant-design)
|
||||
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
|
||||
2. [arco-design](https://github.com/arco-design/arco-design)
|
||||
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
|
||||
4. [gin](https://github.com/gin-gonic/gin)
|
||||
5. [casbin](https://github.com/casbin/casbin)
|
||||
6. [spf13/viper](https://github.com/spf13/viper)
|
||||
7. [gorm](https://github.com/jinzhu/gorm)
|
||||
8. [gin-swagger](https://github.com/swaggo/gin-swagger)
|
||||
9. [jwt-go](https://github.com/dgrijalva/jwt-go)
|
||||
10. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
|
||||
11. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
|
||||
12. [form-generator](https://github.com/JakHuang/form-generator)
|
||||
|
||||
|
||||
## 🤟 打赏
|
||||
|
||||
> 如果你觉得这个项目帮助到了你,你可以帮作者买一杯果汁表示鼓励 :tropical_drink:
|
||||
|
||||
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
|
||||
|
||||
## 🤝 链接
|
||||
|
||||
[Go开发者成长线路图](http://www.golangroadmap.com/)
|
||||
|
||||
## 🔑 License
|
||||
|
||||
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
|
||||
|
||||
Copyright (c) 2024 wenjianzhang
|
||||
@@ -0,0 +1,345 @@
|
||||
|
||||
# go-admin
|
||||
|
||||
<img align="right" width="320" src="https://raw.githubusercontent.com/wenjianzhang/image/203c5930b9ed08d5cf2fcb4516b85e412f8e0e60/img/go-admin.svg">
|
||||
|
||||
|
||||
[](https://github.com/go-admin-team/go-admin)
|
||||
[](https://github.com/go-admin-team/go-admin/releases)
|
||||
[](https://github.com/go-admin-team/go-admin)
|
||||
|
||||
English | [简体中文](https://github.com/go-admin-team/go-admin/blob/master/README.Zh-cn.md)
|
||||
|
||||
The front-end and back-end separation authority management system based on Gin + Vue + Element UI OR Arco Design is extremely simple to initialize the system. You only need to modify the database connection in the configuration file. The system supports multi-instruction operations. Migration instructions can make it easier to initialize database information. Service instructions It's easy to start the api service.
|
||||
|
||||
[documentation](https://www.go-admin.dev)
|
||||
|
||||
[Front-end project](https://github.com/go-admin-team/go-admin-ui)
|
||||
|
||||
[Video tutorial](https://space.bilibili.com/565616721/channel/detail?cid=125737)
|
||||
|
||||
## 🎬 Online Demo
|
||||
|
||||
Element UI vue demo:[https://vue2.go-admin.dev](https://vue2.go-admin.dev/#/login)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
|
||||
Arco Design vue3 demo:[https://vue3.go-admin.dev](https://vue3.go-admin.dev/#/login)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
|
||||
antd demo:[https://antd.go-admin.pro](https://antd.go-admin.pro/)
|
||||
> 上游在线演示凭据不属于 Bell,已移除。
|
||||
>
|
||||
## ✨ Feature
|
||||
|
||||
- Follow RESTful API design specifications
|
||||
|
||||
- Based on the GIN WEB API framework, it provides rich middleware support (user authentication, cross-domain, access log, tracking ID, etc.)
|
||||
|
||||
- RBAC access control model based on Casbin
|
||||
|
||||
- JWT authentication
|
||||
|
||||
- Support Swagger documents (based on swaggo)
|
||||
|
||||
- Database storage based on GORM, which can expand multiple types of databases
|
||||
|
||||
- Simple model mapping of configuration files to quickly get the desired configuration
|
||||
|
||||
- Code generation tool
|
||||
|
||||
- Form builder
|
||||
|
||||
- Multi-command mode
|
||||
|
||||
- TODO: unit test
|
||||
|
||||
|
||||
## 🎁 Internal
|
||||
|
||||
1. User management: The user is the system operator, this function mainly completes the system user configuration.
|
||||
2. Department management: configure the system organization (company, department, group), and display the tree structure to support data permissions.
|
||||
3. Position management: configure the positions of system users.
|
||||
4. Menu management: configure the system menu, operation authority, button authority identification, interface authority, etc.
|
||||
5. Role management: Role menu permission assignment and role setting are divided into data scope permissions by organization.
|
||||
6. Dictionary management: Maintain some relatively fixed data frequently used in the system.
|
||||
7. Parameter management: dynamically configure common parameters for the system.
|
||||
8. Operation log: system normal operation log record and query; system abnormal information log record and query.
|
||||
9. Login log: The system login log record query contains login exceptions.
|
||||
1. Interface documentation: Automatically generate related api interface documents according to the business code.
|
||||
1. Code generation: According to the data table structure, generate the corresponding addition, deletion, modification, and check corresponding business, and the whole process of visual operation, so that the basic business can be implemented with zero code.
|
||||
1. Form construction: Customize the page style, drag and drop to realize the page layout.
|
||||
1. Service monitoring: View the basic information of some servers.
|
||||
1. Content management: demo function, including classification management and content management. You can refer to the easy to use quick start.
|
||||
|
||||
## Ready to work
|
||||
|
||||
You need to install locally [go] [gin] [node](http://nodejs.org/) 和 [git](https://git-scm.com/)
|
||||
|
||||
At the same time, a series of tutorials including videos and documents are provided. How to complete the downloading to the proficient use, it is strongly recommended that you read these tutorials before you practice this project! ! !
|
||||
|
||||
### Easily implement go-admin to write the first application-documentation tutorial
|
||||
|
||||
[Step 1 - basic content introduction](https://doc.zhangwj.com/guide/intro/tutorial01.html)
|
||||
|
||||
[Step 2 - Practical application - writing database operations](https://doc.zhangwj.com/guide/intro/tutorial02.html)
|
||||
|
||||
### Teach you from getting started to giving up-video tutorial
|
||||
|
||||
[How to start go-admin](https://www.bilibili.com/video/BV1z5411x7JG)
|
||||
|
||||
[Easily implement business using build tools](https://www.bilibili.com/video/BV1Dg4y1i79D)
|
||||
|
||||
[v1.1.0 version code generation tool-free your hands](https://www.bilibili.com/video/BV1N54y1i71P) [Advanced]
|
||||
|
||||
[Explanation of multi-command startup mode and IDE configuration](https://www.bilibili.com/video/BV1Fg4y1q7ph)
|
||||
|
||||
[Configuration instructions for go-admin menu](https://www.bilibili.com/video/BV1Wp4y1D715) [Must see]
|
||||
|
||||
[How to configure menu information and interface information](https://www.bilibili.com/video/BV1zv411B7nG) [Must see]
|
||||
|
||||
[go-admin permission configuration instructions](https://www.bilibili.com/video/BV1rt4y197d3) [Must see]
|
||||
|
||||
[Instructions for use of go-admin data permissions](https://www.bilibili.com/video/BV1LK4y1s71e) [Must see]
|
||||
|
||||
**If you have any questions, please read the above-mentioned usage documents and articles first. If you are not satisfied, welcome to issue and pr. Video tutorials and documents are being updated continuously.**
|
||||
|
||||
## 📦 Local development
|
||||
|
||||
### Environmental requirements
|
||||
|
||||
go 1.26.5
|
||||
|
||||
nodejs: v22+ (v24 LTS recommended)
|
||||
|
||||
package manager: pnpm v9+ (the UI project uses pnpm)
|
||||
|
||||
### Development directory creation
|
||||
|
||||
```bash
|
||||
|
||||
# Create a development directory
|
||||
mkdir goadmin
|
||||
cd goadmin
|
||||
```
|
||||
|
||||
### Get the code
|
||||
|
||||
> Important note: the two projects must be placed in the same folder;
|
||||
|
||||
```bash
|
||||
# Get backend code
|
||||
git clone https://github.com/go-admin-team/go-admin.git
|
||||
|
||||
# Get the front-end code
|
||||
git clone https://github.com/go-admin-team/go-admin-ui.git
|
||||
|
||||
```
|
||||
|
||||
### Startup instructions
|
||||
|
||||
#### Server startup instructions
|
||||
|
||||
```bash
|
||||
# Enter the go-admin backend project
|
||||
cd ./go-admin
|
||||
|
||||
# Update dependencies
|
||||
go mod tidy
|
||||
|
||||
# Compile the project
|
||||
go build
|
||||
|
||||
# Change setting
|
||||
# File path go-admin/config/settings.yml
|
||||
vi ./config/settings.yml
|
||||
|
||||
# 1. Modify the database information in the configuration file
|
||||
# Note: The corresponding configuration data under settings.database
|
||||
# 2. Confirm the log path
|
||||
```
|
||||
|
||||
:::tip ⚠️Note that this problem will occur if CGO is not installed in the windows10+ environment;
|
||||
|
||||
```bash
|
||||
E:\go-admin>go build
|
||||
# github.com/mattn/go-sqlite3
|
||||
cgo: exec /missing-cc: exec: "/missing-cc": file does not exist
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
D:\Code\go-admin>go build
|
||||
# github.com/mattn/go-sqlite3
|
||||
cgo: exec gcc: exec: "gcc": executable file not found in %PATH%
|
||||
```
|
||||
|
||||
[Solve the cgo problem and enter](https://doc.go-admin.dev/guide/faq#cgo-%E7%9A%84%E9%97%AE%E9%A2%98)
|
||||
|
||||
:::
|
||||
|
||||
#### Initialize the database, and start the service
|
||||
|
||||
``` bash
|
||||
# The first configuration needs to initialize the database resource information
|
||||
# Use under macOS or linux
|
||||
$ ./go-admin migrate -c config/settings.dev.yml
|
||||
|
||||
# ⚠️Note: Use under windows
|
||||
$ go-admin.exe migrate -c config/settings.dev.yml
|
||||
|
||||
# Start the project, you can also use the IDE for debugging
|
||||
# Use under macOS or linux
|
||||
$ ./go-admin server -c config/settings.yml
|
||||
|
||||
# ⚠️Note: Use under windows
|
||||
$ go-admin.exe server -c config/settings.yml
|
||||
```
|
||||
|
||||
#### Use docker to compile and start
|
||||
|
||||
```shell
|
||||
# Compile the image
|
||||
docker build -t go-admin .
|
||||
|
||||
|
||||
# Start the container, the first go-admin is the container name, and the second go-admin is the image name
|
||||
# -v Mapping configuration file Local path: container path
|
||||
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Generation Document
|
||||
|
||||
```bash
|
||||
go generate
|
||||
```
|
||||
|
||||
#### Cross compile
|
||||
```bash
|
||||
# windows
|
||||
env GOOS=windows GOARCH=amd64 go build main.go
|
||||
|
||||
# or
|
||||
# linux
|
||||
env GOOS=linux GOARCH=amd64 go build main.go
|
||||
```
|
||||
|
||||
### UI interactive terminal startup instructions
|
||||
|
||||
```bash
|
||||
# Install pnpm if you don't have it
|
||||
npm install -g pnpm
|
||||
|
||||
# Installation dependencies
|
||||
pnpm install
|
||||
|
||||
# Start service
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 📨 Interactive
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
|
||||
<td><img src="https://doc-image.zhangwj.com/img/qrcode_for_gh_b798dc7db30c_258.jpg" width="180px"></td>
|
||||
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
|
||||
<td><a href="https://space.bilibili.com/565616721">wenjianzhang</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Wechat</td>
|
||||
<td>Wechat公众号🔥🔥🔥</td>
|
||||
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
|
||||
<td>bilibili🔥🔥🔥</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 💎 Contributors
|
||||
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wenjianzhang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3890175?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/G-Akiraka" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45746659?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/lwnmengjing" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/12806223?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/bing127" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31166183?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/chengxiao" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1379545?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/NightFire0307" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19854086?v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/appleboy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/21979?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/ninstein" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/580303?v=4&h=60&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/kikiyou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17959053?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/horizonzy" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/22524871?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Cassuis" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/48005724?s=64&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/hqcchina" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/5179057?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/nodece" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16235121?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/stephenzhang0713" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/18169290?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zhouxixi-dev" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/100399679?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Jalins" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/31172582?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wkf928592" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6063351?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wxxiong6" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/6983441?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Silicon-He" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/52478309?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/GizmoOAO" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20385106?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/bestgopher" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/36840497?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/wxb1207" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/20775558?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/misakichan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/16569274?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zhuxuyang" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/19301024?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/mss-boot" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/109259065?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/AuroraV" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/37330199?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Vingurzhou" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/57127283?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/haimait" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40926384?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/zyd" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3446278?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/infnan" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38274826?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/d1y" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/45585937?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/qlijin" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/515900?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/logtous
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/88697234?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/stepway
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9927079?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/NaturalGao
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/43291304?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/DemoLiang
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/23476007?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/jfcg
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1410597?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
<span style="margin: 0 5px;" ><a href="https://github.com/Nicole0724
|
||||
" ><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/10487328?s=60&v=4&w=60&fit=cover&mask=circle&maxage=7d" /></a></span>
|
||||
|
||||
|
||||
|
||||
## JetBrains open source certificate support
|
||||
|
||||
The `go-admin` project has always been developed in the GoLand integrated development environment under JetBrains, based on the **free JetBrains Open Source license(s)** genuine free license. I would like to express my gratitude.
|
||||
|
||||
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
|
||||
|
||||
|
||||
## 🤝 Thanks
|
||||
|
||||
1. [ant-design](https://github.com/ant-design/ant-design)
|
||||
2. [ant-design-pro](https://github.com/ant-design/ant-design-pro)
|
||||
2. [arco-design](https://github.com/arco-design/arco-design)
|
||||
2. [arco-design-pro](https://github.com/arco-design/arco-design-pro)
|
||||
2. [gin](https://github.com/gin-gonic/gin)
|
||||
2. [casbin](https://github.com/casbin/casbin)
|
||||
2. [spf13/viper](https://github.com/spf13/viper)
|
||||
2. [gorm](https://github.com/jinzhu/gorm)
|
||||
2. [gin-swagger](https://github.com/swaggo/gin-swagger)
|
||||
2. [jwt-go](https://github.com/dgrijalva/jwt-go)
|
||||
2. [vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)
|
||||
2. [ruoyi-vue](https://gitee.com/y_project/RuoYi-Vue)
|
||||
2. [form-generator](https://github.com/JakHuang/form-generator)
|
||||
|
||||
## 🤟 Sponsor Us
|
||||
|
||||
> If you think this project helped you, you can buy a glass of juice for the author to show encouragement :tropical_drink:
|
||||
|
||||
<img class="no-margin" src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/pay.png" height="200px" >
|
||||
|
||||
## 🤝 Link
|
||||
- [Go developer growth roadmap](http://www.golangroadmap.com/)
|
||||
- [mss-boot-io](https://docs.mss-boot-io.top/)
|
||||
|
||||
## 🔑 License
|
||||
|
||||
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
|
||||
|
||||
Copyright (c) 2022 wenjianzhang
|
||||
@@ -0,0 +1 @@
|
||||
theme: jekyll-theme-cayman
|
||||
@@ -0,0 +1,36 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/captcha"
|
||||
)
|
||||
|
||||
type System struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GenerateCaptchaHandler 获取验证码
|
||||
// @Summary 获取验证码
|
||||
// @Description 获取验证码
|
||||
// @Tags 登陆
|
||||
// @Success 200 {object} response.Response{data=string,id=string,msg=string} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/captcha [get]
|
||||
func (e System) GenerateCaptchaHandler(c *gin.Context) {
|
||||
if err := e.MakeContext(c).Errors; err != nil {
|
||||
e.Error(500, err, "服务初始化失败!")
|
||||
return
|
||||
}
|
||||
id, b64s, _, err := captcha.DriverDigitFunc()
|
||||
if err != nil {
|
||||
e.Logger.Errorf("DriverDigitFunc error, %s", err.Error())
|
||||
e.Error(500, err, "验证码获取失败")
|
||||
return
|
||||
}
|
||||
e.Custom(gin.H{
|
||||
"code": 200,
|
||||
"data": b64s,
|
||||
"id": id,
|
||||
"msg": "success",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const INDEX = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>GO-ADMIN欢迎您</title>
|
||||
<style>
|
||||
body{
|
||||
margin:0;
|
||||
padding:0;
|
||||
overflow-y:hidden
|
||||
}
|
||||
</style>
|
||||
<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
|
||||
<script type="text/javascript">
|
||||
window.onerror=function(){return true;}
|
||||
$(function(){
|
||||
headerH = 0;
|
||||
var h=$(window).height();
|
||||
$("#iframe").height((h-headerH)+"px");
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<iframe id="iframe" frameborder="0" src="https://www.go-admin.pro" style="width:100%;"></iframe>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
func GoAdmin(c *gin.Context) {
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.String(200, INDEX)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
)
|
||||
|
||||
type SysApi struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 获取接口管理列表
|
||||
// @Summary 获取接口管理列表
|
||||
// @Description 获取接口管理列表
|
||||
// @Tags 接口管理
|
||||
// @Param name query string false "名称"
|
||||
// @Param title query string false "标题"
|
||||
// @Param path query string false "地址"
|
||||
// @Param action query string false "类型"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} response.Response{data=response.Page{list=[]models.SysApi}} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-api [get]
|
||||
// @Security Bearer
|
||||
func (e SysApi) GetPage(c *gin.Context) {
|
||||
s := service.SysApi{}
|
||||
req := dto.SysApiGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
list := make([]models.SysApi, 0)
|
||||
var count int64
|
||||
err = s.GetPage(&req, p, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get 获取接口管理
|
||||
// @Summary 获取接口管理
|
||||
// @Description 获取接口管理
|
||||
// @Tags 接口管理
|
||||
// @Param id path string false "id"
|
||||
// @Success 200 {object} response.Response{data=models.SysApi} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-api/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysApi) Get(c *gin.Context) {
|
||||
req := dto.SysApiGetReq{}
|
||||
s := service.SysApi{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
var object models.SysApi
|
||||
err = s.Get(&req, p, &object).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Update 修改接口管理
|
||||
// @Summary 修改接口管理
|
||||
// @Description 修改接口管理
|
||||
// @Tags 接口管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysApiUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
|
||||
// @Router /api/v1/sys-api/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysApi) Update(c *gin.Context) {
|
||||
req := dto.SysApiUpdateReq{}
|
||||
s := service.SysApi{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
err = s.Update(&req, p)
|
||||
if err != nil {
|
||||
e.Error(500, err, "更新失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// DeleteSysApi 删除接口管理
|
||||
// @Summary 删除接口管理
|
||||
// @Description 删除接口管理
|
||||
// @Tags 接口管理
|
||||
// @Param data body dto.SysApiDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
|
||||
// @Router /api/v1/sys-api [delete]
|
||||
// @Security Bearer
|
||||
func (e SysApi) DeleteSysApi(c *gin.Context) {
|
||||
req := dto.SysApiDeleteReq{}
|
||||
s := service.SysApi{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
err = s.Remove(&req, p)
|
||||
if err != nil {
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 获取配置管理列表
|
||||
// @Summary 获取配置管理列表
|
||||
// @Description 获取配置管理列表
|
||||
// @Tags 配置管理
|
||||
// @Param configName query string false "名称"
|
||||
// @Param configKey query string false "key"
|
||||
// @Param configType query string false "类型"
|
||||
// @Param isFrontend query int false "是否前端"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} response.Response{data=response.Page{list=[]models.SysApi}} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-config [get]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) GetPage(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := dto.SysConfigGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]models.SysConfig, 0)
|
||||
var count int64
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get 获取配置管理
|
||||
// @Summary 获取配置管理
|
||||
// @Description 获取配置管理
|
||||
// @Tags 配置管理
|
||||
// @Param id path string false "id"
|
||||
// @Success 200 {object} response.Response{data=models.SysConfig} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-config/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Get(c *gin.Context) {
|
||||
req := dto.SysConfigGetReq{}
|
||||
s := service.SysConfig{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysConfig
|
||||
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert 创建配置管理
|
||||
// @Summary 创建配置管理
|
||||
// @Description 创建配置管理
|
||||
// @Tags 配置管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysConfigControl true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "创建成功"}"
|
||||
// @Router /api/v1/sys-config [post]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Insert(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := dto.SysConfigControl{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "创建失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update 修改配置管理
|
||||
// @Summary 修改配置管理
|
||||
// @Description 修改配置管理
|
||||
// @Tags 配置管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysConfigControl true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
|
||||
// @Router /api/v1/sys-config/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Update(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := dto.SysConfigControl{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Update(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "更新失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete 删除配置管理
|
||||
// @Summary 删除配置管理
|
||||
// @Description 删除配置管理
|
||||
// @Tags 配置管理
|
||||
// @Param ids body []int false "ids"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
|
||||
// @Router /api/v1/sys-config [delete]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Delete(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := dto.SysConfigDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// Get2SysApp 获取系统配置信息
|
||||
// @Summary 获取系统前台配置信息,主要注意这里不在验证权限
|
||||
// @Description 获取系统配置信息,主要注意这里不在验证权限
|
||||
// @Tags 配置管理
|
||||
// @Success 200 {object} response.Response{data=map[string]string} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/app-config [get]
|
||||
func (e SysConfig) Get2SysApp(c *gin.Context) {
|
||||
req := dto.SysConfigGetToSysAppReq{}
|
||||
s := service.SysConfig{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
// 控制只读前台的数据
|
||||
req.IsFrontend = "1"
|
||||
list := make([]models.SysConfig, 0)
|
||||
err = s.GetWithKeyList(&req, &list)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
mp := make(map[string]string)
|
||||
for i := 0; i < len(list); i++ {
|
||||
key := list[i].ConfigKey
|
||||
if key != "" {
|
||||
mp[key] = list[i].ConfigValue
|
||||
}
|
||||
}
|
||||
e.OK(mp, "查询成功")
|
||||
}
|
||||
|
||||
// Get2Set 获取配置
|
||||
// @Summary 获取配置
|
||||
// @Description 界面操作设置配置值的获取
|
||||
// @Tags 配置管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Success 200 {object} response.Response{data=map[string]interface{}} "{"code": 200, "message": "修改成功"}"
|
||||
// @Router /api/v1/set-config [get]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Get2Set(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := make([]dto.GetSetSysConfigReq, 0)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
err = s.GetForSet(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
m := make(map[string]interface{}, 0)
|
||||
for _, v := range req {
|
||||
m[v.ConfigKey] = v.ConfigValue
|
||||
}
|
||||
e.OK(m, "查询成功")
|
||||
}
|
||||
|
||||
// Update2Set 设置配置
|
||||
// @Summary 设置配置
|
||||
// @Description 界面操作设置配置值
|
||||
// @Tags 配置管理
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body []dto.GetSetSysConfigReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
|
||||
// @Router /api/v1/set-config [put]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) Update2Set(c *gin.Context) {
|
||||
s := service.SysConfig{}
|
||||
req := make([]dto.GetSetSysConfigReq, 0)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = s.UpdateForSet(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e.OK("", "更新成功")
|
||||
}
|
||||
|
||||
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
|
||||
// @Summary 根据Key获取SysConfig的Service
|
||||
// @Description 根据Key获取SysConfig的Service
|
||||
// @Tags 配置管理
|
||||
// @Param configKey path string false "configKey"
|
||||
// @Success 200 {object} response.Response{data=dto.SysConfigByKeyReq} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-config/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
|
||||
var s = new(service.SysConfig)
|
||||
var req = new(dto.SysConfigByKeyReq)
|
||||
var resp = new(dto.GetSysConfigByKEYForServiceResp)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = s.GetWithKey(req, resp)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
e.OK(resp, s.Msg)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysDept struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage
|
||||
// @Summary 分页部门列表数据
|
||||
// @Description 分页列表
|
||||
// @Tags 部门
|
||||
// @Param deptName query string false "deptName"
|
||||
// @Param deptId query string false "deptId"
|
||||
// @Param position query string false "position"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dept [get]
|
||||
// @Security Bearer
|
||||
func (e SysDept) GetPage(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]models.SysDept, 0)
|
||||
list, err = s.SetDeptPage(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(list, "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 获取部门数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 部门
|
||||
// @Param deptId path string false "deptId"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dept/{deptId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysDept) Get(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysDept
|
||||
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert 添加部门
|
||||
// @Summary 添加部门
|
||||
// @Description 获取JSON
|
||||
// @Tags 部门
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysDeptInsertReq true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/dept [post]
|
||||
// @Security Bearer
|
||||
func (e SysDept) Insert(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 设置创建人
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "创建失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改部门
|
||||
// @Description 获取JSON
|
||||
// @Tags 部门
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param id path int true "id"
|
||||
// @Param data body dto.SysDeptUpdateReq true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/dept/{deptId} [put]
|
||||
// @Security Bearer
|
||||
func (e SysDept) Update(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Update(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除部门
|
||||
// @Description 删除数据
|
||||
// @Tags 部门
|
||||
// @Param data body dto.SysDeptDeleteReq true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/dept [delete]
|
||||
// @Security Bearer
|
||||
func (e SysDept) Delete(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// Get2Tree 用户管理 左侧部门树
|
||||
func (e SysDept) Get2Tree(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
req := dto.SysDeptGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]dto.DeptLabel, 0)
|
||||
list, err = s.SetDeptTree(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(list, "")
|
||||
}
|
||||
|
||||
// GetDeptTreeRoleSelect TODO: 此接口需要调整不应该将list和选中放在一起
|
||||
func (e SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
|
||||
s := service.SysDept{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
id, err := pkg.StringToInt(c.Param("roleId"))
|
||||
result, err := s.SetDeptLabel()
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
menuIds := make([]int, 0)
|
||||
if id != 0 {
|
||||
menuIds, err = s.GetWithRoleId(id)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
e.OK(gin.H{
|
||||
"depts": result,
|
||||
"checkedKeys": menuIds,
|
||||
}, "")
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysDictData struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage
|
||||
// @Summary 字典数据列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典数据
|
||||
// @Param status query string false "status"
|
||||
// @Param dictCode query string false "dictCode"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/data [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) GetPage(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]models.SysDictData, 0)
|
||||
var count int64
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 通过编码获取字典数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典数据
|
||||
// @Param dictCode path int true "字典编码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/data/{dictCode} [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) Get(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var object models.SysDictData
|
||||
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Logger.Warnf("Get error: %s", err.Error())
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert
|
||||
// @Summary 添加字典数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典数据
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysDictDataInsertReq true "data"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "添加成功"}"
|
||||
// @Router /api/v1/dict/data [post]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) Insert(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改字典数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典数据
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysDictDataUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "修改成功"}"
|
||||
// @Router /api/v1/dict/data/{dictCode} [put]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) Update(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Update(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "更新失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除字典数据
|
||||
// @Description 删除数据
|
||||
// @Tags 字典数据
|
||||
// @Param dictCode body dto.SysDictDataDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "message": "删除成功"}"
|
||||
// @Router /api/v1/dict/data [delete]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) Delete(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// GetAll 数据字典根据key获取 业务页面使用
|
||||
// @Summary 数据字典根据key获取
|
||||
// @Description 数据字典根据key获取
|
||||
// @Tags 字典数据
|
||||
// @Param dictType query int true "dictType"
|
||||
// @Success 200 {object} response.Response{data=[]dto.SysDictDataGetAllResp} "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict-data/option-select [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictData) GetAll(c *gin.Context) {
|
||||
s := service.SysDictData{}
|
||||
req := dto.SysDictDataGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]models.SysDictData, 0)
|
||||
err = s.GetAll(&req, &list)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
l := make([]dto.SysDictDataGetAllResp, 0)
|
||||
for _, i := range list {
|
||||
d := dto.SysDictDataGetAllResp{}
|
||||
e.Translate(i, &d)
|
||||
l = append(l, d)
|
||||
}
|
||||
|
||||
e.OK(l,"查询成功")
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysDictType struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 字典类型列表数据
|
||||
// @Summary 字典类型列表数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典类型
|
||||
// @Param dictName query string false "dictName"
|
||||
// @Param dictId query string false "dictId"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) GetPage(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]models.SysDictType, 0)
|
||||
var count int64
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get 字典类型通过字典id获取
|
||||
// @Summary 字典类型通过字典id获取
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典类型
|
||||
// @Param dictId path int true "字典类型编码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type/{dictId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) Get(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysDictType
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
//Insert 字典类型创建
|
||||
// @Summary 添加字典类型
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典类型
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysDictTypeInsertReq true "data"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type [post]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) Insert(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err,fmt.Sprintf(" 创建字典类型失败,详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改字典类型
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典类型
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysDictTypeUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type/{dictId} [put]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) Update(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Update(&req)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除字典类型
|
||||
// @Description 删除数据
|
||||
// @Tags 字典类型
|
||||
// @Param dictCode body dto.SysDictTypeDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type [delete]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) Delete(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// GetAll
|
||||
// @Summary 字典类型全部数据 代码生成使用接口
|
||||
// @Description 获取JSON
|
||||
// @Tags 字典类型
|
||||
// @Param dictName query string false "dictName"
|
||||
// @Param dictId query string false "dictId"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/dict/type-option-select [get]
|
||||
// @Security Bearer
|
||||
func (e SysDictType) GetAll(c *gin.Context) {
|
||||
s := service.SysDictType{}
|
||||
req :=dto.SysDictTypeGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]models.SysDictType, 0)
|
||||
err = s.GetAll(&req, &list)
|
||||
if err != nil {
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
e.OK(list, "查询成功")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 登录日志列表
|
||||
// @Summary 登录日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param username query string false "用户名"
|
||||
// @Param ipaddr query string false "ip地址"
|
||||
// @Param loginLocation query string false "归属地"
|
||||
// @Param status query string false "状态"
|
||||
// @Param beginTime query string false "开始时间"
|
||||
// @Param endTime query string false "结束时间"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-login-log [get]
|
||||
// @Security Bearer
|
||||
func (e SysLoginLog) GetPage(c *gin.Context) {
|
||||
s := service.SysLoginLog{}
|
||||
req :=dto.SysLoginLogGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
list := make([]models.SysLoginLog, 0)
|
||||
var count int64
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get 登录日志通过id获取
|
||||
// @Summary 登录日志通过id获取
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param id path string false "id"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-login-log/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysLoginLog) Get(c *gin.Context) {
|
||||
s := service.SysLoginLog{}
|
||||
req :=dto.SysLoginLogGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysLoginLog
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Delete 登录日志删除
|
||||
// @Summary 登录日志删除
|
||||
// @Description 登录日志删除
|
||||
// @Tags 登录日志
|
||||
// @Param data body dto.SysLoginLogDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-login-log [delete]
|
||||
// @Security Bearer
|
||||
func (e SysLoginLog) Delete(c *gin.Context) {
|
||||
s := service.SysLoginLog{}
|
||||
req :=dto.SysLoginLogDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysMenu struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage Menu列表数据
|
||||
// @Summary Menu列表数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Param menuName query string false "menuName"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menu [get]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) GetPage(c *gin.Context) {
|
||||
s := service.SysMenu{}
|
||||
req := dto.SysMenuGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var list = make([]models.SysMenu, 0)
|
||||
err = s.GetPage(&req, &list).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(list, "查询成功")
|
||||
}
|
||||
|
||||
// Get 获取菜单详情
|
||||
// @Summary Menu详情数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Param id path string false "id"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menu/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) Get(c *gin.Context) {
|
||||
req := dto.SysMenuGetReq{}
|
||||
s := new(service.SysMenu)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object = models.SysMenu{}
|
||||
|
||||
err = s.Get(&req, &object).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert 创建菜单
|
||||
// @Summary 创建菜单
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysMenuInsertReq true "data"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menu [post]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) Insert(c *gin.Context) {
|
||||
req := dto.SysMenuInsertReq{}
|
||||
s := new(service.SysMenu)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, "创建失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update 修改菜单
|
||||
// @Summary 修改菜单
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param id path int true "id"
|
||||
// @Param data body dto.SysMenuUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menu/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) Update(c *gin.Context) {
|
||||
req := dto.SysMenuUpdateReq{}
|
||||
s := new(service.SysMenu)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Update(&req).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, "更新失败")
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete 删除菜单
|
||||
// @Summary 删除菜单
|
||||
// @Description 删除数据
|
||||
// @Tags 菜单
|
||||
// @Param data body dto.SysMenuDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menu [delete]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) Delete(c *gin.Context) {
|
||||
control := new(dto.SysMenuDeleteReq)
|
||||
s := new(service.SysMenu)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(control, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
err = s.Remove(control).Error
|
||||
if err != nil {
|
||||
e.Logger.Errorf("RemoveSysMenu error, %s", err)
|
||||
e.Error(500, err, "删除失败")
|
||||
return
|
||||
}
|
||||
e.OK(control.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// GetMenuRole 根据登录角色名称获取菜单列表数据(左菜单使用)
|
||||
// @Summary 根据登录角色名称获取菜单列表数据(左菜单使用)
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menurole [get]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) GetMenuRole(c *gin.Context) {
|
||||
s := new(service.SysMenu)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := s.SetMenuRole(user.GetRoleName(c))
|
||||
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(result, "")
|
||||
}
|
||||
|
||||
// GetMenuTreeSelect 根据角色ID查询菜单下拉树结构
|
||||
// @Summary 角色修改使用的菜单列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 菜单
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param roleId path int true "roleId"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/menuTreeselect/{roleId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysMenu) GetMenuTreeSelect(c *gin.Context) {
|
||||
m := service.SysMenu{}
|
||||
r := service.SysRole{}
|
||||
req := dto.SelectRole{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&m.Service).
|
||||
MakeService(&r.Service).
|
||||
Bind(&req, nil).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
result, err := m.SetLabel()
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
menuIds := make([]int, 0)
|
||||
if req.RoleId != 0 {
|
||||
menuIds, err = r.GetRoleMenuId(req.RoleId)
|
||||
if err != nil {
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
}
|
||||
e.OK(gin.H{
|
||||
"menus": result,
|
||||
"checkedKeys": menuIds,
|
||||
}, "获取成功")
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage 操作日志列表
|
||||
// @Summary 操作日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 操作日志
|
||||
// @Param title query string false "title"
|
||||
// @Param method query string false "method"
|
||||
// @Param requestMethod query string false "requestMethod"
|
||||
// @Param operUrl query string false "operUrl"
|
||||
// @Param operIp query string false "operIp"
|
||||
// @Param status query string false "status"
|
||||
// @Param beginTime query string false "beginTime"
|
||||
// @Param endTime query string false "endTime"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-opera-log [get]
|
||||
// @Security Bearer
|
||||
func (e SysOperaLog) GetPage(c *gin.Context) {
|
||||
s := service.SysOperaLog{}
|
||||
req := new(dto.SysOperaLogGetPageReq)
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]models.SysOperaLog, 0)
|
||||
var count int64
|
||||
|
||||
err = s.GetPage(req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get 操作日志通过id获取
|
||||
// @Summary 操作日志通过id获取
|
||||
// @Description 获取JSON
|
||||
// @Tags 操作日志
|
||||
// @Param id path string false "id"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-opera-log/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysOperaLog) Get(c *gin.Context) {
|
||||
s := new(service.SysOperaLog)
|
||||
req :=dto.SysOperaLogGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysOperaLog
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Delete 操作日志删除
|
||||
// DeleteSysMenu 操作日志删除
|
||||
// @Summary 删除操作日志
|
||||
// @Description 删除数据
|
||||
// @Tags 操作日志
|
||||
// @Param data body dto.SysOperaLogDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-opera-log [delete]
|
||||
// @Security Bearer
|
||||
func (e SysOperaLog) Delete(c *gin.Context) {
|
||||
s := new(service.SysOperaLog)
|
||||
req :=dto.SysOperaLogDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500,err, fmt.Sprintf("删除失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysPost struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage
|
||||
// @Summary 岗位列表数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 岗位
|
||||
// @Param postName query string false "postName"
|
||||
// @Param postCode query string false "postCode"
|
||||
// @Param postId query string false "postId"
|
||||
// @Param status query string false "status"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/post [get]
|
||||
// @Security Bearer
|
||||
func (e SysPost) GetPage(c *gin.Context) {
|
||||
s := service.SysPost{}
|
||||
req :=dto.SysPostPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]models.SysPost, 0)
|
||||
var count int64
|
||||
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 获取岗位信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 岗位
|
||||
// @Param id path int true "编码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/post/{postId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysPost) Get(c *gin.Context) {
|
||||
s := service.SysPost{}
|
||||
req :=dto.SysPostGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysPost
|
||||
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("岗位信息获取失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert
|
||||
// @Summary 添加岗位
|
||||
// @Description 获取JSON
|
||||
// @Tags 岗位
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysPostInsertReq true "data"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/post [post]
|
||||
// @Security Bearer
|
||||
func (e SysPost) Insert(c *gin.Context) {
|
||||
s := service.SysPost{}
|
||||
req :=dto.SysPostInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("新建岗位失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改岗位
|
||||
// @Description 获取JSON
|
||||
// @Tags 岗位
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysPostUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/post/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysPost) Update(c *gin.Context) {
|
||||
s := service.SysPost{}
|
||||
req :=dto.SysPostUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
err = s.Update(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("岗位更新失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除岗位
|
||||
// @Description 删除数据
|
||||
// @Tags 岗位
|
||||
// @Param id body dto.SysPostDeleteReq true "请求参数"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/post [delete]
|
||||
// @Security Bearer
|
||||
func (e SysPost) Delete(c *gin.Context) {
|
||||
s := service.SysPost{}
|
||||
req :=dto.SysPostDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.Remove(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("岗位删除失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/common/global"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
)
|
||||
|
||||
type SysRole struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage
|
||||
// @Summary 角色列表数据
|
||||
// @Description Get JSON
|
||||
// @Tags 角色/Role
|
||||
// @Param roleName query string false "roleName"
|
||||
// @Param status query string false "status"
|
||||
// @Param roleKey query string false "roleKey"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role [get]
|
||||
// @Security Bearer
|
||||
func (e SysRole) GetPage(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.SysRoleGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.Form).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]models.SysRole, 0)
|
||||
var count int64
|
||||
|
||||
err = s.GetPage(&req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 获取Role数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 角色/Role
|
||||
// @Param roleId path string false "roleId"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role/{id} [get]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Get(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.SysRoleGetReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf(" %s ", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
var object models.SysRole
|
||||
|
||||
err = s.Get(&req, &object)
|
||||
if err != nil {
|
||||
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert
|
||||
// @Summary 创建角色
|
||||
// @Description 获取JSON
|
||||
// @Tags 角色/Role
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysRoleInsertReq true "data"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role [post]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Insert(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.SysRoleInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 设置创建人
|
||||
req.CreateBy = user.GetUserId(c)
|
||||
if req.Status == "" {
|
||||
req.Status = "2"
|
||||
}
|
||||
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
|
||||
err = s.Insert(&req, cb)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, "创建失败,"+err.Error())
|
||||
return
|
||||
}
|
||||
_, err = global.LoadPolicy(c)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, "创建失败,"+err.Error())
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update 修改用户角色
|
||||
// @Summary 修改用户角色
|
||||
// @Description 获取JSON
|
||||
// @Tags 角色/Role
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysRoleUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Update(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.SysRoleUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
err = s.Update(&req, cb)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = global.LoadPolicy(c)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, "更新失败,"+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除用户角色
|
||||
// @Description 删除数据
|
||||
// @Tags 角色/Role
|
||||
// @Param data body dto.SysRoleDeleteReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role [delete]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Delete(c *gin.Context) {
|
||||
s := new(service.SysRole)
|
||||
req := dto.SysRoleDeleteReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("删除角色 %v 失败,\r\n失败信息 %s", req.Ids, err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
cb := sdk.Runtime.GetCasbinKey(c.Request.Host)
|
||||
err = s.Remove(&req, cb)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(req.GetId(), fmt.Sprintf("删除角色角色 %v 状态成功!", req.GetId()))
|
||||
}
|
||||
|
||||
// Update2Status 修改用户角色状态
|
||||
// @Summary 修改用户角色
|
||||
// @Description 获取JSON
|
||||
// @Tags 角色/Role
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.UpdateStatusReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role-status/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Update2Status(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.UpdateStatusReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, fmt.Sprintf("更新角色状态失败,失败原因:%s ", err.Error()))
|
||||
return
|
||||
}
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
err = s.UpdateStatus(&req)
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("更新角色状态失败,失败原因:%s ", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), fmt.Sprintf("更新角色 %v 状态成功!", req.GetId()))
|
||||
}
|
||||
|
||||
// Update2DataScope 更新角色数据权限
|
||||
// @Summary 更新角色数据权限
|
||||
// @Description 获取JSON
|
||||
// @Tags 角色/Role
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.RoleDataScopeReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/role-status/{id} [put]
|
||||
// @Security Bearer
|
||||
func (e SysRole) Update2DataScope(c *gin.Context) {
|
||||
s := service.SysRole{}
|
||||
req := dto.RoleDataScopeReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
data := &models.SysRole{
|
||||
RoleId: req.RoleId,
|
||||
DataScope: req.DataScope,
|
||||
DeptIds: req.DeptIds,
|
||||
}
|
||||
data.UpdateBy = user.GetUserId(c)
|
||||
err = s.UpdateDataScope(&req).Error
|
||||
if err != nil {
|
||||
e.Error(500, err, fmt.Sprintf("更新角色数据权限失败!错误详情:%s", err.Error()))
|
||||
return
|
||||
}
|
||||
e.OK(nil, "操作成功")
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"go-admin/app/admin/models"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/api"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
|
||||
_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
)
|
||||
|
||||
type SysUser struct {
|
||||
api.Api
|
||||
}
|
||||
|
||||
// GetPage
|
||||
// @Summary 列表用户信息数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Param username query string false "username"
|
||||
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-user [get]
|
||||
// @Security Bearer
|
||||
func (e SysUser) GetPage(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserGetPageReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
|
||||
list := make([]models.SysUser, 0)
|
||||
var count int64
|
||||
|
||||
err = s.GetPage(&req, p, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(500, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
// Get
|
||||
// @Summary 获取用户
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Param userId path int true "用户编码"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-user/{userId} [get]
|
||||
// @Security Bearer
|
||||
func (e SysUser) Get(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserById{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
var object models.SysUser
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
err = s.Get(&req, p, &object)
|
||||
if err != nil {
|
||||
e.Error(http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
e.OK(object, "查询成功")
|
||||
}
|
||||
|
||||
// Insert
|
||||
// @Summary 创建用户
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysUserInsertReq true "用户数据"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-user [post]
|
||||
// @Security Bearer
|
||||
func (e SysUser) Insert(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserInsertReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
req.SetCreateBy(user.GetUserId(c))
|
||||
err = s.Insert(&req)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(req.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
// Update
|
||||
// @Summary 修改用户数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.SysUserUpdateReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-user/{userId} [put]
|
||||
// @Security Bearer
|
||||
func (e SysUser) Update(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserUpdateReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
|
||||
err = s.Update(&req, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// Delete
|
||||
// @Summary 删除用户数据
|
||||
// @Description 删除数据
|
||||
// @Tags 用户
|
||||
// @Param userId path int true "userId"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/sys-user/{userId} [delete]
|
||||
// @Security Bearer
|
||||
func (e SysUser) Delete(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserById{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 设置编辑人
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
// 数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
|
||||
err = s.Remove(&req, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "删除成功")
|
||||
}
|
||||
|
||||
// InsetAvatar
|
||||
// @Summary 修改头像
|
||||
// @Description 获取JSON
|
||||
// @Tags 个人中心
|
||||
// @Accept multipart/form-data
|
||||
// @Param file formData file true "file"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/user/avatar [post]
|
||||
// @Security Bearer
|
||||
func (e SysUser) InsetAvatar(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.UpdateSysUserAvatarReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
// 数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
form, _ := c.MultipartForm()
|
||||
files := form.File["upload[]"]
|
||||
guid := uuid.New().String()
|
||||
filPath := "static/uploadfile/" + guid + ".jpg"
|
||||
for _, file := range files {
|
||||
e.Logger.Debugf("upload avatar file: %s", file.Filename)
|
||||
// 上传文件至指定目录
|
||||
err = c.SaveUploadedFile(file, filPath)
|
||||
if err != nil {
|
||||
e.Logger.Errorf("save file error, %s", err.Error())
|
||||
e.Error(500, err, "")
|
||||
return
|
||||
}
|
||||
}
|
||||
req.UserId = p.UserId
|
||||
req.Avatar = "/" + filPath
|
||||
|
||||
err = s.UpdateAvatar(&req, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(filPath, "修改成功")
|
||||
}
|
||||
|
||||
// UpdateStatus 修改用户状态
|
||||
// @Summary 修改用户状态
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.UpdateSysUserStatusReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/user/status [put]
|
||||
// @Security Bearer
|
||||
func (e SysUser) UpdateStatus(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.UpdateSysUserStatusReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON, nil).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
|
||||
err = s.UpdateStatus(&req, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// ResetPwd 重置用户密码
|
||||
// @Summary 重置用户密码
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.ResetSysUserPwdReq true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/user/pwd/reset [put]
|
||||
// @Security Bearer
|
||||
func (e SysUser) ResetPwd(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.ResetSysUserPwdReq{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req, binding.JSON).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.SetUpdateBy(user.GetUserId(c))
|
||||
|
||||
//数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
|
||||
err = s.ResetPwd(&req, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(req.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
// UpdatePwd
|
||||
// @Summary 修改密码
|
||||
// @Description 获取JSON
|
||||
// @Tags 用户
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body dto.PassWord true "body"
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/user/pwd/set [put]
|
||||
// @Security Bearer
|
||||
func (e SysUser) UpdatePwd(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.PassWord{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
Bind(&req).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 数据权限检查
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
var hash []byte
|
||||
if hash, err = bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost); err != nil {
|
||||
req.NewPassword = string(hash)
|
||||
}
|
||||
|
||||
err = s.UpdatePwd(user.GetUserId(c), req.OldPassword, req.NewPassword, p)
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(http.StatusForbidden, err, "密码修改失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(nil, "密码修改成功")
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
// @Summary 获取个人中心用户
|
||||
// @Description 获取JSON
|
||||
// @Tags 个人中心
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/user/profile [get]
|
||||
// @Security Bearer
|
||||
func (e SysUser) GetProfile(c *gin.Context) {
|
||||
s := service.SysUser{}
|
||||
req := dto.SysUserById{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
req.Id = user.GetUserId(c)
|
||||
|
||||
sysUser := models.SysUser{}
|
||||
roles := make([]models.SysRole, 0)
|
||||
posts := make([]models.SysPost, 0)
|
||||
err = s.GetProfile(&req, &sysUser, &roles, &posts)
|
||||
if err != nil {
|
||||
e.Logger.Errorf("get user profile error, %s", err.Error())
|
||||
e.Error(500, err, "获取用户信息失败")
|
||||
return
|
||||
}
|
||||
e.OK(gin.H{
|
||||
"user": sysUser,
|
||||
"roles": roles,
|
||||
"posts": posts,
|
||||
}, "查询成功")
|
||||
}
|
||||
|
||||
// GetInfo
|
||||
// @Summary 获取个人信息
|
||||
// @Description 获取JSON
|
||||
// @Tags 个人中心
|
||||
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/getinfo [get]
|
||||
// @Security Bearer
|
||||
func (e SysUser) GetInfo(c *gin.Context) {
|
||||
req := dto.SysUserById{}
|
||||
s := service.SysUser{}
|
||||
r := service.SysRole{}
|
||||
err := e.MakeContext(c).
|
||||
MakeOrm().
|
||||
MakeService(&r.Service).
|
||||
MakeService(&s.Service).
|
||||
Errors
|
||||
if err != nil {
|
||||
e.Logger.Error(err)
|
||||
e.Error(500, err, err.Error())
|
||||
return
|
||||
}
|
||||
p := actions.GetPermissionFromContext(c)
|
||||
var roles = make([]string, 1)
|
||||
roles[0] = user.GetRoleName(c)
|
||||
var permissions = make([]string, 1)
|
||||
permissions[0] = "*:*:*"
|
||||
var buttons = make([]string, 1)
|
||||
buttons[0] = "*:*:*"
|
||||
|
||||
var mp = make(map[string]interface{})
|
||||
mp["roles"] = roles
|
||||
if user.GetRoleName(c) == "admin" || user.GetRoleName(c) == "系统管理员" {
|
||||
mp["permissions"] = permissions
|
||||
mp["buttons"] = buttons
|
||||
} else {
|
||||
list, _ := r.GetById(user.GetRoleId(c))
|
||||
mp["permissions"] = list
|
||||
mp["buttons"] = list
|
||||
}
|
||||
sysUser := models.SysUser{}
|
||||
req.Id = user.GetUserId(c)
|
||||
err = s.Get(&req, p, &sysUser)
|
||||
if err != nil {
|
||||
e.Error(http.StatusUnauthorized, err, "登录失败")
|
||||
return
|
||||
}
|
||||
mp["introduction"] = " am a super administrator"
|
||||
mp["avatar"] = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"
|
||||
if sysUser.Avatar != "" {
|
||||
mp["avatar"] = sysUser.Avatar
|
||||
}
|
||||
mp["userName"] = sysUser.Username
|
||||
mp["userId"] = sysUser.UserId
|
||||
mp["deptId"] = sysUser.DeptId
|
||||
mp["name"] = sysUser.NickName
|
||||
mp["code"] = 200
|
||||
e.OK(mp, "")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
type CasbinRule struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
Ptype string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V0 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V1 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V2 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V3 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V4 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
V5 string `gorm:"size:512;uniqueIndex:unique_index"`
|
||||
}
|
||||
|
||||
func (CasbinRule) TableName() string {
|
||||
return "sys_casbin_rule"
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
"gorm.io/gorm"
|
||||
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/config"
|
||||
)
|
||||
|
||||
type DataPermission struct {
|
||||
DataScope string
|
||||
UserId int
|
||||
DeptId int
|
||||
RoleId int
|
||||
}
|
||||
|
||||
func (e *DataPermission) GetDataScope(tableName string, db *gorm.DB) (*gorm.DB, error) {
|
||||
|
||||
if !config.ApplicationConfig.EnableDP {
|
||||
usageStr := `数据权限已经为您` + pkg.Green(`关闭`) + `,如需开启请参考配置文件字段说明`
|
||||
log.Debug("%s\n", usageStr)
|
||||
return db, nil
|
||||
}
|
||||
user := new(SysUser)
|
||||
role := new(SysRole)
|
||||
err := db.Find(user, e.UserId).Error
|
||||
if err != nil {
|
||||
return nil, errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
}
|
||||
err = db.Find(role, user.RoleId).Error
|
||||
if err != nil {
|
||||
return nil, errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
}
|
||||
if role.DataScope == "2" {
|
||||
db = db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", user.RoleId)
|
||||
}
|
||||
if role.DataScope == "3" {
|
||||
db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
|
||||
}
|
||||
if role.DataScope == "4" {
|
||||
db = db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%")
|
||||
}
|
||||
if role.DataScope == "5" || role.DataScope == "" {
|
||||
db = db.Where(tableName+".create_by = ?", e.UserId)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
//func DataScopes(tableName string, userId int) func(db *gorm.DB) *gorm.DB {
|
||||
// return func(db *gorm.DB) *gorm.DB {
|
||||
// user := new(SysUser)
|
||||
// role := new(SysRole)
|
||||
// user.UserId = userId
|
||||
// err := db.Find(user, userId).Error
|
||||
// if err != nil {
|
||||
// db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
// return db
|
||||
// }
|
||||
// err = db.Find(role, user.RoleId).Error
|
||||
// if err != nil {
|
||||
// db.Error = errors.New("获取用户数据出错 msg:" + err.Error())
|
||||
// return db
|
||||
// }
|
||||
// if role.DataScope == "2" {
|
||||
// return db.Where(tableName+".create_by in (select sys_user.user_id from sys_role_dept left join sys_user on sys_user.dept_id=sys_role_dept.dept_id where sys_role_dept.role_id = ?)", user.RoleId)
|
||||
// }
|
||||
// if role.DataScope == "3" {
|
||||
// return db.Where(tableName+".create_by in (SELECT user_id from sys_user where dept_id = ? )", user.DeptId)
|
||||
// }
|
||||
// if role.DataScope == "4" {
|
||||
// return db.Where(tableName+".create_by in (SELECT user_id from sys_user where sys_user.dept_id in(select dept_id from sys_dept where dept_path like ? ))", "%"+pkg.IntToString(user.DeptId)+"%")
|
||||
// }
|
||||
// if role.DataScope == "5" || role.DataScope == "" {
|
||||
// return db.Where(tableName+".create_by = ?", userId)
|
||||
// }
|
||||
// return db
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,55 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-admin/common/global"
|
||||
"gorm.io/gorm"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func InitDb(db *gorm.DB) (err error) {
|
||||
filePath := "config/db.sql"
|
||||
err = ExecSql(db, filePath)
|
||||
if global.Driver == "postgres" {
|
||||
filePath = "config/pg.sql"
|
||||
err = ExecSql(db, filePath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func ExecSql(db *gorm.DB, filePath string) error {
|
||||
sql, err := Ioutil(filePath)
|
||||
if err != nil {
|
||||
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
|
||||
return err
|
||||
}
|
||||
sqlList := strings.Split(sql, ";")
|
||||
for i := 0; i < len(sqlList)-1; i++ {
|
||||
if strings.Contains(sqlList[i], "--") {
|
||||
fmt.Println(sqlList[i])
|
||||
continue
|
||||
}
|
||||
sql := strings.Replace(sqlList[i]+";", "\n", "", -1)
|
||||
sql = strings.TrimSpace(sql)
|
||||
if err = db.Exec(sql).Error; err != nil {
|
||||
log.Printf("error sql: %s", sql)
|
||||
if !strings.Contains(err.Error(), "Query was empty") {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Ioutil(filePath string) (string, error) {
|
||||
if contents, err := ioutil.ReadFile(filePath); err == nil {
|
||||
//因为contents是[]byte类型,直接转换成string类型后会多一行空格,需要使用strings.Replace替换换行符
|
||||
result := strings.Replace(string(contents), "\n", "", 1)
|
||||
fmt.Println("Use ioutil.ReadFile to read a file:", result)
|
||||
return result, nil
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/bitly/go-simplejson"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/runtime"
|
||||
"github.com/go-admin-team/go-admin-core/storage"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysApi struct {
|
||||
Id int `json:"id" gorm:"primaryKey;autoIncrement;comment:主键编码"`
|
||||
Handle string `json:"handle" gorm:"size:128;comment:handle"`
|
||||
Title string `json:"title" gorm:"size:128;comment:标题"`
|
||||
Path string `json:"path" gorm:"size:128;comment:地址"`
|
||||
Action string `json:"action" gorm:"size:16;comment:请求类型"`
|
||||
Type string `json:"type" gorm:"size:16;comment:接口类型"`
|
||||
models.ModelTime
|
||||
models.ControlBy
|
||||
}
|
||||
|
||||
func (*SysApi) TableName() string {
|
||||
return "sys_api"
|
||||
}
|
||||
|
||||
func (e *SysApi) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysApi) GetId() interface{} {
|
||||
return e.Id
|
||||
}
|
||||
|
||||
func SaveSysApi(message storage.Messager) (err error) {
|
||||
var rb []byte
|
||||
rb, err = json.Marshal(message.GetValues())
|
||||
if err != nil {
|
||||
err = fmt.Errorf("json Marshal error, %v", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
var l runtime.Routers
|
||||
err = json.Unmarshal(rb, &l)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("json Unmarshal error, %s", err.Error())
|
||||
return err
|
||||
}
|
||||
dbList := sdk.Runtime.GetDb()
|
||||
for _, d := range dbList {
|
||||
for _, v := range l.List {
|
||||
if v.HttpMethod != "HEAD" ||
|
||||
strings.Contains(v.RelativePath, "/swagger/") ||
|
||||
strings.Contains(v.RelativePath, "/static/") ||
|
||||
strings.Contains(v.RelativePath, "/form-generator/") ||
|
||||
strings.Contains(v.RelativePath, "/sys/tables") {
|
||||
|
||||
// 根据接口方法注释里的@Summary填充接口名称,适用于代码生成器
|
||||
// 可在此处增加配置路径前缀的if判断,只对代码生成的自建应用进行定向的接口名称填充
|
||||
jsonFile, _ := ioutil.ReadFile("docs/swagger.json")
|
||||
jsonData, _ := simplejson.NewFromReader(bytes.NewReader(jsonFile))
|
||||
urlPath := v.RelativePath
|
||||
idPatten := "(.*)/:(\\w+)" // 正则替换,把:id换成{id}
|
||||
reg, _ := regexp.Compile(idPatten)
|
||||
if reg.MatchString(urlPath) {
|
||||
urlPath = reg.ReplaceAllString(v.RelativePath, "${1}/{${2}}") // 把:id换成{id}
|
||||
}
|
||||
apiTitle, _ := jsonData.Get("paths").Get(urlPath).Get(strings.ToLower(v.HttpMethod)).Get("summary").String()
|
||||
|
||||
err := d.Debug().Where(SysApi{Path: v.RelativePath, Action: v.HttpMethod}).
|
||||
Attrs(SysApi{Handle: v.Handler, Title: apiTitle}).
|
||||
FirstOrCreate(&SysApi{}).
|
||||
//Update("handle", v.Handler).
|
||||
Error
|
||||
if err != nil {
|
||||
err := fmt.Errorf("Models SaveSysApi error: %s \r\n ", err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
models.Model
|
||||
ConfigName string `json:"configName" gorm:"size:128;comment:ConfigName"` //
|
||||
ConfigKey string `json:"configKey" gorm:"size:128;comment:ConfigKey"` //
|
||||
ConfigValue string `json:"configValue" gorm:"size:255;comment:ConfigValue"` //
|
||||
ConfigType string `json:"configType" gorm:"size:64;comment:ConfigType"`
|
||||
IsFrontend string `json:"isFrontend" gorm:"size:64;comment:是否前台"` //
|
||||
Remark string `json:"remark" gorm:"size:128;comment:Remark"` //
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysConfig) TableName() string {
|
||||
return "sys_config"
|
||||
}
|
||||
|
||||
func (e *SysConfig) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetId() interface{} {
|
||||
return e.Id
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package models
|
||||
|
||||
import "go-admin/common/models"
|
||||
|
||||
type SysDept struct {
|
||||
DeptId int `json:"deptId" gorm:"primaryKey;autoIncrement;"` //部门编码
|
||||
ParentId int `json:"parentId" gorm:""` //上级部门
|
||||
DeptPath string `json:"deptPath" gorm:"size:255;"` //
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
Sort int `json:"sort" gorm:"size:4;"` //排序
|
||||
Leader string `json:"leader" gorm:"size:128;"` //负责人
|
||||
Phone string `json:"phone" gorm:"size:11;"` //手机
|
||||
Email string `json:"email" gorm:"size:64;"` //邮箱
|
||||
Status int `json:"status" gorm:"size:4;"` //状态
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
Children []SysDept `json:"children" gorm:"-"`
|
||||
}
|
||||
|
||||
func (*SysDept) TableName() string {
|
||||
return "sys_dept"
|
||||
}
|
||||
|
||||
func (e *SysDept) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysDept) GetId() interface{} {
|
||||
return e.DeptId
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysDictData struct {
|
||||
DictCode int `json:"dictCode" gorm:"primaryKey;column:dict_code;autoIncrement;comment:主键编码"`
|
||||
DictSort int `json:"dictSort" gorm:"size:20;comment:DictSort"`
|
||||
DictLabel string `json:"dictLabel" gorm:"size:128;comment:DictLabel"`
|
||||
DictValue string `json:"dictValue" gorm:"size:255;comment:DictValue"`
|
||||
DictType string `json:"dictType" gorm:"size:64;comment:DictType"`
|
||||
CssClass string `json:"cssClass" gorm:"size:128;comment:CssClass"`
|
||||
ListClass string `json:"listClass" gorm:"size:128;comment:ListClass"`
|
||||
IsDefault string `json:"isDefault" gorm:"size:8;comment:IsDefault"`
|
||||
Status int `json:"status" gorm:"size:4;comment:Status"`
|
||||
Default string `json:"default" gorm:"size:8;comment:Default"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:Remark"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysDictData) TableName() string {
|
||||
return "sys_dict_data"
|
||||
}
|
||||
|
||||
func (e *SysDictData) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysDictData) GetId() interface{} {
|
||||
return e.DictCode
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysDictType struct {
|
||||
ID int `json:"id" gorm:"primaryKey;column:dict_id;autoIncrement;comment:主键编码"`
|
||||
DictName string `json:"dictName" gorm:"size:128;comment:DictName"`
|
||||
DictType string `json:"dictType" gorm:"size:128;comment:DictType"`
|
||||
Status int `json:"status" gorm:"size:4;comment:Status"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:Remark"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysDictType) TableName() string {
|
||||
return "sys_dict_type"
|
||||
}
|
||||
|
||||
func (e *SysDictType) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysDictType) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
"github.com/go-admin-team/go-admin-core/storage"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
models.Model
|
||||
Username string `json:"username" gorm:"size:128;comment:用户名"`
|
||||
Status string `json:"status" gorm:"size:4;comment:状态"`
|
||||
Ipaddr string `json:"ipaddr" gorm:"size:255;comment:ip地址"`
|
||||
LoginLocation string `json:"loginLocation" gorm:"size:255;comment:归属地"`
|
||||
Browser string `json:"browser" gorm:"size:255;comment:浏览器"`
|
||||
Os string `json:"os" gorm:"size:255;comment:系统"`
|
||||
Platform string `json:"platform" gorm:"size:255;comment:固件"`
|
||||
LoginTime time.Time `json:"loginTime" gorm:"comment:登录时间"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:备注"`
|
||||
Msg string `json:"msg" gorm:"size:255;comment:信息"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
|
||||
models.ControlBy
|
||||
}
|
||||
|
||||
func (*SysLoginLog) TableName() string {
|
||||
return "sys_login_log"
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetId() interface{} {
|
||||
return e.Id
|
||||
}
|
||||
|
||||
// SaveLoginLog 从队列中获取登录日志
|
||||
func SaveLoginLog(message storage.Messager) (err error) {
|
||||
//准备db
|
||||
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
|
||||
if db == nil {
|
||||
err = errors.New("db not exist")
|
||||
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
|
||||
return err
|
||||
}
|
||||
var rb []byte
|
||||
rb, err = json.Marshal(message.GetValues())
|
||||
if err != nil {
|
||||
log.Errorf("json Marshal error, %s", err.Error())
|
||||
return err
|
||||
}
|
||||
var l SysLoginLog
|
||||
err = json.Unmarshal(rb, &l)
|
||||
if err != nil {
|
||||
log.Errorf("json Unmarshal error, %s", err.Error())
|
||||
return err
|
||||
}
|
||||
err = db.Create(&l).Error
|
||||
if err != nil {
|
||||
log.Errorf("db create error, %s", err.Error())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package models
|
||||
|
||||
import "go-admin/common/models"
|
||||
|
||||
type SysMenu struct {
|
||||
MenuId int `json:"menuId" gorm:"primaryKey;autoIncrement"`
|
||||
MenuName string `json:"menuName" gorm:"size:128;"`
|
||||
Title string `json:"title" gorm:"size:128;"`
|
||||
Icon string `json:"icon" gorm:"size:128;"`
|
||||
Path string `json:"path" gorm:"size:128;"`
|
||||
Paths string `json:"paths" gorm:"size:128;"`
|
||||
MenuType string `json:"menuType" gorm:"size:1;"`
|
||||
Action string `json:"action" gorm:"size:16;"`
|
||||
Permission string `json:"permission" gorm:"size:255;"`
|
||||
ParentId int `json:"parentId" gorm:"size:11;"`
|
||||
NoCache bool `json:"noCache" gorm:"size:8;"`
|
||||
Breadcrumb string `json:"breadcrumb" gorm:"size:255;"`
|
||||
Component string `json:"component" gorm:"size:255;"`
|
||||
Sort int `json:"sort" gorm:"size:4;"`
|
||||
Visible string `json:"visible" gorm:"size:1;"`
|
||||
IsFrame string `json:"isFrame" gorm:"size:1;DEFAULT:0;"`
|
||||
SysApi []SysApi `json:"sysApi" gorm:"many2many:sys_menu_api_rule"`
|
||||
Apis []int `json:"apis" gorm:"-"`
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
RoleId int `gorm:"-"`
|
||||
Children []SysMenu `json:"children,omitempty" gorm:"-"`
|
||||
IsSelect bool `json:"is_select" gorm:"-"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
type SysMenuSlice []SysMenu
|
||||
|
||||
func (x SysMenuSlice) Len() int { return len(x) }
|
||||
func (x SysMenuSlice) Less(i, j int) bool { return x[i].Sort < x[j].Sort }
|
||||
func (x SysMenuSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
||||
|
||||
func (*SysMenu) TableName() string {
|
||||
return "sys_menu"
|
||||
}
|
||||
|
||||
func (e *SysMenu) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysMenu) GetId() interface{} {
|
||||
return e.MenuId
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
"github.com/go-admin-team/go-admin-core/storage"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
models.Model
|
||||
Title string `json:"title" gorm:"size:255;comment:操作模块"`
|
||||
BusinessType string `json:"businessType" gorm:"size:128;comment:操作类型"`
|
||||
BusinessTypes string `json:"businessTypes" gorm:"size:128;comment:BusinessTypes"`
|
||||
Method string `json:"method" gorm:"size:128;comment:函数"`
|
||||
RequestMethod string `json:"requestMethod" gorm:"size:128;comment:请求方式 GET POST PUT DELETE"`
|
||||
OperatorType string `json:"operatorType" gorm:"size:128;comment:操作类型"`
|
||||
OperName string `json:"operName" gorm:"size:128;comment:操作者"`
|
||||
DeptName string `json:"deptName" gorm:"size:128;comment:部门名称"`
|
||||
OperUrl string `json:"operUrl" gorm:"size:255;comment:访问地址"`
|
||||
OperIp string `json:"operIp" gorm:"size:128;comment:客户端ip"`
|
||||
OperLocation string `json:"operLocation" gorm:"size:128;comment:访问位置"`
|
||||
OperParam string `json:"operParam" gorm:"text;comment:请求参数"`
|
||||
Status string `json:"status" gorm:"size:4;comment:操作状态 1:正常 2:关闭"`
|
||||
OperTime time.Time `json:"operTime" gorm:"comment:操作时间"`
|
||||
JsonResult string `json:"jsonResult" gorm:"size:255;comment:返回数据"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:备注"`
|
||||
LatencyTime string `json:"latencyTime" gorm:"size:128;comment:耗时"`
|
||||
UserAgent string `json:"userAgent" gorm:"size:255;comment:ua"`
|
||||
CreatedAt time.Time `json:"createdAt" gorm:"comment:创建时间"`
|
||||
UpdatedAt time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
|
||||
models.ControlBy
|
||||
}
|
||||
|
||||
func (*SysOperaLog) TableName() string {
|
||||
return "sys_opera_log"
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetId() interface{} {
|
||||
return e.Id
|
||||
}
|
||||
|
||||
// SaveOperaLog 从队列中获取操作日志
|
||||
func SaveOperaLog(message storage.Messager) (err error) {
|
||||
//准备db
|
||||
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
|
||||
if db == nil {
|
||||
err = errors.New("db not exist")
|
||||
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
|
||||
// Log writing to the database ignores error
|
||||
return nil
|
||||
}
|
||||
var rb []byte
|
||||
rb, err = json.Marshal(message.GetValues())
|
||||
if err != nil {
|
||||
log.Errorf("json Marshal error, %s", err.Error())
|
||||
// Log writing to the database ignores error
|
||||
return nil
|
||||
}
|
||||
var l SysOperaLog
|
||||
err = json.Unmarshal(rb, &l)
|
||||
if err != nil {
|
||||
log.Errorf("json Unmarshal error, %s", err.Error())
|
||||
// Log writing to the database ignores error
|
||||
return nil
|
||||
}
|
||||
// 超出100个字符返回值截断
|
||||
if len(l.JsonResult) > 100 {
|
||||
l.JsonResult = l.JsonResult[:100]
|
||||
}
|
||||
err = db.Create(&l).Error
|
||||
if err != nil {
|
||||
log.Errorf("db create error, %s", err.Error())
|
||||
// Log writing to the database ignores error
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package models
|
||||
|
||||
import "go-admin/common/models"
|
||||
|
||||
type SysPost struct {
|
||||
PostId int `gorm:"primaryKey;autoIncrement" json:"postId"` //岗位编号
|
||||
PostName string `gorm:"size:128;" json:"postName"` //岗位名称
|
||||
PostCode string `gorm:"size:128;" json:"postCode"` //岗位代码
|
||||
Sort int `gorm:"size:4;" json:"sort"` //岗位排序
|
||||
Status int `gorm:"size:4;" json:"status"` //状态
|
||||
Remark string `gorm:"size:255;" json:"remark"` //描述
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params string `gorm:"-" json:"params"`
|
||||
}
|
||||
|
||||
func (*SysPost) TableName() string {
|
||||
return "sys_post"
|
||||
}
|
||||
|
||||
func (e *SysPost) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysPost) GetId() interface{} {
|
||||
return e.PostId
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package models
|
||||
|
||||
import "go-admin/common/models"
|
||||
|
||||
type SysRole struct {
|
||||
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
|
||||
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
|
||||
Status string `json:"status" gorm:"size:4;"` // 状态 1禁用 2正常
|
||||
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
|
||||
RoleSort int `json:"roleSort" gorm:""` //角色排序
|
||||
Flag string `json:"flag" gorm:"size:128;"` //
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
Admin bool `json:"admin" gorm:"size:4;"`
|
||||
DataScope string `json:"dataScope" gorm:"size:128;"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
SysDept []SysDept `json:"sysDept" gorm:"many2many:sys_role_dept;foreignKey:RoleId;joinForeignKey:role_id;references:DeptId;joinReferences:dept_id;"`
|
||||
SysMenu *[]SysMenu `json:"sysMenu" gorm:"many2many:sys_role_menu;foreignKey:RoleId;joinForeignKey:role_id;references:MenuId;joinReferences:menu_id;"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysRole) TableName() string {
|
||||
return "sys_role"
|
||||
}
|
||||
|
||||
func (e *SysRole) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysRole) GetId() interface{} {
|
||||
return e.RoleId
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"go-admin/common/models"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysUser struct {
|
||||
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
|
||||
Username string `json:"username" gorm:"size:64;comment:用户名"`
|
||||
Password string `json:"-" gorm:"size:128;comment:密码"`
|
||||
NickName string `json:"nickName" gorm:"size:128;comment:昵称"`
|
||||
Phone string `json:"phone" gorm:"size:11;comment:手机号"`
|
||||
RoleId int `json:"roleId" gorm:"size:20;comment:角色ID"`
|
||||
Salt string `json:"-" gorm:"size:255;comment:加盐"`
|
||||
Avatar string `json:"avatar" gorm:"size:255;comment:头像"`
|
||||
Sex string `json:"sex" gorm:"size:255;comment:性别"`
|
||||
Email string `json:"email" gorm:"size:128;comment:邮箱"`
|
||||
DeptId int `json:"deptId" gorm:"size:20;comment:部门"`
|
||||
PostId int `json:"postId" gorm:"size:20;comment:岗位"`
|
||||
Remark string `json:"remark" gorm:"size:255;comment:备注"`
|
||||
Status string `json:"status" gorm:"size:4;comment:状态"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
PostIds []int `json:"postIds" gorm:"-"`
|
||||
RoleIds []int `json:"roleIds" gorm:"-"`
|
||||
Dept *SysDept `json:"dept"`
|
||||
models.ControlBy
|
||||
models.ModelTime
|
||||
}
|
||||
|
||||
func (*SysUser) TableName() string {
|
||||
return "sys_user"
|
||||
}
|
||||
|
||||
func (e *SysUser) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysUser) GetId() interface{} {
|
||||
return e.UserId
|
||||
}
|
||||
|
||||
// Encrypt 加密
|
||||
func (e *SysUser) Encrypt() (err error) {
|
||||
if e.Password == "" {
|
||||
return
|
||||
}
|
||||
|
||||
var hash []byte
|
||||
if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
|
||||
return
|
||||
} else {
|
||||
e.Password = string(hash)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *SysUser) BeforeCreate(_ *gorm.DB) error {
|
||||
return e.Encrypt()
|
||||
}
|
||||
|
||||
func (e *SysUser) BeforeUpdate(_ *gorm.DB) error {
|
||||
var err error
|
||||
if e.Password != "" {
|
||||
err = e.Encrypt()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (e *SysUser) AfterFind(_ *gorm.DB) error {
|
||||
e.DeptIds = []int{e.DeptId}
|
||||
e.PostIds = []int{e.PostId}
|
||||
e.RoleIds = []int{e.RoleId}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk"
|
||||
common "go-admin/common/middleware"
|
||||
)
|
||||
|
||||
// InitRouter 路由初始化,不要怀疑,这里用到了
|
||||
func InitRouter() {
|
||||
var r *gin.Engine
|
||||
h := sdk.Runtime.GetEngine()
|
||||
if h == nil {
|
||||
log.Fatal("not found engine...")
|
||||
os.Exit(-1)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
// the jwt middleware
|
||||
authMiddleware, err := common.AuthInit()
|
||||
if err != nil {
|
||||
log.Fatalf("JWT Init Error, %s", err.Error())
|
||||
}
|
||||
|
||||
// 注册系统路由
|
||||
InitSysRouter(r, authMiddleware)
|
||||
|
||||
// 注册业务路由
|
||||
// TODO: 这里可存放业务路由,里边并无实际路由只有演示代码
|
||||
InitExamplesRouter(r, authMiddleware)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
)
|
||||
|
||||
var (
|
||||
routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
|
||||
routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
|
||||
)
|
||||
|
||||
func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
|
||||
|
||||
// 无需认证的路由
|
||||
examplesNoCheckRoleRouter(r)
|
||||
// 需要认证的路由
|
||||
examplesCheckRoleRouter(r, authMiddleware)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// 无需认证的路由示例
|
||||
func examplesNoCheckRoleRouter(r *gin.Engine) {
|
||||
// 可根据业务需求来设置接口版本
|
||||
v1 := r.Group("/api/v1")
|
||||
for _, f := range routerNoCheckRole {
|
||||
f(v1)
|
||||
}
|
||||
}
|
||||
|
||||
// 需要认证的路由示例
|
||||
func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
|
||||
// 可根据业务需求来设置接口版本
|
||||
v1 := r.Group("/api/v1")
|
||||
// Bell 骨架只启用认证/RBAC 必需的用户、角色和菜单模块。
|
||||
// 其余冻结上游模块源码保留,但不注册路由,避免仅隐藏菜单后仍可直访。
|
||||
for _, f := range []func(*gin.RouterGroup, *jwt.GinJWTMiddleware){
|
||||
registerSysMenuRouter,
|
||||
registerSysRoleRouter,
|
||||
registerSysUserRouter,
|
||||
} {
|
||||
f(v1, authMiddleware)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysApiRouter)
|
||||
}
|
||||
|
||||
// registerSysApiRouter
|
||||
func registerSysApiRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysApi{}
|
||||
r := v1.Group("/sys-api").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.PUT("/:id", api.Update)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysConfigRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysConfig{}
|
||||
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("/:id", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
|
||||
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r1.GET("/:configKey", api.GetSysConfigByKEYForService)
|
||||
}
|
||||
|
||||
r2 := v1.Group("/app-config")
|
||||
{
|
||||
r2.GET("", api.Get2SysApp)
|
||||
}
|
||||
|
||||
r3 := v1.Group("/set-config").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r3.PUT("", api.Update2Set)
|
||||
r3.GET("", api.Get2Set)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysDeptRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysDept{}
|
||||
|
||||
r := v1.Group("/dept").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("/:id", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
|
||||
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r1.GET("/deptTree", api.Get2Tree)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerDictRouter)
|
||||
}
|
||||
|
||||
func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
dictApi := apis.SysDictType{}
|
||||
dataApi := apis.SysDictData{}
|
||||
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
|
||||
dicts.GET("/data", dataApi.GetPage)
|
||||
dicts.GET("/data/:dictCode", dataApi.Get)
|
||||
dicts.POST("/data", dataApi.Insert)
|
||||
dicts.PUT("/data/:dictCode", dataApi.Update)
|
||||
dicts.DELETE("/data", dataApi.Delete)
|
||||
|
||||
dicts.GET("/type-option-select", dictApi.GetAll)
|
||||
dicts.GET("/type", dictApi.GetPage)
|
||||
dicts.GET("/type/:id", dictApi.Get)
|
||||
dicts.POST("/type", dictApi.Insert)
|
||||
dicts.PUT("/type/:id", dictApi.Update)
|
||||
dicts.DELETE("/type", dictApi.Delete)
|
||||
}
|
||||
opSelect := v1.Group("/dict-data").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
opSelect.GET("/option-select", dataApi.GetAll)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysLoginLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysLoginLog{}
|
||||
|
||||
r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysMenuRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysMenu{}
|
||||
|
||||
r := v1.Group("/menu").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("/:id", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
|
||||
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r1.GET("/menurole", api.GetMenuRole)
|
||||
//r1.GET("/menuids", api.GetMenuIDS)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysOperaLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysOperaLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysOperaLog{}
|
||||
r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSyPostRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSyPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysPost{}
|
||||
r := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("/:id", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysRoleRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysRole{}
|
||||
r := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("/:id", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
r1 := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
r1.PUT("/role-status", api.Update2Status)
|
||||
r1.PUT("/roledatascope", api.Update2DataScope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/middleware"
|
||||
"go-admin/common/middleware/handler"
|
||||
)
|
||||
|
||||
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
|
||||
g := r.Group("")
|
||||
// Bell 骨架只注册认证入口和明确允许的 RBAC 管理路由;
|
||||
// 上游静态、Swagger、WebSocket 等默认能力保留源码但默认不暴露。
|
||||
sysCheckRoleRouterInit(g, authMiddleware)
|
||||
return g
|
||||
}
|
||||
|
||||
func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
v1 := r.Group("/api/v1")
|
||||
{
|
||||
v1.POST("/login", authMiddleware.LoginHandler)
|
||||
// Refresh time can be longer than token timeout
|
||||
v1.GET("/refresh_token", authMiddleware.RefreshHandler)
|
||||
}
|
||||
registerBaseRouter(v1, authMiddleware)
|
||||
}
|
||||
|
||||
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
systemAPI := apis.System{}
|
||||
v1.GET("/captcha", systemAPI.GenerateCaptchaHandler)
|
||||
|
||||
api := apis.SysMenu{}
|
||||
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
v1auth.GET("/roleMenuTreeselect/:roleId", api.GetMenuTreeSelect)
|
||||
v1auth.POST("/logout", handler.LogOut)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
|
||||
"go-admin/app/admin/apis"
|
||||
"go-admin/common/actions"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysUserRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := apis.SysUser{}
|
||||
r := v1.Group("/sys-user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction())
|
||||
{
|
||||
r.GET("", api.GetPage)
|
||||
r.GET("/:id", api.Get)
|
||||
r.POST("", api.Insert)
|
||||
r.PUT("", api.Update)
|
||||
r.DELETE("", api.Delete)
|
||||
}
|
||||
|
||||
user := v1.Group("/user").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole()).Use(actions.PermissionAction())
|
||||
{
|
||||
user.GET("/profile", api.GetProfile)
|
||||
user.POST("/avatar", api.InsetAvatar)
|
||||
user.PUT("/pwd/set", api.UpdatePwd)
|
||||
user.PUT("/pwd/reset", api.ResetPwd)
|
||||
user.PUT("/status", api.UpdateStatus)
|
||||
}
|
||||
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc())
|
||||
{
|
||||
v1auth.GET("/getinfo", api.GetInfo)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
// SysApiGetPageReq 功能列表请求参数
|
||||
type SysApiGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Title string `form:"title" search:"type:contains;column:title;table:sys_api" comment:"标题"`
|
||||
Path string `form:"path" search:"type:contains;column:path;table:sys_api" comment:"地址"`
|
||||
Action string `form:"action" search:"type:exact;column:action;table:sys_api" comment:"请求方式"`
|
||||
ParentId string `form:"parentId" search:"type:exact;column:parent_id;table:sys_api" comment:"按钮id"`
|
||||
Type string `form:"type" search:"-" comment:"类型"`
|
||||
SysApiOrder
|
||||
}
|
||||
|
||||
type SysApiOrder struct {
|
||||
TitleOrder string `search:"type:order;column:title;table:sys_api" form:"titleOrder"`
|
||||
PathOrder string `search:"type:order;column:path;table:sys_api" form:"pathOrder"`
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_api" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
func (m *SysApiGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
// SysApiInsertReq 功能创建请求参数
|
||||
type SysApiInsertReq struct {
|
||||
Id int `json:"-" comment:"编码"` // 编码
|
||||
Handle string `json:"handle" comment:"handle"`
|
||||
Title string `json:"title" comment:"标题"`
|
||||
Path string `json:"path" comment:"地址"`
|
||||
Type string `json:"type" comment:""`
|
||||
Action string `json:"action" comment:"类型"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysApiInsertReq) Generate(model *models.SysApi) {
|
||||
model.Handle = s.Handle
|
||||
model.Title = s.Title
|
||||
model.Path = s.Path
|
||||
model.Type = s.Type
|
||||
model.Action = s.Action
|
||||
}
|
||||
|
||||
func (s *SysApiInsertReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysApiUpdateReq 功能更新请求参数
|
||||
type SysApiUpdateReq struct {
|
||||
Id int `uri:"id" comment:"编码"` // 编码
|
||||
Handle string `json:"handle" comment:"handle"`
|
||||
Title string `json:"title" comment:"标题"`
|
||||
Path string `json:"path" comment:"地址"`
|
||||
Type string `json:"type" comment:""`
|
||||
Action string `json:"action" comment:"类型"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysApiUpdateReq) Generate(model *models.SysApi) {
|
||||
if s.Id != 0 {
|
||||
model.Id = s.Id
|
||||
}
|
||||
model.Handle = s.Handle
|
||||
model.Title = s.Title
|
||||
model.Path = s.Path
|
||||
model.Type = s.Type
|
||||
model.Action = s.Action
|
||||
}
|
||||
|
||||
func (s *SysApiUpdateReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysApiGetReq 功能获取请求参数
|
||||
type SysApiGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysApiGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysApiDeleteReq 功能删除请求参数
|
||||
type SysApiDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *SysApiDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
// SysConfigGetPageReq 列表或者搜索使用结构体
|
||||
type SysConfigGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
ConfigName string `form:"configName" search:"type:contains;column:config_name;table:sys_config"`
|
||||
ConfigKey string `form:"configKey" search:"type:contains;column:config_key;table:sys_config"`
|
||||
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config"`
|
||||
IsFrontend string `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
|
||||
SysConfigOrder
|
||||
}
|
||||
|
||||
type SysConfigOrder struct {
|
||||
IdOrder string `search:"type:order;column:id;table:sys_config" form:"idOrder"`
|
||||
ConfigNameOrder string `search:"type:order;column:config_name;table:sys_config" form:"configNameOrder"`
|
||||
ConfigKeyOrder string `search:"type:order;column:config_key;table:sys_config" form:"configKeyOrder"`
|
||||
ConfigTypeOrder string `search:"type:order;column:config_type;table:sys_config" form:"configTypeOrder"`
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_config" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
func (m *SysConfigGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysConfigGetToSysAppReq struct {
|
||||
IsFrontend string `form:"isFrontend" search:"type:exact;column:is_frontend;table:sys_config"`
|
||||
}
|
||||
|
||||
func (m *SysConfigGetToSysAppReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
// SysConfigControl 增、改使用的结构体
|
||||
type SysConfigControl struct {
|
||||
Id int `uri:"Id" comment:"编码"` // 编码
|
||||
ConfigName string `json:"configName" comment:""`
|
||||
ConfigKey string `uri:"configKey" json:"configKey" comment:""`
|
||||
ConfigValue string `json:"configValue" comment:""`
|
||||
ConfigType string `json:"configType" comment:""`
|
||||
IsFrontend string `json:"isFrontend"`
|
||||
Remark string `json:"remark" comment:""`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
// Generate 结构体数据转化 从 SysConfigControl 至 system.SysConfig 对应的模型
|
||||
func (s *SysConfigControl) Generate(model *models.SysConfig) {
|
||||
if s.Id == 0 {
|
||||
model.Model = common.Model{Id: s.Id}
|
||||
}
|
||||
model.ConfigName = s.ConfigName
|
||||
model.ConfigKey = s.ConfigKey
|
||||
model.ConfigValue = s.ConfigValue
|
||||
model.ConfigType = s.ConfigType
|
||||
model.IsFrontend = s.IsFrontend
|
||||
model.Remark = s.Remark
|
||||
|
||||
}
|
||||
|
||||
// GetId 获取数据对应的ID
|
||||
func (s *SysConfigControl) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// GetSetSysConfigReq 增、改使用的结构体
|
||||
type GetSetSysConfigReq struct {
|
||||
ConfigKey string `json:"configKey" comment:""`
|
||||
ConfigValue string `json:"configValue" comment:""`
|
||||
}
|
||||
|
||||
// Generate 结构体数据转化 从 SysConfigControl 至 system.SysConfig 对应的模型
|
||||
func (s *GetSetSysConfigReq) Generate(model *models.SysConfig) {
|
||||
model.ConfigValue = s.ConfigValue
|
||||
}
|
||||
|
||||
type UpdateSetSysConfigReq map[string]string
|
||||
|
||||
// SysConfigByKeyReq 根据Key获取配置
|
||||
type SysConfigByKeyReq struct {
|
||||
ConfigKey string `uri:"configKey" search:"type:contains;column:config_key;table:sys_config"`
|
||||
}
|
||||
|
||||
func (m *SysConfigByKeyReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type GetSysConfigByKEYForServiceResp struct {
|
||||
ConfigKey string `json:"configKey" comment:""`
|
||||
ConfigValue string `json:"configValue" comment:""`
|
||||
}
|
||||
|
||||
type SysConfigGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysConfigGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysConfigDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysConfigDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
// SysDeptGetPageReq 列表或者搜索使用结构体
|
||||
type SysDeptGetPageReq struct {
|
||||
DeptId int `form:"deptId" search:"type:exact;column:dept_id;table:sys_dept" comment:"id"` //id
|
||||
ParentId int `form:"parentId" search:"type:exact;column:parent_id;table:sys_dept" comment:"上级部门"` //上级部门
|
||||
DeptPath string `form:"deptPath" search:"type:exact;column:dept_path;table:sys_dept" comment:""` //路径
|
||||
DeptName string `form:"deptName" search:"type:exact;column:dept_name;table:sys_dept" comment:"部门名称"` //部门名称
|
||||
Sort int `form:"sort" search:"type:exact;column:sort;table:sys_dept" comment:"排序"` //排序
|
||||
Leader string `form:"leader" search:"type:exact;column:leader;table:sys_dept" comment:"负责人"` //负责人
|
||||
Phone string `form:"phone" search:"type:exact;column:phone;table:sys_dept" comment:"手机"` //手机
|
||||
Email string `form:"email" search:"type:exact;column:email;table:sys_dept" comment:"邮箱"` //邮箱
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_dept" comment:"状态"` //状态
|
||||
}
|
||||
|
||||
func (m *SysDeptGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysDeptInsertReq struct {
|
||||
DeptId int `uri:"id" comment:"编码"` // 编码
|
||||
ParentId int `json:"parentId" comment:"上级部门" vd:"?"` //上级部门
|
||||
DeptPath string `json:"deptPath" comment:""` //路径
|
||||
DeptName string `json:"deptName" comment:"部门名称" vd:"len($)>0"` //部门名称
|
||||
Sort int `json:"sort" comment:"排序" vd:"?"` //排序
|
||||
Leader string `json:"leader" comment:"负责人" vd:"@:len($)>0; msg:'leader不能为空'"` //负责人
|
||||
Phone string `json:"phone" comment:"手机" vd:"?"` //手机
|
||||
Email string `json:"email" comment:"邮箱" vd:"?"` //邮箱
|
||||
Status int `json:"status" comment:"状态" vd:"$>0"` //状态
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDeptInsertReq) Generate(model *models.SysDept) {
|
||||
if s.DeptId != 0 {
|
||||
model.DeptId = s.DeptId
|
||||
}
|
||||
model.DeptName = s.DeptName
|
||||
model.ParentId = s.ParentId
|
||||
model.DeptPath = s.DeptPath
|
||||
model.Sort = s.Sort
|
||||
model.Leader = s.Leader
|
||||
model.Phone = s.Phone
|
||||
model.Email = s.Email
|
||||
model.Status = s.Status
|
||||
}
|
||||
|
||||
// GetId 获取数据对应的ID
|
||||
func (s *SysDeptInsertReq) GetId() interface{} {
|
||||
return s.DeptId
|
||||
}
|
||||
|
||||
type SysDeptUpdateReq struct {
|
||||
DeptId int `uri:"id" comment:"编码"` // 编码
|
||||
ParentId int `json:"parentId" comment:"上级部门" vd:"?"` //上级部门
|
||||
DeptPath string `json:"deptPath" comment:""` //路径
|
||||
DeptName string `json:"deptName" comment:"部门名称" vd:"len($)>0"` //部门名称
|
||||
Sort int `json:"sort" comment:"排序" vd:"?"` //排序
|
||||
Leader string `json:"leader" comment:"负责人" vd:"@:len($)>0; msg:'leader不能为空'"` //负责人
|
||||
Phone string `json:"phone" comment:"手机" vd:"?"` //手机
|
||||
Email string `json:"email" comment:"邮箱" vd:"?"` //邮箱
|
||||
Status int `json:"status" comment:"状态" vd:"$>0"` //状态
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
// Generate 结构体数据转化 从 SysDeptControl 至 SysDept 对应的模型
|
||||
func (s *SysDeptUpdateReq) Generate(model *models.SysDept) {
|
||||
if s.DeptId != 0 {
|
||||
model.DeptId = s.DeptId
|
||||
}
|
||||
model.DeptName = s.DeptName
|
||||
model.ParentId = s.ParentId
|
||||
model.DeptPath = s.DeptPath
|
||||
model.Sort = s.Sort
|
||||
model.Leader = s.Leader
|
||||
model.Phone = s.Phone
|
||||
model.Email = s.Email
|
||||
model.Status = s.Status
|
||||
}
|
||||
|
||||
// GetId 获取数据对应的ID
|
||||
func (s *SysDeptUpdateReq) GetId() interface{} {
|
||||
return s.DeptId
|
||||
}
|
||||
|
||||
type SysDeptGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysDeptGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDeptDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *SysDeptDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
|
||||
type DeptLabel struct {
|
||||
Id int `gorm:"-" json:"id"`
|
||||
Label string `gorm:"-" json:"label"`
|
||||
Children []DeptLabel `gorm:"-" json:"children"`
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysDictDataGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Id int `form:"id" search:"type:exact;column:dict_code;table:sys_dict_data" comment:""`
|
||||
DictLabel string `form:"dictLabel" search:"type:contains;column:dict_label;table:sys_dict_data" comment:""`
|
||||
DictValue string `form:"dictValue" search:"type:contains;column:dict_value;table:sys_dict_data" comment:""`
|
||||
DictType string `form:"dictType" search:"type:contains;column:dict_type;table:sys_dict_data" comment:""`
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_dict_data" comment:""`
|
||||
}
|
||||
|
||||
func (m *SysDictDataGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysDictDataGetAllResp struct {
|
||||
DictLabel string `json:"label"`
|
||||
DictValue string `json:"value"`
|
||||
}
|
||||
|
||||
type SysDictDataInsertReq struct {
|
||||
Id int `json:"-" comment:""`
|
||||
DictSort int `json:"dictSort" comment:""`
|
||||
DictLabel string `json:"dictLabel" comment:""`
|
||||
DictValue string `json:"dictValue" comment:""`
|
||||
DictType string `json:"dictType" comment:""`
|
||||
CssClass string `json:"cssClass" comment:""`
|
||||
ListClass string `json:"listClass" comment:""`
|
||||
IsDefault string `json:"isDefault" comment:""`
|
||||
Status int `json:"status" comment:""`
|
||||
Default string `json:"default" comment:""`
|
||||
Remark string `json:"remark" comment:""`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDictDataInsertReq) Generate(model *models.SysDictData) {
|
||||
model.DictCode = s.Id
|
||||
model.DictSort = s.DictSort
|
||||
model.DictLabel = s.DictLabel
|
||||
model.DictValue = s.DictValue
|
||||
model.DictType = s.DictType
|
||||
model.CssClass = s.CssClass
|
||||
model.ListClass = s.ListClass
|
||||
model.IsDefault = s.IsDefault
|
||||
model.Status = s.Status
|
||||
model.Default = s.Default
|
||||
model.Remark = s.Remark
|
||||
}
|
||||
|
||||
func (s *SysDictDataInsertReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictDataUpdateReq struct {
|
||||
Id int `uri:"dictCode" comment:""`
|
||||
DictSort int `json:"dictSort" comment:""`
|
||||
DictLabel string `json:"dictLabel" comment:""`
|
||||
DictValue string `json:"dictValue" comment:""`
|
||||
DictType string `json:"dictType" comment:""`
|
||||
CssClass string `json:"cssClass" comment:""`
|
||||
ListClass string `json:"listClass" comment:""`
|
||||
IsDefault string `json:"isDefault" comment:""`
|
||||
Status int `json:"status" comment:""`
|
||||
Default string `json:"default" comment:""`
|
||||
Remark string `json:"remark" comment:""`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDictDataUpdateReq) Generate(model *models.SysDictData) {
|
||||
model.DictCode = s.Id
|
||||
model.DictSort = s.DictSort
|
||||
model.DictLabel = s.DictLabel
|
||||
model.DictValue = s.DictValue
|
||||
model.DictType = s.DictType
|
||||
model.CssClass = s.CssClass
|
||||
model.ListClass = s.ListClass
|
||||
model.IsDefault = s.IsDefault
|
||||
model.Status = s.Status
|
||||
model.Default = s.Default
|
||||
model.Remark = s.Remark
|
||||
}
|
||||
|
||||
func (s *SysDictDataUpdateReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictDataGetReq struct {
|
||||
Id int `uri:"dictCode"`
|
||||
}
|
||||
|
||||
func (s *SysDictDataGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictDataDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
common.ControlBy `json:"-"`
|
||||
}
|
||||
|
||||
func (s *SysDictDataDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysDictTypeGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
DictId []int `form:"dictId" search:"type:in;column:dict_id;table:sys_dict_type"`
|
||||
DictName string `form:"dictName" search:"type:icontains;column:dict_name;table:sys_dict_type"`
|
||||
DictType string `form:"dictType" search:"type:icontains;column:dict_type;table:sys_dict_type"`
|
||||
Status int `form:"status" search:"type:exact;column:status;table:sys_dict_type"`
|
||||
}
|
||||
|
||||
type SysDictTypeOrder struct {
|
||||
DictIdOrder string `search:"type:order;column:dict_id;table:sys_dict_type" form:"dictIdOrder"`
|
||||
}
|
||||
|
||||
func (m *SysDictTypeGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysDictTypeInsertReq struct {
|
||||
Id int `uri:"id"`
|
||||
DictName string `json:"dictName"`
|
||||
DictType string `json:"dictType"`
|
||||
Status int `json:"status"`
|
||||
Remark string `json:"remark"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDictTypeInsertReq) Generate(model *models.SysDictType) {
|
||||
if s.Id != 0 {
|
||||
model.ID = s.Id
|
||||
}
|
||||
model.DictName = s.DictName
|
||||
model.DictType = s.DictType
|
||||
model.Status = s.Status
|
||||
model.Remark = s.Remark
|
||||
|
||||
}
|
||||
|
||||
func (s *SysDictTypeInsertReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictTypeUpdateReq struct {
|
||||
Id int `uri:"id"`
|
||||
DictName string `json:"dictName"`
|
||||
DictType string `json:"dictType"`
|
||||
Status int `json:"status"`
|
||||
Remark string `json:"remark"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDictTypeUpdateReq) Generate(model *models.SysDictType) {
|
||||
if s.Id != 0 {
|
||||
model.ID = s.Id
|
||||
}
|
||||
model.DictName = s.DictName
|
||||
model.DictType = s.DictType
|
||||
model.Status = s.Status
|
||||
model.Remark = s.Remark
|
||||
|
||||
}
|
||||
|
||||
func (s *SysDictTypeUpdateReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictTypeGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysDictTypeGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysDictTypeDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysDictTypeDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-admin/common/dto"
|
||||
)
|
||||
|
||||
type SysLoginLogGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Username string `form:"username" search:"type:exact;column:username;table:sys_login_log" comment:"用户名"`
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_login_log" comment:"状态"`
|
||||
Ipaddr string `form:"ipaddr" search:"type:exact;column:ipaddr;table:sys_login_log" comment:"ip地址"`
|
||||
LoginLocation string `form:"loginLocation" search:"type:exact;column:login_location;table:sys_login_log" comment:"归属地"`
|
||||
BeginTime string `form:"beginTime" search:"type:gte;column:ctime;table:sys_login_log" comment:"创建时间"`
|
||||
EndTime string `form:"endTime" search:"type:lte;column:ctime;table:sys_login_log" comment:"创建时间"`
|
||||
SysLoginLogOrder
|
||||
}
|
||||
|
||||
type SysLoginLogOrder struct {
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_login_log" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
func (m *SysLoginLogGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysLoginLogControl struct {
|
||||
ID int `uri:"Id" comment:"主键"` // 主键
|
||||
Username string `json:"username" comment:"用户名"`
|
||||
Status string `json:"status" comment:"状态"`
|
||||
Ipaddr string `json:"ipaddr" comment:"ip地址"`
|
||||
LoginLocation string `json:"loginLocation" comment:"归属地"`
|
||||
Browser string `json:"browser" comment:"浏览器"`
|
||||
Os string `json:"os" comment:"系统"`
|
||||
Platform string `json:"platform" comment:"固件"`
|
||||
LoginTime time.Time `json:"loginTime" comment:"登录时间"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
Msg string `json:"msg" comment:"信息"`
|
||||
}
|
||||
|
||||
type SysLoginLogGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysLoginLogGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysLoginLogDeleteReq 功能删除请求参数
|
||||
type SysLoginLogDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *SysLoginLogDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
common "go-admin/common/models"
|
||||
|
||||
"go-admin/common/dto"
|
||||
)
|
||||
|
||||
// SysMenuGetPageReq 列表或者搜索使用结构体
|
||||
type SysMenuGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Title string `form:"title" search:"type:contains;column:title;table:sys_menu" comment:"菜单名称"` // 菜单名称
|
||||
Visible int `form:"visible" search:"type:exact;column:visible;table:sys_menu" comment:"显示状态"` // 显示状态
|
||||
}
|
||||
|
||||
func (m *SysMenuGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysMenuInsertReq struct {
|
||||
MenuId int `uri:"id" comment:"编码"` // 编码
|
||||
MenuName string `form:"menuName" comment:"菜单name"` //菜单name
|
||||
Title string `form:"title" comment:"显示名称"` //显示名称
|
||||
Icon string `form:"icon" comment:"图标"` //图标
|
||||
Path string `form:"path" comment:"路径"` //路径
|
||||
Paths string `form:"paths" comment:"id路径"` //id路径
|
||||
MenuType string `form:"menuType" comment:"菜单类型"` //菜单类型
|
||||
SysApi []models.SysApi `form:"sysApi"`
|
||||
Apis []int `form:"apis"`
|
||||
Action string `form:"action" comment:"请求方式"` //请求方式
|
||||
Permission string `form:"permission" comment:"权限编码"` //权限编码
|
||||
ParentId int `form:"parentId" comment:"上级菜单"` //上级菜单
|
||||
NoCache bool `form:"noCache" comment:"是否缓存"` //是否缓存
|
||||
Breadcrumb string `form:"breadcrumb" comment:"是否面包屑"` //是否面包屑
|
||||
Component string `form:"component" comment:"组件"` //组件
|
||||
Sort int `form:"sort" comment:"排序"` //排序
|
||||
Visible string `form:"visible" comment:"是否显示"` //是否显示
|
||||
IsFrame string `form:"isFrame" comment:"是否frame"` //是否frame
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysMenuInsertReq) Generate(model *models.SysMenu) {
|
||||
if s.MenuId != 0 {
|
||||
model.MenuId = s.MenuId
|
||||
}
|
||||
model.MenuName = s.MenuName
|
||||
model.Title = s.Title
|
||||
model.Icon = s.Icon
|
||||
model.Path = s.Path
|
||||
model.Paths = s.Paths
|
||||
model.MenuType = s.MenuType
|
||||
model.Action = s.Action
|
||||
model.SysApi = s.SysApi
|
||||
model.Permission = s.Permission
|
||||
model.ParentId = s.ParentId
|
||||
model.NoCache = s.NoCache
|
||||
model.Breadcrumb = s.Breadcrumb
|
||||
model.Component = s.Component
|
||||
model.Sort = s.Sort
|
||||
model.Visible = s.Visible
|
||||
model.IsFrame = s.IsFrame
|
||||
if s.CreateBy != 0 {
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
if s.UpdateBy != 0 {
|
||||
model.UpdateBy = s.UpdateBy
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SysMenuInsertReq) GetId() interface{} {
|
||||
return s.MenuId
|
||||
}
|
||||
|
||||
type SysMenuUpdateReq struct {
|
||||
MenuId int `uri:"id" comment:"编码"` // 编码
|
||||
MenuName string `form:"menuName" comment:"菜单name"` //菜单name
|
||||
Title string `form:"title" comment:"显示名称"` //显示名称
|
||||
Icon string `form:"icon" comment:"图标"` //图标
|
||||
Path string `form:"path" comment:"路径"` //路径
|
||||
Paths string `form:"paths" comment:"id路径"` //id路径
|
||||
MenuType string `form:"menuType" comment:"菜单类型"` //菜单类型
|
||||
SysApi []models.SysApi `form:"sysApi"`
|
||||
Apis []int `form:"apis"`
|
||||
Action string `form:"action" comment:"请求方式"` //请求方式
|
||||
Permission string `form:"permission" comment:"权限编码"` //权限编码
|
||||
ParentId int `form:"parentId" comment:"上级菜单"` //上级菜单
|
||||
NoCache bool `form:"noCache" comment:"是否缓存"` //是否缓存
|
||||
Breadcrumb string `form:"breadcrumb" comment:"是否面包屑"` //是否面包屑
|
||||
Component string `form:"component" comment:"组件"` //组件
|
||||
Sort int `form:"sort" comment:"排序"` //排序
|
||||
Visible string `form:"visible" comment:"是否显示"` //是否显示
|
||||
IsFrame string `form:"isFrame" comment:"是否frame"` //是否frame
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysMenuUpdateReq) Generate(model *models.SysMenu) {
|
||||
if s.MenuId != 0 {
|
||||
model.MenuId = s.MenuId
|
||||
}
|
||||
model.MenuName = s.MenuName
|
||||
model.Title = s.Title
|
||||
model.Icon = s.Icon
|
||||
model.Path = s.Path
|
||||
model.Paths = s.Paths
|
||||
model.MenuType = s.MenuType
|
||||
model.Action = s.Action
|
||||
model.SysApi = s.SysApi
|
||||
model.Permission = s.Permission
|
||||
model.ParentId = s.ParentId
|
||||
model.NoCache = s.NoCache
|
||||
model.Breadcrumb = s.Breadcrumb
|
||||
model.Component = s.Component
|
||||
model.Sort = s.Sort
|
||||
model.Visible = s.Visible
|
||||
model.IsFrame = s.IsFrame
|
||||
if s.CreateBy != 0 {
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
if s.UpdateBy != 0 {
|
||||
model.UpdateBy = s.UpdateBy
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SysMenuUpdateReq) GetId() interface{} {
|
||||
return s.MenuId
|
||||
}
|
||||
|
||||
type SysMenuGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysMenuGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysMenuDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysMenuDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
|
||||
type MenuLabel struct {
|
||||
Id int `json:"id,omitempty" gorm:"-"`
|
||||
Label string `json:"label,omitempty" gorm:"-"`
|
||||
Children []MenuLabel `json:"children,omitempty" gorm:"-"`
|
||||
}
|
||||
|
||||
type MenuRole struct {
|
||||
models.SysMenu
|
||||
IsSelect bool `json:"is_select" gorm:"-"`
|
||||
}
|
||||
|
||||
type SelectRole struct {
|
||||
RoleId int `uri:"roleId"`
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
const (
|
||||
OperaStatusEnabel = "1" // 状态-正常
|
||||
OperaStatusDisable = "2" // 状态-关闭
|
||||
)
|
||||
|
||||
type SysOperaLogGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Title string `form:"title" search:"type:contains;column:title;table:sys_opera_log" comment:"操作模块"`
|
||||
Method string `form:"method" search:"type:contains;column:method;table:sys_opera_log" comment:"函数"`
|
||||
RequestMethod string `form:"requestMethod" search:"type:contains;column:request_method;table:sys_opera_log" comment:"请求方式: GET POST PUT DELETE"`
|
||||
OperUrl string `form:"operUrl" search:"type:contains;column:oper_url;table:sys_opera_log" comment:"访问地址"`
|
||||
OperIp string `form:"operIp" search:"type:exact;column:oper_ip;table:sys_opera_log" comment:"客户端ip"`
|
||||
Status int `form:"status" search:"type:exact;column:status;table:sys_opera_log" comment:"状态 1:正常 2:关闭"`
|
||||
BeginTime string `form:"beginTime" search:"type:gte;column:created_at;table:sys_opera_log" comment:"创建时间"`
|
||||
EndTime string `form:"endTime" search:"type:lte;column:created_at;table:sys_opera_log" comment:"更新时间"`
|
||||
SysOperaLogOrder
|
||||
}
|
||||
|
||||
type SysOperaLogOrder struct {
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_opera_log" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
func (m *SysOperaLogGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysOperaLogControl struct {
|
||||
ID int `uri:"Id" comment:"编码"` // 编码
|
||||
Title string `json:"title" comment:"操作模块"`
|
||||
BusinessType string `json:"businessType" comment:"操作类型"`
|
||||
BusinessTypes string `json:"businessTypes" comment:""`
|
||||
Method string `json:"method" comment:"函数"`
|
||||
RequestMethod string `json:"requestMethod" comment:"请求方式"`
|
||||
OperatorType string `json:"operatorType" comment:"操作类型"`
|
||||
OperName string `json:"operName" comment:"操作者"`
|
||||
DeptName string `json:"deptName" comment:"部门名称"`
|
||||
OperUrl string `json:"operUrl" comment:"访问地址"`
|
||||
OperIp string `json:"operIp" comment:"客户端ip"`
|
||||
OperLocation string `json:"operLocation" comment:"访问位置"`
|
||||
OperParam string `json:"operParam" comment:"请求参数"`
|
||||
Status string `json:"status" comment:"操作状态"`
|
||||
OperTime time.Time `json:"operTime" comment:"操作时间"`
|
||||
JsonResult string `json:"jsonResult" comment:"返回数据"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
LatencyTime string `json:"latencyTime" comment:"耗时"`
|
||||
UserAgent string `json:"userAgent" comment:"ua"`
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) Generate() (*models.SysOperaLog, error) {
|
||||
return &models.SysOperaLog{
|
||||
Model: common.Model{Id: s.ID},
|
||||
Title: s.Title,
|
||||
BusinessType: s.BusinessType,
|
||||
BusinessTypes: s.BusinessTypes,
|
||||
Method: s.Method,
|
||||
RequestMethod: s.RequestMethod,
|
||||
OperatorType: s.OperatorType,
|
||||
OperName: s.OperName,
|
||||
DeptName: s.DeptName,
|
||||
OperUrl: s.OperUrl,
|
||||
OperIp: s.OperIp,
|
||||
OperLocation: s.OperLocation,
|
||||
OperParam: s.OperParam,
|
||||
Status: s.Status,
|
||||
OperTime: s.OperTime,
|
||||
JsonResult: s.JsonResult,
|
||||
Remark: s.Remark,
|
||||
LatencyTime: s.LatencyTime,
|
||||
UserAgent: s.UserAgent,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysOperaLogGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysOperaLogGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysOperaLogDeleteReq 功能删除请求参数
|
||||
type SysOperaLogDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *SysOperaLogDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
common "go-admin/common/models"
|
||||
|
||||
"go-admin/common/dto"
|
||||
)
|
||||
|
||||
// SysPostPageReq 列表或者搜索使用结构体
|
||||
type SysPostPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
PostId int `form:"postId" search:"type:exact;column:post_id;table:sys_post" comment:"id"` // id
|
||||
PostName string `form:"postName" search:"type:contains;column:post_name;table:sys_post" comment:"名称"` // 名称
|
||||
PostCode string `form:"postCode" search:"type:contains;column:post_code;table:sys_post" comment:"编码"` // 编码
|
||||
Sort int `form:"sort" search:"type:exact;column:sort;table:sys_post" comment:"排序"` // 排序
|
||||
Status int `form:"status" search:"type:exact;column:status;table:sys_post" comment:"状态"` // 状态
|
||||
Remark string `form:"remark" search:"type:exact;column:remark;table:sys_post" comment:"备注"` // 备注
|
||||
}
|
||||
|
||||
func (m *SysPostPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
// SysPostInsertReq 增使用的结构体
|
||||
type SysPostInsertReq struct {
|
||||
PostId int `uri:"id" comment:"id"`
|
||||
PostName string `form:"postName" comment:"名称"`
|
||||
PostCode string `form:"postCode" comment:"编码"`
|
||||
Sort int `form:"sort" comment:"排序"`
|
||||
Status int `form:"status" comment:"状态"`
|
||||
Remark string `form:"remark" comment:"备注"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysPostInsertReq) Generate(model *models.SysPost) {
|
||||
model.PostName = s.PostName
|
||||
model.PostCode = s.PostCode
|
||||
model.Sort = s.Sort
|
||||
model.Status = s.Status
|
||||
model.Remark = s.Remark
|
||||
if s.ControlBy.UpdateBy != 0 {
|
||||
model.UpdateBy = s.UpdateBy
|
||||
}
|
||||
if s.ControlBy.CreateBy != 0 {
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
}
|
||||
|
||||
// GetId 获取数据对应的ID
|
||||
func (s *SysPostInsertReq) GetId() interface{} {
|
||||
return s.PostId
|
||||
}
|
||||
|
||||
// SysPostUpdateReq 改使用的结构体
|
||||
type SysPostUpdateReq struct {
|
||||
PostId int `uri:"id" comment:"id"`
|
||||
PostName string `form:"postName" comment:"名称"`
|
||||
PostCode string `form:"postCode" comment:"编码"`
|
||||
Sort int `form:"sort" comment:"排序"`
|
||||
Status int `form:"status" comment:"状态"`
|
||||
Remark string `form:"remark" comment:"备注"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysPostUpdateReq) Generate(model *models.SysPost) {
|
||||
model.PostId = s.PostId
|
||||
model.PostName = s.PostName
|
||||
model.PostCode = s.PostCode
|
||||
model.Sort = s.Sort
|
||||
model.Status = s.Status
|
||||
model.Remark = s.Remark
|
||||
if s.ControlBy.UpdateBy != 0 {
|
||||
model.UpdateBy = s.UpdateBy
|
||||
}
|
||||
if s.ControlBy.CreateBy != 0 {
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SysPostUpdateReq) GetId() interface{} {
|
||||
return s.PostId
|
||||
}
|
||||
|
||||
// SysPostGetReq 获取单个的结构体
|
||||
type SysPostGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysPostGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
// SysPostDeleteReq 删除的结构体
|
||||
type SysPostDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysPostDeleteReq) Generate(model *models.SysPost) {
|
||||
if s.ControlBy.UpdateBy != 0 {
|
||||
model.UpdateBy = s.UpdateBy
|
||||
}
|
||||
if s.ControlBy.CreateBy != 0 {
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SysPostDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
common "go-admin/common/models"
|
||||
|
||||
"go-admin/common/dto"
|
||||
)
|
||||
|
||||
type SysRoleGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
|
||||
RoleId int `form:"roleId" search:"type:exact;column:role_id;table:sys_role" comment:"角色编码"` // 角色编码
|
||||
RoleName string `form:"roleName" search:"type:exact;column:role_name;table:sys_role" comment:"角色名称"` // 角色名称
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_role" comment:"状态"` // 状态
|
||||
RoleKey string `form:"roleKey" search:"type:exact;column:role_key;table:sys_role" comment:"角色代码"` // 角色代码
|
||||
RoleSort int `form:"roleSort" search:"type:exact;column:role_sort;table:sys_role" comment:"角色排序"` // 角色排序
|
||||
Flag string `form:"flag" search:"type:exact;column:flag;table:sys_role" comment:"标记"` // 标记
|
||||
Remark string `form:"remark" search:"type:exact;column:remark;table:sys_role" comment:"备注"` // 备注
|
||||
Admin bool `form:"admin" search:"type:exact;column:admin;table:sys_role" comment:"是否管理员"`
|
||||
DataScope string `form:"dataScope" search:"type:exact;column:data_scope;table:sys_role" comment:"是否管理员"`
|
||||
}
|
||||
|
||||
type SysRoleOrder struct {
|
||||
RoleIdOrder string `search:"type:order;column:role_id;table:sys_role" form:"roleIdOrder"`
|
||||
RoleNameOrder string `search:"type:order;column:role_name;table:sys_role" form:"roleNameOrder"`
|
||||
RoleSortOrder string `search:"type:order;column:role_sort;table:sys_role" form:"usernameOrder"`
|
||||
StatusOrder string `search:"type:order;column:status;table:sys_role" form:"statusOrder"`
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_role" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
func (m *SysRoleGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type SysRoleInsertReq struct {
|
||||
RoleId int `uri:"id" comment:"角色编码"` // 角色编码
|
||||
RoleName string `form:"roleName" comment:"角色名称"` // 角色名称
|
||||
Status string `form:"status" comment:"状态"` // 状态 1禁用 2正常
|
||||
RoleKey string `form:"roleKey" comment:"角色代码"` // 角色代码
|
||||
RoleSort int `form:"roleSort" comment:"角色排序"` // 角色排序
|
||||
Flag string `form:"flag" comment:"标记"` // 标记
|
||||
Remark string `form:"remark" comment:"备注"` // 备注
|
||||
Admin bool `form:"admin" comment:"是否管理员"`
|
||||
DataScope string `form:"dataScope"`
|
||||
SysMenu []models.SysMenu `form:"sysMenu"`
|
||||
MenuIds []int `form:"menuIds"`
|
||||
SysDept []models.SysDept `form:"sysDept"`
|
||||
DeptIds []int `form:"deptIds"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysRoleInsertReq) Generate(model *models.SysRole) {
|
||||
if s.RoleId != 0 {
|
||||
model.RoleId = s.RoleId
|
||||
}
|
||||
model.RoleName = s.RoleName
|
||||
model.Status = s.Status
|
||||
model.RoleKey = s.RoleKey
|
||||
model.RoleSort = s.RoleSort
|
||||
model.Flag = s.Flag
|
||||
model.Remark = s.Remark
|
||||
model.Admin = s.Admin
|
||||
model.DataScope = s.DataScope
|
||||
model.SysMenu = &s.SysMenu
|
||||
model.SysDept = s.SysDept
|
||||
}
|
||||
|
||||
func (s *SysRoleInsertReq) GetId() interface{} {
|
||||
return s.RoleId
|
||||
}
|
||||
|
||||
type SysRoleUpdateReq struct {
|
||||
RoleId int `uri:"id" comment:"角色编码"` // 角色编码
|
||||
RoleName string `form:"roleName" comment:"角色名称"` // 角色名称
|
||||
Status string `form:"status" comment:"状态"` // 状态
|
||||
RoleKey string `form:"roleKey" comment:"角色代码"` // 角色代码
|
||||
RoleSort int `form:"roleSort" comment:"角色排序"` // 角色排序
|
||||
Flag string `form:"flag" comment:"标记"` // 标记
|
||||
Remark string `form:"remark" comment:"备注"` // 备注
|
||||
Admin bool `form:"admin" comment:"是否管理员"`
|
||||
DataScope string `form:"dataScope"`
|
||||
SysMenu []models.SysMenu `form:"sysMenu"`
|
||||
MenuIds []int `form:"menuIds"`
|
||||
SysDept []models.SysDept `form:"sysDept"`
|
||||
DeptIds []int `form:"deptIds"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysRoleUpdateReq) Generate(model *models.SysRole) {
|
||||
if s.RoleId != 0 {
|
||||
model.RoleId = s.RoleId
|
||||
}
|
||||
model.RoleName = s.RoleName
|
||||
model.Status = s.Status
|
||||
model.RoleKey = s.RoleKey
|
||||
model.RoleSort = s.RoleSort
|
||||
model.Flag = s.Flag
|
||||
model.Remark = s.Remark
|
||||
model.Admin = s.Admin
|
||||
model.DataScope = s.DataScope
|
||||
model.SysMenu = &s.SysMenu
|
||||
model.SysDept = s.SysDept
|
||||
}
|
||||
|
||||
func (s *SysRoleUpdateReq) GetId() interface{} {
|
||||
return s.RoleId
|
||||
}
|
||||
|
||||
type UpdateStatusReq struct {
|
||||
RoleId int `form:"roleId" comment:"角色编码"` // 角色编码
|
||||
Status string `form:"status" comment:"状态"` // 状态
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *UpdateStatusReq) Generate(model *models.SysRole) {
|
||||
if s.RoleId != 0 {
|
||||
model.RoleId = s.RoleId
|
||||
}
|
||||
model.Status = s.Status
|
||||
}
|
||||
|
||||
func (s *UpdateStatusReq) GetId() interface{} {
|
||||
return s.RoleId
|
||||
}
|
||||
|
||||
type SysRoleByName struct {
|
||||
RoleName string `form:"role"` // 角色编码
|
||||
}
|
||||
|
||||
type SysRoleGetReq struct {
|
||||
Id int `uri:"id"`
|
||||
}
|
||||
|
||||
func (s *SysRoleGetReq) GetId() interface{} {
|
||||
return s.Id
|
||||
}
|
||||
|
||||
type SysRoleDeleteReq struct {
|
||||
Ids []int `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *SysRoleDeleteReq) GetId() interface{} {
|
||||
return s.Ids
|
||||
}
|
||||
|
||||
// RoleDataScopeReq 角色数据权限修改
|
||||
type RoleDataScopeReq struct {
|
||||
RoleId int `json:"roleId" binding:"required"`
|
||||
DataScope string `json:"dataScope" binding:"required"`
|
||||
DeptIds []int `json:"deptIds"`
|
||||
}
|
||||
|
||||
func (s *RoleDataScopeReq) Generate(model *models.SysRole) {
|
||||
if s.RoleId != 0 {
|
||||
model.RoleId = s.RoleId
|
||||
}
|
||||
model.DataScope = s.DataScope
|
||||
model.DeptIds = s.DeptIds
|
||||
}
|
||||
|
||||
type DeptIdList struct {
|
||||
DeptId int `json:"DeptId"`
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
"go-admin/common/dto"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysUserGetPageReq struct {
|
||||
dto.Pagination `search:"-"`
|
||||
UserId int `form:"userId" search:"type:exact;column:user_id;table:sys_user" comment:"用户ID"`
|
||||
Username string `form:"username" search:"type:contains;column:username;table:sys_user" comment:"用户名"`
|
||||
NickName string `form:"nickName" search:"type:contains;column:nick_name;table:sys_user" comment:"昵称"`
|
||||
Phone string `form:"phone" search:"type:contains;column:phone;table:sys_user" comment:"手机号"`
|
||||
RoleId string `form:"roleId" search:"type:exact;column:role_id;table:sys_user" comment:"角色ID"`
|
||||
Sex string `form:"sex" search:"type:exact;column:sex;table:sys_user" comment:"性别"`
|
||||
Email string `form:"email" search:"type:contains;column:email;table:sys_user" comment:"邮箱"`
|
||||
PostId string `form:"postId" search:"type:exact;column:post_id;table:sys_user" comment:"岗位"`
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_user" comment:"状态"`
|
||||
DeptJoin `search:"type:left;on:dept_id:dept_id;table:sys_user;join:sys_dept"`
|
||||
SysUserOrder
|
||||
}
|
||||
|
||||
type SysUserOrder struct {
|
||||
UserIdOrder string `search:"type:order;column:user_id;table:sys_user" form:"userIdOrder"`
|
||||
UsernameOrder string `search:"type:order;column:username;table:sys_user" form:"usernameOrder"`
|
||||
StatusOrder string `search:"type:order;column:status;table:sys_user" form:"statusOrder"`
|
||||
CreatedAtOrder string `search:"type:order;column:created_at;table:sys_user" form:"createdAtOrder"`
|
||||
}
|
||||
|
||||
type DeptJoin struct {
|
||||
DeptId string `search:"type:contains;column:dept_path;table:sys_dept" form:"deptId"`
|
||||
}
|
||||
|
||||
func (m *SysUserGetPageReq) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
type ResetSysUserPwdReq struct {
|
||||
UserId int `json:"userId" comment:"用户ID" vd:"$>0"` // 用户ID
|
||||
Password string `json:"password" comment:"密码" vd:"len($)>0"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *ResetSysUserPwdReq) GetId() interface{} {
|
||||
return s.UserId
|
||||
}
|
||||
|
||||
func (s *ResetSysUserPwdReq) Generate(model *models.SysUser) {
|
||||
if s.UserId != 0 {
|
||||
model.UserId = s.UserId
|
||||
}
|
||||
model.Password = s.Password
|
||||
}
|
||||
|
||||
type UpdateSysUserAvatarReq struct {
|
||||
UserId int `json:"userId" comment:"用户ID" vd:"len($)>0"` // 用户ID
|
||||
Avatar string `json:"avatar" comment:"头像" vd:"len($)>0"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *UpdateSysUserAvatarReq) GetId() interface{} {
|
||||
return s.UserId
|
||||
}
|
||||
|
||||
func (s *UpdateSysUserAvatarReq) Generate(model *models.SysUser) {
|
||||
if s.UserId != 0 {
|
||||
model.UserId = s.UserId
|
||||
}
|
||||
model.Avatar = s.Avatar
|
||||
}
|
||||
|
||||
type UpdateSysUserStatusReq struct {
|
||||
UserId int `json:"userId" comment:"用户ID" vd:"$>0"` // 用户ID
|
||||
Status string `json:"status" comment:"状态" vd:"len($)>0"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *UpdateSysUserStatusReq) GetId() interface{} {
|
||||
return s.UserId
|
||||
}
|
||||
|
||||
func (s *UpdateSysUserStatusReq) Generate(model *models.SysUser) {
|
||||
if s.UserId != 0 {
|
||||
model.UserId = s.UserId
|
||||
}
|
||||
model.Status = s.Status
|
||||
}
|
||||
|
||||
type SysUserInsertReq struct {
|
||||
UserId int `json:"userId" comment:"用户ID"` // 用户ID
|
||||
Username string `json:"username" comment:"用户名" vd:"len($)>0"`
|
||||
Password string `json:"password" comment:"密码"`
|
||||
NickName string `json:"nickName" comment:"昵称" vd:"len($)>0"`
|
||||
Phone string `json:"phone" comment:"手机号" vd:"len($)>0"`
|
||||
RoleId int `json:"roleId" comment:"角色ID"`
|
||||
Avatar string `json:"avatar" comment:"头像"`
|
||||
Sex string `json:"sex" comment:"性别"`
|
||||
Email string `json:"email" comment:"邮箱" vd:"len($)>0,email"`
|
||||
DeptId int `json:"deptId" comment:"部门" vd:"$>0"`
|
||||
PostId int `json:"postId" comment:"岗位"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
Status string `json:"status" comment:"状态" vd:"len($)>0" default:"1"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysUserInsertReq) Generate(model *models.SysUser) {
|
||||
if s.UserId != 0 {
|
||||
model.UserId = s.UserId
|
||||
}
|
||||
model.Username = s.Username
|
||||
model.Password = s.Password
|
||||
model.NickName = s.NickName
|
||||
model.Phone = s.Phone
|
||||
model.RoleId = s.RoleId
|
||||
model.Avatar = s.Avatar
|
||||
model.Sex = s.Sex
|
||||
model.Email = s.Email
|
||||
model.DeptId = s.DeptId
|
||||
model.PostId = s.PostId
|
||||
model.Remark = s.Remark
|
||||
model.Status = s.Status
|
||||
model.CreateBy = s.CreateBy
|
||||
}
|
||||
|
||||
func (s *SysUserInsertReq) GetId() interface{} {
|
||||
return s.UserId
|
||||
}
|
||||
|
||||
type SysUserUpdateReq struct {
|
||||
UserId int `json:"userId" comment:"用户ID"` // 用户ID
|
||||
Username string `json:"username" comment:"用户名" vd:"len($)>0"`
|
||||
NickName string `json:"nickName" comment:"昵称" vd:"len($)>0"`
|
||||
Phone string `json:"phone" comment:"手机号" vd:"len($)>0"`
|
||||
RoleId int `json:"roleId" comment:"角色ID"`
|
||||
Avatar string `json:"avatar" comment:"头像"`
|
||||
Sex string `json:"sex" comment:"性别"`
|
||||
Email string `json:"email" comment:"邮箱" vd:"len($)>0,email"`
|
||||
DeptId int `json:"deptId" comment:"部门" vd:"$>0"`
|
||||
PostId int `json:"postId" comment:"岗位"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
Status string `json:"status" comment:"状态" default:"1"`
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysUserUpdateReq) Generate(model *models.SysUser) {
|
||||
if s.UserId != 0 {
|
||||
model.UserId = s.UserId
|
||||
}
|
||||
model.Username = s.Username
|
||||
model.NickName = s.NickName
|
||||
model.Phone = s.Phone
|
||||
model.RoleId = s.RoleId
|
||||
model.Avatar = s.Avatar
|
||||
model.Sex = s.Sex
|
||||
model.Email = s.Email
|
||||
model.DeptId = s.DeptId
|
||||
model.PostId = s.PostId
|
||||
model.Remark = s.Remark
|
||||
model.Status = s.Status
|
||||
}
|
||||
|
||||
func (s *SysUserUpdateReq) GetId() interface{} {
|
||||
return s.UserId
|
||||
}
|
||||
|
||||
type SysUserById struct {
|
||||
dto.ObjectById
|
||||
common.ControlBy
|
||||
}
|
||||
|
||||
func (s *SysUserById) GetId() interface{} {
|
||||
if len(s.Ids) > 0 {
|
||||
s.Ids = append(s.Ids, s.Id)
|
||||
return s.Ids
|
||||
}
|
||||
return s.Id
|
||||
}
|
||||
|
||||
func (s *SysUserById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysUser{}, nil
|
||||
}
|
||||
|
||||
// PassWord 密码
|
||||
type PassWord struct {
|
||||
NewPassword string `json:"newPassword" vd:"len($)>0"`
|
||||
OldPassword string `json:"oldPassword" vd:"len($)>0"`
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/runtime"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
cDto "go-admin/common/dto"
|
||||
"go-admin/common/global"
|
||||
)
|
||||
|
||||
type SysApi struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取SysApi列表
|
||||
func (e *SysApi) GetPage(c *dto.SysApiGetPageReq, p *actions.DataPermission, list *[]models.SysApi, count *int64) error {
|
||||
var err error
|
||||
var data models.SysApi
|
||||
|
||||
orm := e.Orm.Debug().Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
actions.Permission(data.TableName(), p),
|
||||
)
|
||||
if c.Type != "" {
|
||||
qType := c.Type
|
||||
if qType == "暂无" {
|
||||
qType = ""
|
||||
}
|
||||
if global.Driver == "postgres" {
|
||||
orm = orm.Where("type = ?", qType)
|
||||
} else {
|
||||
orm = orm.Where("`type` = ?", qType)
|
||||
}
|
||||
|
||||
}
|
||||
err = orm.Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service GetSysApiPage error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 获取SysApi对象with id
|
||||
func (e *SysApi) Get(d *dto.SysApiGetReq, p *actions.DataPermission, model *models.SysApi) *SysApi {
|
||||
var data models.SysApi
|
||||
err := e.Orm.Model(&data).
|
||||
Scopes(
|
||||
actions.Permission(data.TableName(), p),
|
||||
).
|
||||
FirstOrInit(model, d.GetId()).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
_ = e.AddError(err)
|
||||
return e
|
||||
}
|
||||
if model.Id == 0 {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("Service GetSysApi error: %s", err)
|
||||
_ = e.AddError(err)
|
||||
return e
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// Update 修改SysApi对象
|
||||
func (e *SysApi) Update(c *dto.SysApiUpdateReq, p *actions.DataPermission) error {
|
||||
var model = models.SysApi{}
|
||||
db := e.Orm.Debug().First(&model, c.GetId())
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
}
|
||||
c.Generate(&model)
|
||||
db = e.Orm.Save(&model)
|
||||
if err := db.Error; err != nil {
|
||||
e.Log.Errorf("Service UpdateSysApi error:%s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除SysApi
|
||||
func (e *SysApi) Remove(d *dto.SysApiDeleteReq, p *actions.DataPermission) error {
|
||||
var data models.SysApi
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Scopes(
|
||||
actions.Permission(data.TableName(), p),
|
||||
).Delete(&data, d.GetId())
|
||||
if err := db.Error; err != nil {
|
||||
e.Log.Errorf("Service RemoveSysApi error:%s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权删除该数据")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckStorageSysApi 创建SysApi对象
|
||||
func (e *SysApi) CheckStorageSysApi(c *[]runtime.Router) error {
|
||||
for _, v := range *c {
|
||||
err := e.Orm.Debug().Where(models.SysApi{Path: v.RelativePath, Action: v.HttpMethod}).
|
||||
Attrs(models.SysApi{Handle: v.Handler}).
|
||||
FirstOrCreate(&models.SysApi{}).Error
|
||||
if err != nil {
|
||||
err := fmt.Errorf("Service CheckStorageSysApi error: %s \r\n ", err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
cDto "go-admin/common/dto"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取SysConfig列表
|
||||
func (e *SysConfig) GetPage(c *dto.SysConfigGetPageReq, list *[]models.SysConfig, count *int64) error {
|
||||
err := e.Orm.
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 获取SysConfig对象
|
||||
func (e *SysConfig) Get(d *dto.SysConfigGetReq, model *models.SysConfig) error {
|
||||
err := e.Orm.
|
||||
FirstOrInit(model, d.GetId()).
|
||||
Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
_ = e.AddError(err)
|
||||
return err
|
||||
}
|
||||
if model.Id == 0 {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("Service GetSysApi error: %s", err)
|
||||
_ = e.AddError(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Insert 创建SysConfig对象
|
||||
func (e *SysConfig) Insert(c *dto.SysConfigControl) error {
|
||||
var err error
|
||||
var data models.SysConfig
|
||||
c.Generate(&data)
|
||||
err = e.Orm.Create(&data).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service InsertSysConfig error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 修改SysConfig对象
|
||||
func (e *SysConfig) Update(c *dto.SysConfigControl) error {
|
||||
var err error
|
||||
var model = models.SysConfig{}
|
||||
e.Orm.First(&model, c.GetId())
|
||||
c.Generate(&model)
|
||||
db := e.Orm.Save(&model)
|
||||
err = db.Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service UpdateSysConfig error:%s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSysConfig 修改SysConfig对象
|
||||
func (e *SysConfig) SetSysConfig(c *[]dto.GetSetSysConfigReq) error {
|
||||
var err error
|
||||
for _, req := range *c {
|
||||
var model = models.SysConfig{}
|
||||
e.Orm.Where("config_key = ?", req.ConfigKey).First(&model)
|
||||
if model.Id != 0 {
|
||||
req.Generate(&model)
|
||||
db := e.Orm.Save(&model)
|
||||
err = db.Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service SetSysConfig error:%s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetForSet(c *[]dto.GetSetSysConfigReq) error {
|
||||
var err error
|
||||
var data models.SysConfig
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Find(c).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) UpdateForSet(c *[]dto.GetSetSysConfigReq) error {
|
||||
m := *c
|
||||
for _, req := range m {
|
||||
var data models.SysConfig
|
||||
if err := e.Orm.Where("config_key = ?", req.ConfigKey).
|
||||
First(&data).Error; err != nil {
|
||||
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
|
||||
return err
|
||||
}
|
||||
if data.ConfigValue != req.ConfigValue {
|
||||
data.ConfigValue = req.ConfigValue
|
||||
|
||||
if err := e.Orm.Save(&data).Error; err != nil {
|
||||
e.Log.Errorf("Service GetSysConfigPage error:%s", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除SysConfig
|
||||
func (e *SysConfig) Remove(d *dto.SysConfigDeleteReq) error {
|
||||
var err error
|
||||
var data models.SysConfig
|
||||
|
||||
db := e.Orm.Delete(&data, d.Ids)
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("Service RemoveSysConfig error:%s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetWithKey 根据Key获取SysConfig
|
||||
func (e *SysConfig) GetWithKey(c *dto.SysConfigByKeyReq, resp *dto.GetSysConfigByKEYForServiceResp) error {
|
||||
var err error
|
||||
var data models.SysConfig
|
||||
err = e.Orm.Table(data.TableName()).Where("config_key = ?", c.ConfigKey).First(resp).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("At Service GetSysConfigByKEY Error:%s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetWithKeyList(c *dto.SysConfigGetToSysAppReq, list *[]models.SysConfig) error {
|
||||
err := e.Orm.
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
).
|
||||
Find(list).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("Service GetSysConfigByKey error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"go-admin/app/admin/models"
|
||||
|
||||
log "github.com/go-admin-team/go-admin-core/logger"
|
||||
"github.com/go-admin-team/go-admin-core/sdk/pkg"
|
||||
|
||||
"go-admin/app/admin/service/dto"
|
||||
cDto "go-admin/common/dto"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
)
|
||||
|
||||
type SysDept struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取SysDept列表
|
||||
//func (e *SysDept) GetPage(c *dto.SysDeptGetPageReq, list *[]models.SysDept) error {
|
||||
// var err error
|
||||
// var data models.SysDept
|
||||
//
|
||||
// err = e.Orm.Model(&data).
|
||||
// Scopes(
|
||||
// cDto.MakeCondition(c.GetNeedSearch()),
|
||||
// ).
|
||||
// Find(list).Error
|
||||
// if err != nil {
|
||||
// e.Log.Errorf("db error:%s", err)
|
||||
// return err
|
||||
// }
|
||||
// return nil
|
||||
//}
|
||||
|
||||
// Get 获取SysDept对象
|
||||
func (e *SysDept) Get(d *dto.SysDeptGetReq, model *models.SysDept) error {
|
||||
var err error
|
||||
var data models.SysDept
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
FirstOrInit(model, d.GetId()).
|
||||
Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
_ = e.AddError(err)
|
||||
return err
|
||||
}
|
||||
if model.DeptId == 0 {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("Service GetSysApi error: %s", err)
|
||||
_ = e.AddError(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Insert 创建SysDept对象
|
||||
func (e *SysDept) Insert(c *dto.SysDeptInsertReq) error {
|
||||
var err error
|
||||
var data models.SysDept
|
||||
c.Generate(&data)
|
||||
tx := e.Orm.Debug().Begin()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
} else {
|
||||
tx.Commit()
|
||||
}
|
||||
}()
|
||||
err = tx.Create(&data).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
deptPath := pkg.IntToString(data.DeptId) + "/"
|
||||
if data.ParentId != 0 {
|
||||
var deptP models.SysDept
|
||||
tx.First(&deptP, data.ParentId)
|
||||
deptPath = deptP.DeptPath + deptPath
|
||||
} else {
|
||||
deptPath = "/0/" + deptPath
|
||||
}
|
||||
var mp = map[string]string{}
|
||||
mp["dept_path"] = deptPath
|
||||
if err = tx.Model(&data).Update("dept_path", deptPath).Error; err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 修改SysDept对象
|
||||
func (e *SysDept) Update(c *dto.SysDeptUpdateReq) error {
|
||||
var err error
|
||||
var model = models.SysDept{}
|
||||
tx := e.Orm.Debug().Begin()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
} else {
|
||||
tx.Commit()
|
||||
}
|
||||
}()
|
||||
tx.First(&model, c.GetId())
|
||||
c.Generate(&model)
|
||||
|
||||
deptPath := pkg.IntToString(model.DeptId) + "/"
|
||||
if model.ParentId != 0 {
|
||||
var deptP models.SysDept
|
||||
tx.First(&deptP, model.ParentId)
|
||||
deptPath = deptP.DeptPath + deptPath
|
||||
} else {
|
||||
deptPath = "/0/" + deptPath
|
||||
}
|
||||
model.DeptPath = deptPath
|
||||
db := tx.Save(&model)
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("UpdateSysDept error:%s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除SysDept
|
||||
func (e *SysDept) Remove(d *dto.SysDeptDeleteReq) error {
|
||||
var err error
|
||||
var data models.SysDept
|
||||
|
||||
db := e.Orm.Model(&data).Delete(&data, d.GetId())
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("Delete error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSysDeptList 获取组织数据
|
||||
func (e *SysDept) getList(c *dto.SysDeptGetPageReq, list *[]models.SysDept) error {
|
||||
var err error
|
||||
var data models.SysDept
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
).
|
||||
Find(list).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDeptTree 设置组织数据
|
||||
func (e *SysDept) SetDeptTree(c *dto.SysDeptGetPageReq) (m []dto.DeptLabel, err error) {
|
||||
var list []models.SysDept
|
||||
err = e.getList(c, &list)
|
||||
|
||||
m = make([]dto.DeptLabel, 0)
|
||||
for i := 0; i < len(list); i++ {
|
||||
if list[i].ParentId != 0 {
|
||||
continue
|
||||
}
|
||||
e := dto.DeptLabel{}
|
||||
e.Id = list[i].DeptId
|
||||
e.Label = list[i].DeptName
|
||||
deptsInfo := deptTreeCall(&list, e)
|
||||
|
||||
m = append(m, deptsInfo)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Call 递归构造组织数据
|
||||
func deptTreeCall(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
|
||||
list := *deptList
|
||||
childrenList := make([]dto.DeptLabel, 0)
|
||||
for j := 0; j < len(list); j++ {
|
||||
if dept.Id != list[j].ParentId {
|
||||
continue
|
||||
}
|
||||
mi := dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
|
||||
ms := deptTreeCall(deptList, mi)
|
||||
childrenList = append(childrenList, ms)
|
||||
}
|
||||
dept.Children = childrenList
|
||||
return dept
|
||||
}
|
||||
|
||||
// SetDeptPage 设置dept页面数据
|
||||
func (e *SysDept) SetDeptPage(c *dto.SysDeptGetPageReq) (m []models.SysDept, err error) {
|
||||
var list []models.SysDept
|
||||
err = e.getList(c, &list)
|
||||
for i := 0; i < len(list); i++ {
|
||||
if list[i].ParentId != 0 {
|
||||
continue
|
||||
}
|
||||
info := e.deptPageCall(&list, list[i])
|
||||
m = append(m, info)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysDept) deptPageCall(deptlist *[]models.SysDept, menu models.SysDept) models.SysDept {
|
||||
list := *deptlist
|
||||
childrenList := make([]models.SysDept, 0)
|
||||
for j := 0; j < len(list); j++ {
|
||||
if menu.DeptId != list[j].ParentId {
|
||||
continue
|
||||
}
|
||||
mi := models.SysDept{}
|
||||
mi.DeptId = list[j].DeptId
|
||||
mi.ParentId = list[j].ParentId
|
||||
mi.DeptPath = list[j].DeptPath
|
||||
mi.DeptName = list[j].DeptName
|
||||
mi.Sort = list[j].Sort
|
||||
mi.Leader = list[j].Leader
|
||||
mi.Phone = list[j].Phone
|
||||
mi.Email = list[j].Email
|
||||
mi.Status = list[j].Status
|
||||
mi.CreatedAt = list[j].CreatedAt
|
||||
mi.Children = []models.SysDept{}
|
||||
ms := e.deptPageCall(deptlist, mi)
|
||||
childrenList = append(childrenList, ms)
|
||||
}
|
||||
menu.Children = childrenList
|
||||
return menu
|
||||
}
|
||||
|
||||
// GetWithRoleId 获取角色的部门ID集合
|
||||
func (e *SysDept) GetWithRoleId(roleId int) ([]int, error) {
|
||||
deptIds := make([]int, 0)
|
||||
deptList := make([]dto.DeptIdList, 0)
|
||||
if err := e.Orm.Table("sys_role_dept").
|
||||
Select("sys_role_dept.dept_id").
|
||||
Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").
|
||||
Where("role_id = ? ", roleId).
|
||||
Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", roleId).
|
||||
Find(&deptList).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < len(deptList); i++ {
|
||||
deptIds = append(deptIds, deptList[i].DeptId)
|
||||
}
|
||||
return deptIds, nil
|
||||
}
|
||||
|
||||
func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
|
||||
list := make([]models.SysDept, 0)
|
||||
err = e.Orm.Find(&list).Error
|
||||
if err != nil {
|
||||
log.Error("find dept list error, %s", err.Error())
|
||||
return
|
||||
}
|
||||
m = make([]dto.DeptLabel, 0)
|
||||
var item dto.DeptLabel
|
||||
for i := range list {
|
||||
if list[i].ParentId != 0 {
|
||||
continue
|
||||
}
|
||||
item = dto.DeptLabel{}
|
||||
item.Id = list[i].DeptId
|
||||
item.Label = list[i].DeptName
|
||||
deptInfo := deptLabelCall(&list, item)
|
||||
m = append(m, deptInfo)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// deptLabelCall
|
||||
func deptLabelCall(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
|
||||
list := *deptList
|
||||
var mi dto.DeptLabel
|
||||
childrenList := make([]dto.DeptLabel, 0)
|
||||
for j := 0; j < len(list); j++ {
|
||||
if dept.Id != list[j].ParentId {
|
||||
continue
|
||||
}
|
||||
mi = dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
|
||||
ms := deptLabelCall(deptList, mi)
|
||||
childrenList = append(childrenList, ms)
|
||||
}
|
||||
dept.Children = childrenList
|
||||
return dept
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
cDto "go-admin/common/dto"
|
||||
)
|
||||
|
||||
type SysDictData struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取列表
|
||||
func (e *SysDictData) GetPage(c *dto.SysDictDataGetPageReq, list *[]models.SysDictData, count *int64) error {
|
||||
var err error
|
||||
var data models.SysDictData
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 获取对象
|
||||
func (e *SysDictData) Get(d *dto.SysDictDataGetReq, model *models.SysDictData) error {
|
||||
var err error
|
||||
var data models.SysDictData
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Insert 创建对象
|
||||
func (e *SysDictData) Insert(c *dto.SysDictDataInsertReq) error {
|
||||
var err error
|
||||
var data = new(models.SysDictData)
|
||||
c.Generate(data)
|
||||
err = e.Orm.Create(data).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 修改对象
|
||||
func (e *SysDictData) Update(c *dto.SysDictDataUpdateReq) error {
|
||||
var err error
|
||||
var model = models.SysDictData{}
|
||||
e.Orm.First(&model, c.GetId())
|
||||
c.Generate(&model)
|
||||
db := e.Orm.Save(model)
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除
|
||||
func (e *SysDictData) Remove(c *dto.SysDictDataDeleteReq) error {
|
||||
var err error
|
||||
var data models.SysDictData
|
||||
|
||||
db := e.Orm.Delete(&data, c.GetId())
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("Delete error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAll 获取所有
|
||||
func (e *SysDictData) GetAll(c *dto.SysDictDataGetPageReq, list *[]models.SysDictData) error {
|
||||
var err error
|
||||
var data models.SysDictData
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
).
|
||||
Find(list).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
cDto "go-admin/common/dto"
|
||||
)
|
||||
|
||||
type SysDictType struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取列表
|
||||
func (e *SysDictType) GetPage(c *dto.SysDictTypeGetPageReq, list *[]models.SysDictType, count *int64) error {
|
||||
var err error
|
||||
var data models.SysDictType
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 获取对象
|
||||
func (e *SysDictType) Get(d *dto.SysDictTypeGetReq, model *models.SysDictType) error {
|
||||
var err error
|
||||
|
||||
db := e.Orm.First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Insert 创建对象
|
||||
func (e *SysDictType) Insert(c *dto.SysDictTypeInsertReq) error {
|
||||
var err error
|
||||
var data models.SysDictType
|
||||
c.Generate(&data)
|
||||
var count int64
|
||||
e.Orm.Model(&data).Where("dict_type = ?", data.DictType).Count(&count)
|
||||
if count > 0 {
|
||||
return fmt.Errorf("当前字典类型[%s]已经存在!", data.DictType)
|
||||
}
|
||||
err = e.Orm.Create(&data).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 修改对象
|
||||
func (e *SysDictType) Update(c *dto.SysDictTypeUpdateReq) error {
|
||||
var err error
|
||||
var model = models.SysDictType{}
|
||||
e.Orm.First(&model, c.GetId())
|
||||
c.Generate(&model)
|
||||
db := e.Orm.Save(&model)
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除
|
||||
func (e *SysDictType) Remove(d *dto.SysDictTypeDeleteReq) error {
|
||||
var err error
|
||||
var data models.SysDictType
|
||||
|
||||
db := e.Orm.Delete(&data, d.GetId())
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("Delete error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAll 获取所有
|
||||
func (e *SysDictType) GetAll(c *dto.SysDictTypeGetPageReq, list *[]models.SysDictType) error {
|
||||
var err error
|
||||
var data models.SysDictType
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
).
|
||||
Find(list).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/go-admin-team/go-admin-core/sdk/service"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
cDto "go-admin/common/dto"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetPage 获取SysLoginLog列表
|
||||
func (e *SysLoginLog) GetPage(c *dto.SysLoginLogGetPageReq, list *[]models.SysLoginLog, count *int64) error {
|
||||
var err error
|
||||
var data models.SysLoginLog
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 获取SysLoginLog对象
|
||||
func (e *SysLoginLog) Get(d *dto.SysLoginLogGetReq, model *models.SysLoginLog) error {
|
||||
var err error
|
||||
db := e.Orm.First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("db error:%s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove 删除SysLoginLog
|
||||
func (e *SysLoginLog) Remove(c *dto.SysLoginLogDeleteReq) error {
|
||||
var err error
|
||||
var data models.SysLoginLog
|
||||
|
||||
db := e.Orm.Delete(&data, c.GetId())
|
||||
if err = db.Error; err != nil {
|
||||
e.Log.Errorf("Delete error: %s", err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user