Browse Source

init

develop
文武 9 months ago
parent
commit
cdc0c3f2fb
  1. 24
      .gitignore
  2. 5
      .idea/.gitignore
  3. 9
      .idea/admin-api.iml
  4. 8
      .idea/modules.xml
  5. 6
      .idea/vcs.xml
  6. 1
      README.md
  7. 131
      api/admin/application.go
  8. 186
      api/admin/banner.go
  9. 549
      api/admin/bill.go
  10. 162
      api/admin/business.go
  11. 153
      api/admin/category.go
  12. 36
      api/admin/chain.go
  13. 40
      api/admin/dict.go
  14. 61
      api/admin/goods.go
  15. 575
      api/admin/mission.go
  16. 80
      api/admin/order.go
  17. 131
      api/admin/organization.go
  18. 131
      api/admin/provider.go
  19. 181
      api/admin/tags.go
  20. 219
      api/admin/user.go
  21. 48
      api/admin/wallet.go
  22. 130
      api/sys/exa_breakpoint_continue.go
  23. 175
      api/sys/sys_api.go
  24. 140
      api/sys/sys_authority.go
  25. 99
      api/sys/sys_auto_code.go
  26. 37
      api/sys/sys_captcha.go
  27. 54
      api/sys/sys_casbin.go
  28. 77
      api/sys/sys_dictionary.go
  29. 77
      api/sys/sys_dictionary_detail.go
  30. 19
      api/sys/sys_email.go
  31. 22
      api/sys/sys_jwt_blacklist.go
  32. 237
      api/sys/sys_menu.go
  33. 117
      api/sys/sys_operation_record.go
  34. 65
      api/sys/sys_system.go
  35. 395
      api/sys/sys_user.go
  36. 78
      config-prod.yaml
  37. 78
      config.yaml
  38. 18
      config/auto_code.go
  39. 7
      config/captcha.go
  40. 5
      config/casbin.go
  41. 26
      config/config.go
  42. 11
      config/email.go
  43. 5
      config/excel.go
  44. 21
      config/gorm.go
  45. 10
      config/gorm_settings.go
  46. 8
      config/jpush.go
  47. 7
      config/jwt.go
  48. 8
      config/minio.go
  49. 31
      config/oss.go
  50. 10
      config/paypal.go
  51. 7
      config/redis.go
  52. 9
      config/system.go
  53. 13
      config/timer.go
  54. 13
      config/zap.go
  55. 38
      core/server.go
  56. 17
      core/server_other.go
  57. 19
      core/server_win.go
  58. 57
      core/viper.go
  59. 103
      core/zap.go
  60. 0
      deploy/.gitkeep
  61. 24
      deploy/admin-api-deployment.yaml
  62. 13
      deploy/admin-api-service.yaml
  63. 11770
      docs/docs.go
  64. 11745
      docs/swagger.json
  65. 7674
      docs/swagger.yaml
  66. 1006
      dto/customer.pb.go
  67. 73
      dto/customer.proto
  68. 24
      global/global.go
  69. 56
      global/model.go
  70. 159
      go.mod
  71. 1046
      go.sum
  72. 2205
      initialize/api/greeter.pb.go
  73. 203
      initialize/api/greeter.proto
  74. 482
      initialize/api/greeter_grpc.pb.go
  75. 100
      initialize/gorm.go
  76. 54
      initialize/grpc.go
  77. 52
      initialize/internal/gorm.go
  78. 33
      initialize/internal/logger.go
  79. 22
      initialize/minio.go
  80. 24
      initialize/redis.go
  81. 75
      initialize/router.go
  82. 27
      initialize/timer.go
  83. 22
      initialize/validator.go
  84. 33
      main.go
  85. 36
      middleware/casbin_rbac.go
  86. 26
      middleware/cors.go
  87. 61
      middleware/error.go
  88. 144
      middleware/jwt.go
  89. 26
      middleware/loadtls.go
  90. 23
      middleware/need_init.go
  91. 87
      middleware/operation.go
  92. 30
      model/account.go
  93. 22
      model/address.go
  94. 23
      model/application.go
  95. 28
      model/banner.go
  96. 42
      model/bill.go
  97. 47
      model/bill_fund.go
  98. 28
      model/brochure.go
  99. 18
      model/business.go
  100. 39
      model/category.go

24
.gitignore

@ -0,0 +1,24 @@
# ---> Go
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
*.log
log
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
*.baiduyun.*
# Dependency directories (remove the comment below to include it)
# vendor/
*.history
*_debug*
*.vscode
*cache

5
.idea/.gitignore

@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/

9
.idea/admin-api.iml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/modules.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/admin-api.iml" filepath="$PROJECT_DIR$/.idea/admin-api.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

1
README.md

@ -1,2 +1 @@
# admin-api

131
api/admin/application.go

@ -0,0 +1,131 @@
package v1
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags Applicationv0.0.0
// @Summary 创建Application
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Application true "创建Application"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /application/createApplication [post]
func CreateApplication(c *gin.Context) {
var application model.Application
_ = c.ShouldBindJSON(&application)
if err := service.CreateApplication(application); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags Applicationv0.0.0
// @Summary 删除Application
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Application true "删除Application"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /application/deleteApplication [delete]
func DeleteApplication(c *gin.Context) {
var application model.Application
_ = c.ShouldBindJSON(&application)
if err := service.DeleteApplication(application); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Applicationv0.0.0
// @Summary 批量删除Application
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除Application"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /application/deleteApplicationByIds [delete]
func DeleteApplicationByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteApplicationByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags Applicationv0.0.0
// @Summary 更新Application
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Application true "更新Application"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /application/updateApplication [put]
func UpdateApplication(c *gin.Context) {
var application model.Application
_ = c.ShouldBindJSON(&application)
if err := service.UpdateApplication(application); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Applicationv0.0.0
// @Summary 用id查询Application
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Application true "用id查询Application"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /application/findApplication [get]
func FindApplication(c *gin.Context) {
var application model.Application
_ = c.ShouldBindQuery(&application)
if err, reapplication := service.GetApplication(application.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(gin.H{"reapplication": reapplication}, c)
}
}
// @Tags Applicationv0.0.0
// @Summary 分页获取Application列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.ApplicationSearch true "分页获取Application列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /application/getApplicationList [get]
func GetApplicationList(c *gin.Context) {
var pageInfo request.ApplicationSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetApplicationInfoList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

186
api/admin/banner.go

@ -0,0 +1,186 @@
package v1
import (
"github.com/gin-gonic/gin"
"pure-admin/api/sys"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
)
// GetBannerList
// @Tags banner
// @Summary 分页获取banner列表【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SearchBanner true "data"
// @Success 200 {array} response.BannerListResponse "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /banner/list [get]
func GetBannerList(c *gin.Context) {
var (
err error
list interface{}
total int64
pageInfo request.SearchBanner
)
_ = c.ShouldBindQuery(&pageInfo)
if err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total = service.GetBannerList(pageInfo); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// CreateBanner
// @Tags banner
// @Summary 创建banner【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CreateBanner true "data"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /banner [post]
func CreateBanner(c *gin.Context) {
var (
err error
params request.CreateBanner
)
_ = c.ShouldBindJSON(&params)
//去除空格
if err = utils.Verify(params, utils.BannerVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
uuid := sys.GetUserUuid(c)
err = service.AddBanner(params, uuid)
if err != nil {
//global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage(err.Error(), c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// UpdateBanner
// @Tags banner
// @Summary 编辑banner【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.UpdateBanner true "id,data"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /banner [put]
func UpdateBanner(c *gin.Context) {
var (
err error
params request.UpdateBanner
)
_ = c.ShouldBindJSON(&params)
if err = utils.Verify(params, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//编辑参数验证
if err = utils.Verify(params, utils.BannerVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
uuid := sys.GetUserUuid(c)
if err = service.UpdateBanner(params, uuid); err != nil {
//global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败,"+err.Error(), c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// DelBannerByIds
// @Tags banner
// @Summary 批量删除banner【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "ids"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /banner/batchDelBanner [delete]
func DelBannerByIds(c *gin.Context) {
var (
err error
param request.IdsReq
)
_ = c.ShouldBindJSON(&param)
if err = service.DeleteBannerByIds(param); err != nil {
//global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// BannerUpData
// @Tags banner
// @Summary 上移banner排序【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdReq true "id,page,pageSize..."
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /banner/up-data [put]
func BannerUpData(c *gin.Context) {
var (
err error
param request.IdReq
)
_ = c.ShouldBindJSON(&param)
if err = utils.Verify(param, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err = service.BannerUpData(param, c); err != nil {
//global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// BannerDownData
// @Tags banner
// @Summary 下移banner排序【v1.1.0新增】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdReq true "id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /banner/down-data [put]
func BannerDownData(c *gin.Context) {
var (
err error
param request.IdReq
)
_ = c.ShouldBindJSON(&param)
if err = utils.Verify(param, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err = service.BannerDownData(param, c); err != nil {
//global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}

549
api/admin/bill.go

@ -0,0 +1,549 @@
package v1
import (
"github.com/gin-gonic/gin"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
)
// @Summary 用户账单数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} response.BillData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/customer-data [get]
func GetUserBillData(c *gin.Context) {
var (
err error
params request.BillSearch
result response.BillData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBillData("customer", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 用户账单列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} []model.BillList "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/customer-list [get]
func GetUserBillList(c *gin.Context) {
var (
err error
total int64
params request.BillSearch
result []model.BillList
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetBillList("customer", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 网红提现数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} response.InfluenceWithdrawalData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/influence-data [get]
func GetInfluenceWithdrawalData(c *gin.Context) {
var (
err error
params request.WithdrawalSearch
result response.InfluenceWithdrawalData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetInfluenceWithdrawalData(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 网红提现列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} []model.Withdrawal "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/influence-list [get]
func GetInfluenceWithdrawalList(c *gin.Context) {
var (
err error
total int64
params request.WithdrawalSearch
result []model.Withdrawal
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetWithdrawalList("1", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
func ExamineInfluenceWithdrawal(c *gin.Context) {
//var (
// err error
// params request.ExamineWithdrawal
//)
//_ = c.ShouldBindJSON(&params)
//err = service.ExamineWithdrawal("1", &params)
//if err != nil {
// response.FailWithMessage(err.Error(), c)
// return
//}
response.OkWithMessage("提交成功", c)
}
// @Summary 手动提现打款状态
// @Security Bearer
// @Description
// @Tags bill
// @Param data body request.TransferResult false "data..."
// @Success 200 {string} string "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/status [put]
func UpdateWithdrawalStatus(c *gin.Context) {
var (
err error
params request.TransferResult
)
_ = c.ShouldBindJSON(&params)
err = service.UpdateWithdrawalStatus(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithMessage("操作成功", c)
}
func TransferWithdrawalRetry(c *gin.Context) {
var (
//err error
//params request.RetryWithdrawal
)
//_ = c.ShouldBindJSON(&params)
//err = service.TransferWithdrawalRetry("1", &params)
//if err != nil {
// response.FailWithMessage(err.Error(), c)
// return
//}
response.OkWithMessage("操作成功", c)
}
// @Summary 网红账单数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} response.BillData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/influence-data [get]
func GetInfluenceBillData(c *gin.Context) {
var (
err error
params request.BillSearch
result response.BillData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBillData("influencer", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 网红账单列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} []model.BillList "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/influence-list [get]
func GetInfluenceBillList(c *gin.Context) {
var (
err error
total int64
params request.BillSearch
result []model.BillList
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetBillList("influencer", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 商家提现数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} response.SellerWithdrawalData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/seller-data [get]
func GetSellerWithdrawalData(c *gin.Context) {
var (
err error
params request.WithdrawalSearch
result response.SellerWithdrawalData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetSellerWithdrawalData(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 商家提现列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} []model.Withdrawal "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/seller-list [get]
func GetSellerWithdrawalList(c *gin.Context) {
var (
err error
total int64
params request.WithdrawalSearch
result []model.Withdrawal
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetWithdrawalList("2", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 商家提现审核
// @Security Bearer
// @Description
// @Tags bill
// @Param data body request.ExamineWithdrawal false "data..."
// @Success 200 {string} string "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/seller-examine [post]
func ExamineSellerWithdrawal(c *gin.Context) {
//var (
// err error
// params request.ExamineWithdrawal
//)
//_ = c.ShouldBindJSON(&params)
//err = service.ExamineWithdrawal("2", &params)
//if err != nil {
// response.FailWithMessage(err.Error(), c)
// return
//}
response.OkWithMessage("操作成功", c)
}
// @Summary 商家账单数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} response.BillData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/seller-data [get]
func GetSellerBillData(c *gin.Context) {
var (
err error
params request.BillSearch
result response.BillData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBillData("seller", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 商家账单列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} []model.BillList "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/seller-list [get]
func GetSellerBillList(c *gin.Context) {
var (
err error
total int64
params request.BillSearch
result []model.BillList
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetBillList("seller", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 商家营销账户数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillFundSearch false "data..."
// @Success 200 {object} response.SellerFundData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/seller-fund-data [get]
func GetSellerFundData(c *gin.Context) {
var (
err error
params request.BillFundSearch
result response.SellerFundData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetSellerFundData(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 商家营销账户记录列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillFundSearch false "data..."
// @Success 200 {array} model.SellerBillFund "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/seller-fund-list [get]
func GetSellerFundList(c *gin.Context) {
var (
err error
total int64
params request.BillFundSearch
result []model.SellerBillFund
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetSellerFundList("seller", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 平台提现数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} response.BkbData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/admin-data [get]
func GetAdminWithdrawalData(c *gin.Context) {
var (
err error
params request.WithdrawalSearch
result response.BkbData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBkbWithdrawalData(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 平台提现列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.WithdrawalSearch false "data..."
// @Success 200 {object} []model.Withdrawal "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /withdrawal/admin-list [get]
func GetAdminWithdrawalList(c *gin.Context) {
var (
err error
total int64
params request.WithdrawalSearch
result []model.Withdrawal
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetWithdrawalList("", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 平台账单数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} response.BillData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/admin-data [get]
func GetAdminBillData(c *gin.Context) {
var (
err error
params request.BillSearch
result response.BillData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBillData("", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 平台账单列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillSearch false "data..."
// @Success 200 {object} []model.BillList "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/admin-list [get]
func GetAdminBillList(c *gin.Context) {
var (
err error
total int64
params request.BillSearch
result []model.BillList
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetBillList("", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}
// @Summary 平台奖励账户数据
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillFundSearch false "data..."
// @Success 200 {object} response.AdminFundData "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/admin-fund-data [get]
func GetAdminFundData(c *gin.Context) {
var (
err error
params request.BillFundSearch
result response.AdminFundData
)
_ = c.ShouldBindQuery(&params)
err, result = service.GetBkbFundData(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}
// @Summary 平台奖励账户列表
// @Security Bearer
// @Description
// @Tags bill
// @Param data query request.BillFundSearch false "data..."
// @Success 200 {array} model.AdminBillFund "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /bill/admin-fund-list [get]
func GetAdminFundList(c *gin.Context) {
var (
err error
total int64
params request.BillFundSearch
result []model.AdminBillFund
)
_ = c.ShouldBindQuery(&params)
err, result, total = service.GetBkbFundList("bkb", &params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: result,
Total: total,
Page: params.Page,
PageSize: params.PageSize,
}, "获取成功", c)
}

162
api/admin/business.go

@ -0,0 +1,162 @@
package v1
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
)
// @Tags Businessv0.0.0
// @Summary 创建Business
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SellerStore true "创建Business"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /business [post]
func CreateBusiness(c *gin.Context) {
var business model.SellerStore
_ = c.ShouldBindJSON(&business)
if err := service.CreateBusiness(business); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags Businessv0.0.0
// @Summary 删除Business
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SellerStore true "删除Business"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /business [delete]
func DeleteBusiness(c *gin.Context) {
var business model.SellerStore
_ = c.ShouldBindJSON(&business)
if err := service.DeleteBusiness(business); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Businessv0.0.0
// @Summary 批量删除商家
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除Business"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /business/deleteBusinessByIds [delete]
func DeleteBusinessByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteBusinessByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags Business
// @Summary 更新商家
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SellerStore true "更新Business"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /business [put]
func UpdateBusiness(c *gin.Context) {
var business model.SellerStore
_ = c.ShouldBindJSON(&business)
if err := service.UpdateBusiness(business); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Business
// @Summary 用id查询商家
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body response.StoreInfoItem true "用id查询Business"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /business [get]
func GetBusiness(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindQuery(&info)
rebusiness, err := service.GetBusiness(info.ID)
if err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(rebusiness, c)
}
}
// @Tags Business
// @Summary 商家列表
// @Security ApiKeyAuth
// @accept application/json
// @Param data body request.PageInfo true "分页获取商家列表"
// @Success 200 {object} model.SellerStoreInfo "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /business/list [get]
func ListBusiness(c *gin.Context) {
var info request.PageInfo
_ = c.ShouldBindQuery(&info)
if info.Page == 0 {
info.Page = 1
}
list, total, err := service.GetBusinessInfoList(info)
if err != nil {
global.MG_LOG.Error("获取失败!" + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// @Tags Business
// @Summary 商家搜索
// @Security ApiKeyAuth
// @accept application/json
// @Param data body request.SearchStore true "分页获取商家列表"
// @Success 200 {object} model.SellerStoreInfo "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /business/search [get]
func SearchBusiness(c *gin.Context) {
var info request.SearchStore
_ = c.ShouldBindQuery(&info)
if info.Page == 0 {
info.Page = 1
}
list, total, err := service.SearchBusiness(info)
if err != nil {
global.MG_LOG.Error("获取失败!" + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}

153
api/admin/category.go

@ -0,0 +1,153 @@
package v1
import (
"github.com/gin-gonic/gin"
"pure-admin/global"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
)
// UpdateCategory
// @Summary 更新分类
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data body request.UpdateCategory false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category [put]
func UpdateCategory(c *gin.Context) {
var info request.UpdateCategory
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = service.UpdateCategory(info.Id, info.Name)
if err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("操作失败", c)
return
}
response.OkWithMessage("操作成功", c)
}
// CreateCategory
// @Summary 创建分类
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data body request.CreateCategory false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category [post]
func CreateCategory(c *gin.Context) {
var info request.CreateCategory
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err = service.CreateCategory(info.Name, info.Pid, info.Layer)
if err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("操作失败", c)
}
response.OkWithMessage("操作成功", c)
}
// DeleteCategory
// @Summary 删除分类
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data body request.IdsReq false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category [delete]
func DeleteCategory(c *gin.Context) {
var info request.IdsReq
err := c.ShouldBindJSON(&info)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.DeleteCategory(info.Ids); err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// ListCategoryPage
// @Summary 商品分类分页
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data query request.ListCategoryPage false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category/list [get]
func ListCategoryPage(c *gin.Context) {
var info request.ListCategoryPage
_ = c.ShouldBindQuery(&info)
if info.Page <= 0 {
info.Page = 1
}
list, total, err := service.ListCategoryTree(info)
if err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// ListCategoryChildren
// @Summary 查询分类下级
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data query request.ListCategoryChildren false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category/children [get]
func ListCategoryChildren(c *gin.Context) {
var info request.ListCategoryChildren
err := c.ShouldBindQuery(&info)
if err != nil {
global.MG_LOG.Error(err.Error())
response.FailWithMessage(err.Error(), c)
return
}
list, err := service.ListCategoryChildren(info.Pid)
if err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("获取失败", c)
return
}
response.OkWithDetailed(list, "获取成功", c)
}
// GetCategoryItem
// @Summary 查询单个商品分类
// @Description
// @Tags category
// @Security ApiKeyAuth
// @Param data body request.IdReq false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /category [get]
func GetCategoryItem(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindQuery(&info)
item, err := service.GetCategoryTree(int64(info.ID))
if err != nil {
global.MG_LOG.Error("获取失败! " + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(item, "获取成功", c)
}
}

36
api/admin/chain.go

@ -0,0 +1,36 @@
package v1
import (
"github.com/gin-gonic/gin"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
)
// GetChainInfo
// @Summary 获取区块链数据
// @Description
// @Tags Chain
// @Param data query request.ChainParams false "data..."
// @Success 200 {object} []response.ChainResp "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /base/chain [get]
func GetChainInfo(c *gin.Context) {
var (
err error
params request.ChainParams
result []response.ChainResp
)
_ = c.ShouldBindQuery(&params)
if err := utils.Verify(params, utils.ChainVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err, result = service.GetChainInfo(params.Hash)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithData(result, c)
}

40
api/admin/dict.go

@ -0,0 +1,40 @@
package v1
import (
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
)
// GetSysDictDataList
// @Tags dict
// @Summary 获取数据字典取值列表【v1.0】
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SearchDictDataParams true "data"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /dict/getDictDataList [get]
func GetSysDictDataList(c *gin.Context) {
var (
err error
list interface{}
params request.SearchDictDataParams
)
_ = c.ShouldBindQuery(&params)
if err = utils.Verify(params, utils.DictDataVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list = service.GetSysDictDataList(params); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SelectListResult{
List: list,
}, "获取成功", c)
}
}

61
api/admin/goods.go

@ -0,0 +1,61 @@
package v1
import (
"pure-admin/global"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
)
// @Tags Goods
// @Summary 商品列表
// @Security ApiKeyAuth
// @accept application/json
// @Param data body request.PageInfo true "分页获取商品列表"
// @Success 200 {object} model.TbGoods4List "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /goods/list [get]
func ListGoods(c *gin.Context) {
var info request.PageInfo
_ = c.ShouldBindQuery(&info)
if info.Page == 0 {
info.Page = 1
}
if list, total, err := service.ListGoods(info); err != nil {
global.MG_LOG.Error("获取失败!" + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// @Tags Goods
// @Summary 商品搜索
// @Security ApiKeyAuth
// @accept application/json
// @Param data body request.PageInfo true "分页获取商品列表"
// @Success 200 {object} model.TbGoods4List "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /goods/search [get]
func SearchGoods(c *gin.Context) {
var info request.SearchGoods
_ = c.ShouldBindQuery(&info)
if info.Page == 0 {
info.Page = 1
}
if list, total, err := service.SearchGoods(info); err != nil {
global.MG_LOG.Error("获取失败!" + err.Error())
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}

575
api/admin/mission.go

@ -0,0 +1,575 @@
package v1
import (
"pure-admin/api/sys"
"pure-admin/global"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// GetMissionDetail
// @Summary 获取任务详情
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.IdReq false "params"
// @Success 200 {object} model.MissionDetail "{"code": 200, "data": {}}"
// @Router /mission/mission [get]
func GetMissionDetail(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, data := service.GetMissionDetail(info.ID); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithData(data, c)
}
}
// GetMissionList
// @Summary 获取任务列表
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.SearchMission false "params"
// @Success 200 {object} response.PageResult "{"code": 200, "data": {}}"
// @Router /mission/mission-list [get]
func GetMissionList(c *gin.Context) {
var info request.SearchMission
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//if timeZone := c.GetHeader("Time-Zone"); timeZone != "" {
// info.TimeZone, _ = time.LoadLocation(timeZone)
//} else {
// info.TimeZone = time.Local
//}
if err, list, total := service.GetMissionList(info); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// GetMissionVideoList
// @Summary 获取任务视频列表
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.SearchMissionVideo false "params"
// @Success 200 {array} response.MissionVideoResponse "{"code": 200, "data": {}}"
// @Router /mission/video-list [get]
func GetMissionVideoList(c *gin.Context) {
var info request.SearchMissionVideo
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//info.VideoStatus = 2 //仅查询审核通过状态的视频列表
if err, list, total := service.GetMissionVideoList(info); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// AddMissionVideo
// @Summary 创建任务视频
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data body request.AddMissionVideo false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /mission/add-video [post]
func AddMissionVideo(c *gin.Context) {
var info request.AddMissionVideo
_ = c.ShouldBindJSON(&info)
if err := service.AddMissionVideo(sys.GetUserUuid(c), info); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// EditMissionVideo
// @Summary 编辑任务视频
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data body request.EditMissionVideo false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"编辑成功"}"
// @Router /mission/edit-video [put]
func EditMissionVideo(c *gin.Context) {
var info request.EditMissionVideo
_ = c.ShouldBindJSON(&info)
if err := service.EditMissionVideo(sys.GetUserUuid(c), info); err != nil {
global.MG_LOG.Error("编辑失败!", zap.Any("err", err))
response.FailWithMessage("编辑失败", c)
} else {
response.OkWithMessage("编辑成功", c)
}
}
// AddMissionRecommend
// @Summary 创建任务推荐关联
// @Description
// @Tags mission/recommend
// @Security ApiKeyAuth
// @Param data body request.AddMissionRecommend false "params"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /mission/recommend/add-data [post]
func AddMissionRecommend(c *gin.Context) {
var p request.AddMissionRecommend
var err error
err = c.ShouldBindJSON(&p)
if err != nil {
response.OkWithMessage("创建失败,参数错误", c)
return
}
if err = service.AddMissionRecommend(&p, sys.GetUserUuid(c)); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败,"+err.Error(), c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// BatchDelMissionRecommendByIds
// @Tags mission/recommend
// @Summary 批量删除任务推荐关联
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsUReq true "ids"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /mission/recommend/batch-del-data [delete]
func BatchDelMissionRecommendByIds(c *gin.Context) {
var (
err error
param request.IdsUReq
)
_ = c.ShouldBindJSON(&param)
if err = service.DeleteMissionRecommendByIds(param); err != nil {
//global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// MissionRecommendUpData
// @Tags mission/recommend
// @Summary 上移任务推荐排序
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdReq true "id,page,pageSize..."
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /mission/recommend/up-data [put]
func MissionRecommendUpData(c *gin.Context) {
var (
err error
param request.IdReq
)
_ = c.ShouldBindJSON(&param)
if err = utils.Verify(param, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err = service.MissionRecommendUpData(param, c); err != nil {
//global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// MissionRecommendDownData
// @Tags mission/recommend
// @Summary 上移任务推荐排序
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdReq true "id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /mission/recommend/down-data [put]
func MissionRecommendDownData(c *gin.Context) {
var (
err error
param request.IdReq
)
_ = c.ShouldBindJSON(&param)
if err = utils.Verify(param, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err = service.MissionRecommendDownData(param, c); err != nil {
//global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// MissionRecommendDownData
// @Tags mission/recommend
// @Summary 修改任务推荐排序
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body global.BASE_ID_SORT true "id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"操作成功"}"
// @Router /mission/recommend/update-sort [put]
func UpdateMissionRecommendSort(c *gin.Context) {
var (
err error
param global.BASE_ID_SORT
)
_ = c.ShouldBindJSON(&param)
if err = utils.Verify(param, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err = service.UpdateMissionRecommendSort(param); err != nil {
//global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败", c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// GetMissionRecommendList
// @Tags mission/recommend
// @Summary 分页获取任务推荐列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SearchMission true "data"
// @Success 200 {object} []response.MissionRecommendResponse "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /mission/recommend/list [get]
func GetMissionRecommendList(c *gin.Context) {
var (
err error
list interface{}
total int64
params request.SearchMission
)
_ = c.ShouldBindQuery(&params)
if err, list, total = service.GetMissionRecommendList(params); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
}, "获取成功", c)
}
}
// GetMissionClaimVideoDetail
// @Summary 任务视频审核详情【v1.0】
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.IdReq false "params"
// @Success 200 {array} response.MissionClaimVideoDetail "{"code": 200, "data": {}}"
// @Router /mission/claim-video-detail [get]
func GetMissionClaimVideoDetail(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, res := service.GetMissionClaimVideoDetail(info.ID); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(res, "获取成功", c)
}
}
// GetMissionStopList
// @Tags mission
// @Summary 分页获取任务结束申请列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SearchStopMission true "data"
// @Success 200 {array} response.MissionStopData "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /mission/stop-list [get]
func GetMissionStopList(c *gin.Context) {
var (
err error
list []response.MissionStopData
total int64
params request.SearchStopMission
)
_ = c.ShouldBindQuery(&params)
if err, list, total = service.GetMissionStopList(params); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
}, "获取成功", c)
}
}
// GetMissionStopDetail
// @Tags mission
// @Summary 获取任务结束详情
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.IdReq true "data"
// @Success 200 {object} response.MissionStopData "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /mission/stop-detail [get]
func GetMissionStopDetail(c *gin.Context) {
var (
err error
data response.MissionStopData
params request.IdReq
)
_ = c.ShouldBindQuery(&params)
if err, data = service.GetMissionStopDetail(params); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(data, "获取成功", c)
}
}
// StopMission
// @Summary 结束任务
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data body request.IdReq false "params"
// @Success 200 {string} string "{"code": 200, "data": {}}"
// @Router /mission/stop [put]
func StopMission(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindJSON(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.StopMission(sys.GetUserUuid(c), info); err != nil {
global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败,"+err.Error(), c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// GetMissionClaimList
// @Summary 获取任务领取列表
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.SearchMissionClaim false "params"
// @Success 200 {array} response.MissionClaimSimpleData "{"code": 200, "data": {}}"
// @Router /mission/claim-list [get]
func GetMissionClaimList(c *gin.Context) {
var info request.SearchMissionClaim
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total := service.GetMissionClaimList(info); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// GetSysRewardList
// @Summary 获取平台奖励列表【v1.0】
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.SearchSysReward false "params"
// @Success 200 {array} model.SysMissionReward "{"code": 200, "data": {}}"
// @Router /mission/sys-reward-list [get]
func GetSysRewardList(c *gin.Context) {
var info request.SearchSysReward
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//uuid := sys.GetUserUuid(c)
if err, list, total := service.GetSysMissionRewardList(info); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// SendSysReward
// @Summary 发送系统任务奖励
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data body request.IdReq false "params"
// @Success 200 {string} string "{"code": 200, "data": {}}"
// @Router /mission/send-sys-reward [post]
func SendSysReward(c *gin.Context) {
var info request.IdReq
_ = c.ShouldBindJSON(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.SendSysMissionReward(sys.GetUserUuid(c), info); err != nil {
global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败,"+err.Error(), c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// MissionTagRelation
// @Summary 打标签
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data body request.CreateMissionTagRelation false "params"
// @Success 200 {string} string "{"code": 200, "data": {}}"
// @Router /mission/tag-relation [post]
func MissionTagRelation(c *gin.Context) {
var info request.CreateMissionTagRelation
_ = c.ShouldBindJSON(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.CreateMissionTagRelation(info, sys.GetUserUuid(c)); err != nil {
global.MG_LOG.Error("操作失败!", zap.Any("err", err))
response.FailWithMessage("操作失败,"+err.Error(), c)
} else {
response.OkWithMessage("操作成功", c)
}
}
// GetInfluencerMissionSummaryList
// @Summary 获取网红任务统计列表
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.InfluencerSummaryListParam false "params"
// @Success 200 {array} model.MissionClaimSummary "{"code": 200, "data": {}}"
// @Router /mission/influencer-summary-list [get]
func GetInfluencerMissionSummaryList(c *gin.Context) {
var info request.InfluencerSummaryListParam
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//info.VideoStatus = 2 //仅查询审核通过状态的视频列表
if err, list, total := service.GetInfluencerSummaryList(info); err != nil {
//global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage(err.Error(), c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// GetMissionClaimOrder
// @Summary 获取任务订单详情【v1.0】
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.OrderId false "params"
// @Success 200 {object} response.MissionClaimOrderResponse "{"code": 200, "data": {}}"
// @Router /mission/claim-order [get]
func GetMissionClaimOrder(c *gin.Context) {
var info request.OrderId
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info, utils.OrderIDVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, data := service.GetMissionClaimOrder(info.OrderID); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithData(response.MissionClaimOrderResponse{Order: data}, c)
}
}
// GetMissionClaimOrderList
// @Summary 获取任务订单列表【v1.0】
// @Description
// @Tags mission
// @Security ApiKeyAuth
// @Param data query request.SearchMissionClaimOrder false "params"
// @Success 200 {array} model.MissionClaimOrderDetail "{"code": 200, "data": {}}"
// @Router /mission/claim-order-list [get]
func GetMissionClaimOrderList(c *gin.Context) {
var info request.SearchMissionClaimOrder
_ = c.ShouldBindQuery(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total := service.GetMissionClaimOrderList(info); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}

80
api/admin/order.go

@ -0,0 +1,80 @@
package v1
import (
"github.com/gin-gonic/gin"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
)
// @Summary 获取订单列表
// @Security Bearer
// @Description
// @Tags order
// @Param data query request.SearchOrderList false "data..."
// @Success 200 {object} []model.OrderList "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /order/list [get]
func GetOrderList(c *gin.Context) {
var (
err error
list interface{}
total int64
data request.SearchOrderList
)
_ = c.ShouldBindQuery(&data)
err, list, total = service.GetOrderList(&data)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: data.Page,
PageSize: data.PageSize,
}, "获取成功", c)
}
// @Summary 获取订单详情
// @Security Bearer
// @Description
// @Tags order
// @Param data query request.SearchOrderDetail false "data..."
// @Success 200 {object} model.OrderDetail "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /order/detail [get]
func GetOrderDetail(c *gin.Context) {
var (
err error
list interface{}
data request.SearchOrderDetail
)
_ = c.ShouldBindQuery(&data)
err, list = service.GetOrderDetail(&data)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(list, "获取成功", c)
}
// @Summary 获取数据统计
// @Security Bearer
// @Description
// @Tags order
// @Success 200 {object} response.DataStatistics "{"code": 0, "data": [...]}"
// @Success 201 {string} string "{"code": 1, "message": ""}"
// @Router /order/statistic [get]
func GetStatisticData(c *gin.Context) {
var (
err error
result response.DataStatistics
)
result, err = service.GetStatisticData()
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDetailed(result, "获取成功", c)
}

131
api/admin/organization.go

@ -0,0 +1,131 @@
package v1
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags Organizationv0.0.0
// @Summary 创建Organization
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Organization true "创建Organization"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /organization/createOrganization [post]
func CreateOrganization(c *gin.Context) {
var organization model.Organization
_ = c.ShouldBindJSON(&organization)
if err := service.CreateOrganization(organization); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags Organizationv0.0.0
// @Summary 删除Organization
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Organization true "删除Organization"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /organization/deleteOrganization [delete]
func DeleteOrganization(c *gin.Context) {
var organization model.Organization
_ = c.ShouldBindJSON(&organization)
if err := service.DeleteOrganization(organization); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Organizationv0.0.0
// @Summary 批量删除Organization
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除Organization"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /organization/deleteOrganizationByIds [delete]
func DeleteOrganizationByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteOrganizationByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags Organizationv0.0.0
// @Summary 更新Organization
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Organization true "更新Organization"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /organization/updateOrganization [put]
func UpdateOrganization(c *gin.Context) {
var organization model.Organization
_ = c.ShouldBindJSON(&organization)
if err := service.UpdateOrganization(organization); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Organizationv0.0.0
// @Summary 用id查询Organization
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Organization true "用id查询Organization"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /organization/findOrganization [get]
func FindOrganization(c *gin.Context) {
var organization model.Organization
_ = c.ShouldBindQuery(&organization)
if err, reorganization := service.GetOrganization(organization.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(gin.H{"reorganization": reorganization}, c)
}
}
// @Tags Organizationv0.0.0
// @Summary 分页获取Organization列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.OrganizationSearch true "分页获取Organization列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /organization/getOrganizationList [get]
func GetOrganizationList(c *gin.Context) {
var pageInfo request.OrganizationSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetOrganizationInfoList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

131
api/admin/provider.go

@ -0,0 +1,131 @@
package v1
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags Providerv0.0.0
// @Summary 创建Provider
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Provider true "创建Provider"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /provider/createProvider [post]
func CreateProvider(c *gin.Context) {
var provider model.Provider
_ = c.ShouldBindJSON(&provider)
if err := service.CreateProvider(provider); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags Providerv0.0.0
// @Summary 删除Provider
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Provider true "删除Provider"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /provider/deleteProvider [delete]
func DeleteProvider(c *gin.Context) {
var provider model.Provider
_ = c.ShouldBindJSON(&provider)
if err := service.DeleteProvider(provider); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Providerv0.0.0
// @Summary 批量删除Provider
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除Provider"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /provider/deleteProviderByIds [delete]
func DeleteProviderByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteProviderByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags Providerv0.0.0
// @Summary 更新Provider
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Provider true "更新Provider"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /provider/updateProvider [put]
func UpdateProvider(c *gin.Context) {
var provider model.Provider
_ = c.ShouldBindJSON(&provider)
if err := service.UpdateProvider(provider); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Providerv0.0.0
// @Summary 用id查询Provider
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.Provider true "用id查询Provider"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /provider/findProvider [get]
func FindProvider(c *gin.Context) {
var provider model.Provider
_ = c.ShouldBindQuery(&provider)
if err, reprovider := service.GetProvider(provider.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(gin.H{"reprovider": reprovider}, c)
}
}
// @Tags Providerv0.0.0
// @Summary 分页获取Provider列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.ProviderSearch true "分页获取Provider列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /provider/getProviderList [get]
func GetProviderList(c *gin.Context) {
var pageInfo request.ProviderSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetProviderInfoList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

181
api/admin/tags.go

@ -0,0 +1,181 @@
package v1
import (
"pure-admin/api/sys"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"strings"
"github.com/gin-gonic/gin"
)
// GetTagsList
// @Tags tags
// @Summary 分页获取标签列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.SearchTags true "data"
// @Success 200 {object} [][]model.Tags "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /tags/list [get]
func GetTagsList(c *gin.Context) {
var (
err error
list interface{}
total int64
pageInfo request.SearchTags
)
_ = c.ShouldBindQuery(&pageInfo)
if err = utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total = service.GetTagsList(pageInfo); err != nil {
////global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// CreateTags
// @Tags tags
// @Summary 创建标签
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.TagsCommon true "data"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /tags [post]
func CreateTags(c *gin.Context) {
var (
err error
params request.TagsCommon
outData model.Tags
)
_ = c.ShouldBindJSON(&params)
//去除空格
params.Value = strings.Replace(params.Value, " ", "", -1)
if err = utils.Verify(params, utils.ValueVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
uuid := sys.GetUserUuid(c)
outData, err = service.CreateTags(params, uuid)
if err != nil {
//global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage(err.Error(), c)
} else {
response.OkWithDataMessage(outData.ID, "创建成功", c)
}
}
// UpdateTags
// @Tags tags
// @Summary 编辑标签
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.TagsCommon true "id,data"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /tags [put]
func UpdateTags(c *gin.Context) {
var (
err error
params request.TagsCommon
)
_ = c.ShouldBindJSON(&params)
params.Value = strings.Replace(params.Value, " ", "", -1)
if err = utils.Verify(params, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
//编辑参数验证
if err = utils.Verify(params, utils.ValueVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
uuid := sys.GetUserUuid(c)
if err = service.UpdateTags(params, uuid); err != nil {
//global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败,"+err.Error(), c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// DelTagsByIds
// @Tags tags
// @Summary 批量删除标签
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "ids"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /tags/batchDelTags [delete]
func DelTagsByIds(c *gin.Context) {
var (
err error
param request.IdsReq
)
_ = c.ShouldBindJSON(&param)
if err = service.DeleteTagsByIds(param); err != nil {
//global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// GetTagsList
// @Tags tags
// @Summary 获取关联标签列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.RaletionTags true "data"
// @Success 200 {object} []model.TagsDesc "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /tags/relationTags [get]
func GetRelationTags(c *gin.Context) {
var (
param request.RaletionTags
)
_ = c.ShouldBindJSON(&param)
tags, err := service.GetTagsByRelation(&param)
if err != nil {
response.FailWithMessage("获取失败", c)
return
}
response.OkWithData(tags, c)
}
// @Summary 打标签
// @Description
// @Tags tags
// @Security ApiKeyAuth
// @Param data body request.CreateTagRelation false "params"
// @Success 200 {string} string "{"code": 200, "data": {}}"
// @Router /tags/relationTags [post]
func TagRelation(c *gin.Context) {
var info request.CreateTagRelation
_ = c.ShouldBindJSON(&info)
if err := utils.Verify(info, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.CreateTagRelation(info, sys.GetUserUuid(c)); err != nil {
response.FailWithMessage("操作失败,"+err.Error(), c)
} else {
response.OkWithMessage("操作成功", c)
}
}

219
api/admin/user.go

@ -0,0 +1,219 @@
package v1
import (
"pure-admin/api/sys"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags User
// @Summary 创建User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.User true "创建User"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/createUser [post]
func CreateUser(c *gin.Context) {
var user model.User
_ = c.ShouldBindJSON(&user)
if err := service.CreateUser(user); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags User
// @Summary 删除User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.User true "删除User"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /user/deleteUser [delete]
func DeleteUser(c *gin.Context) {
var user model.User
_ = c.ShouldBindJSON(&user)
if err := service.DeleteUser(user); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags User
// @Summary 批量删除User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除User"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /user/deleteUserByIds [delete]
func DeleteUserByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteUserByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags User
// @Summary 更新User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.User true "更新User"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /user/updateUser [put]
func UpdateUser(c *gin.Context) {
var user model.User
_ = c.ShouldBindJSON(&user)
if err := service.UpdateUser(user); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags User
// @Summary 用id查询User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.UserSearchByID true "用id查询User"
// @Success 200 {object} model.UserSimple "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /user/findUser [get]
func FindUser(c *gin.Context) {
var user request.UserSearchByID
_ = c.ShouldBindQuery(&user)
if err, reuser := service.GetUser(user.UserID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithData(gin.H{"reuser": reuser}, c)
}
}
// @Tags User
// @Summary 分页获取User列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.UserSimpleSearch true "分页获取User列表"
// @Success 200 {object} model.UserSimple "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserList [get]
func GetUserList(c *gin.Context) {
var pageInfo request.UserSimpleSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetUserInfoList(pageInfo, sys.GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// @Tags User
// @Summary 分页获取系统User列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.UserSimpleSearch true "分页获取User列表"
// @Success 200 {object} model.UserSimple "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserList [post]
func GetSysUserList(c *gin.Context) {
var pageInfo request.UserSimpleSearch
_ = c.ShouldBind(&pageInfo)
if err, list, total := service.GetSysUserInfoList(pageInfo, sys.GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// @Tags User
// @Summary 获取网红认证审核记录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.PlatformAuthSearch true "分页获取User列表"
// @Success 200 {object} model.PlatformAuthSimple "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/platformAuth [get]
func PlatformAuth(c *gin.Context) {
var pageInfo request.PlatformAuthSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetPlatformAuthList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// @Tags User
// @Summary 网红认证审核
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PlatformAuthCheck true "分页获取User列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/platformAuth [put]
func CheckPlatformAuth(c *gin.Context) {
var auth request.PlatformAuthCheck
_ = c.ShouldBindJSON(&auth)
userID := sys.GetUserUuid(c)
if err := service.CheckPlatformAuth(&auth, userID); err != nil {
global.MG_LOG.Error("审核失败!", zap.Any("err", err))
response.FailWithMessage("审核失败", c)
} else {
response.OkWithMessage("审核成功", c)
}
}
// @Tags User
// @Summary 用户禁用启用
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.UserStatus true "分页获取User列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/userStatus [put]
func UpdateUserStatus(c *gin.Context) {
var auth request.UserStatus
_ = c.ShouldBind(&auth)
if err := service.UpdateUserStatus(&auth, sys.GetUserAppid(c), sys.GetUserUuid(c)); err != nil {
global.MG_LOG.Error("审核失败!", zap.Any("err", err))
response.FailWithMessage("审核失败,"+err.Error(), c)
} else {
response.OkWithMessage("审核成功", c)
}
}

48
api/admin/wallet.go

@ -0,0 +1,48 @@
package v1
import (
"fmt"
"github.com/gin-gonic/gin"
"pure-admin/dto"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
)
// @Summary 奖励账户充值
// @Security Bearer
// @Description
// @Tags wallet
// @Param data body request.FundRecharge false "data..."
// @Success 200 {object} response.PayResult "{"code": 0, "data": [...]}"
// @Success 200 {string} string "{"code": 1, "message": ""}"
// @Router /wallet/fund/recharge [post]
func FundRecharge(c *gin.Context) {
var (
err error
params request.FundRecharge
result response.PayResult
)
_ = c.ShouldBindJSON(&params)
err, result = service.FundRecharge(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithDataMessage(result, "ok", c)
}
func PaymentPayback(c *gin.Context) {
var (
err error
params dto.PaybackBody
)
_ = c.ShouldBind(&params)
fmt.Println(params)
err = service.PaypalCallback(&params)
if err != nil {
response.FailWithMessage(err.Error(), c)
return
}
response.OkWithMessage("回调成功", c)
}

130
api/sys/exa_breakpoint_continue.go

@ -0,0 +1,130 @@
package sys
import (
"io/ioutil"
"pure-admin/global"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"strconv"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags ExaFileUploadAndDownload
// @Summary 断点续传到服务器
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "an example for breakpoint resume, 断点续传示例"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"切片创建成功"}"
// @Router /fileUploadAndDownload/breakpointContinue [post]
func BreakpointContinue(c *gin.Context) {
fileMd5 := c.Request.FormValue("fileMd5")
fileName := c.Request.FormValue("fileName")
chunkMd5 := c.Request.FormValue("chunkMd5")
chunkNumber, _ := strconv.Atoi(c.Request.FormValue("chunkNumber"))
chunkTotal, _ := strconv.Atoi(c.Request.FormValue("chunkTotal"))
_, FileHeader, err := c.Request.FormFile("file")
if err != nil {
global.MG_LOG.Error("接收文件失败!", zap.Any("err", err))
response.FailWithMessage("接收文件失败", c)
return
}
f, err := FileHeader.Open()
if err != nil {
global.MG_LOG.Error("文件读取失败!", zap.Any("err", err))
response.FailWithMessage("文件读取失败", c)
return
}
defer f.Close()
cen, _ := ioutil.ReadAll(f)
if !utils.CheckMd5(cen, chunkMd5) {
global.MG_LOG.Error("检查md5失败!", zap.Any("err", err))
response.FailWithMessage("检查md5失败", c)
return
}
err, file := service.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
global.MG_LOG.Error("查找或创建记录失败!", zap.Any("err", err))
response.FailWithMessage("查找或创建记录失败", c)
return
}
err, pathc := utils.BreakPointContinue(cen, fileName, chunkNumber, chunkTotal, fileMd5)
if err != nil {
global.MG_LOG.Error("断点续传失败!", zap.Any("err", err))
response.FailWithMessage("断点续传失败", c)
return
}
if err = service.CreateFileChunk(file.ID, pathc, chunkNumber); err != nil {
global.MG_LOG.Error("创建文件记录失败!", zap.Any("err", err))
response.FailWithMessage("创建文件记录失败", c)
return
}
response.OkWithMessage("切片创建成功", c)
}
// @Tags ExaFileUploadAndDownload
// @Summary 查找文件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "Find the file, 查找文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查找成功"}"
// @Router /fileUploadAndDownload/findFile [post]
func FindFile(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
chunkTotal, _ := strconv.Atoi(c.Query("chunkTotal"))
err, file := service.FindOrCreateFile(fileMd5, fileName, chunkTotal)
if err != nil {
global.MG_LOG.Error("查找失败!", zap.Any("err", err))
response.FailWithMessage("查找失败", c)
} else {
response.OkWithDetailed(response.FileResponse{File: file}, "查找成功", c)
}
}
// @Tags ExaFileUploadAndDownload
// @Summary 创建文件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "上传文件完成"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"file uploaded, 文件创建成功"}"
// @Router /fileUploadAndDownload/findFile [post]
func BreakpointContinueFinish(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
err, filePath := utils.MakeFile(fileName, fileMd5)
if err != nil {
global.MG_LOG.Error("文件创建失败!", zap.Any("err", err))
response.FailWithMessage("文件创建失败", c)
} else {
response.OkWithDetailed(response.FilePathResponse{FilePath: filePath}, "文件创建成功", c)
}
}
// @Tags ExaFileUploadAndDownload
// @Summary 删除切片
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce application/json
// @Param file formData file true "删除缓存切片"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"缓存切片删除成功"}"
// @Router /fileUploadAndDownload/removeChunk [post]
func RemoveChunk(c *gin.Context) {
fileMd5 := c.Query("fileMd5")
fileName := c.Query("fileName")
filePath := c.Query("filePath")
err := utils.RemoveChunk(fileMd5)
err = service.DeleteFileChunk(fileMd5, fileName, filePath)
if err != nil {
global.MG_LOG.Error("缓存切片删除失败!", zap.Any("err", err))
response.FailWithMessage("缓存切片删除失败", c)
} else {
response.OkWithDetailed(response.FilePathResponse{FilePath: filePath}, "缓存切片删除成功", c)
}
}

175
api/sys/sys_api.go

@ -0,0 +1,175 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags SysApi
// @Summary 创建基础api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysApi true "api路径, api中文描述, api组, 方法"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /api/createApi [post]
func CreateApi(c *gin.Context) {
var api model.SysApi
_ = c.ShouldBindJSON(&api)
if err := utils.Verify(api, utils.ApiVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
api.Appid = GetUserAppid(c)
api.Type = "admin"
if err := service.CreateApi(api); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败,"+err.Error(), c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags SysApi
// @Summary 删除api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysApi true "ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /api/deleteApi [post]
func DeleteApi(c *gin.Context) {
var api model.SysApi
_ = c.ShouldBindJSON(&api)
if err := utils.Verify(api.MG_MODEL, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
api.Appid = GetUserAppid(c)
if err := service.DeleteApi(api, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags SysApi
// @Summary 分页获取API列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SearchApiParams true "分页获取API列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/getApiList [post]
func GetApiList(c *gin.Context) {
var pageInfo request.SearchApiParams
_ = c.ShouldBindJSON(&pageInfo)
if err := utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
pageInfo.SysApi.Appid = GetUserAppid(c)
if err, list, total := service.GetAPIInfoList(pageInfo.SysApi, pageInfo.PageInfo, pageInfo.OrderKey, pageInfo.Desc); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}
// @Tags SysApi
// @Summary 根据id获取api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "根据id获取api"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/getApiById [post]
func GetApiById(c *gin.Context) {
var idInfo request.GetById
_ = c.ShouldBindJSON(&idInfo)
if err := utils.Verify(idInfo, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
err, api := service.GetApiById(idInfo.ID)
if err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithData(response.SysAPIResponse{Api: api}, c)
}
}
// @Tags SysApi
// @Summary 更新基础api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysApi true "api路径, api中文描述, api组, 方法"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /api/updateApi [post]
func UpdateApi(c *gin.Context) {
var api model.SysApi
_ = c.ShouldBindJSON(&api)
if err := utils.Verify(api, utils.ApiVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
api.Appid = GetUserAppid(c)
api.Type = "admin"
if err := service.UpdateApi(api); err != nil {
global.MG_LOG.Error("修改失败!", zap.Any("err", err))
response.FailWithMessage("修改失败"+err.Error(), c)
} else {
response.OkWithMessage("修改成功", c)
}
}
// @Tags SysApi
// @Summary 获取所有的Api 不分页
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/getAllApis [post]
func GetAllApis(c *gin.Context) {
if err, apis := service.GetAllApis(GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SysAPIListResponse{Apis: apis}, "获取成功", c)
}
}
// @Tags SysApi
// @Summary 删除选中Api
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /api/deleteApisByIds [delete]
func DeleteApisByIds(c *gin.Context) {
var ids request.IdsReq
_ = c.ShouldBindJSON(&ids)
if err := service.DeleteApisByIds(ids, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}

140
api/sys/sys_authority.go

@ -0,0 +1,140 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags Authority
// @Summary 创建角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysAuthority true "权限id, 权限名, 父角色id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /authority/createAuthority [post]
func CreateAuthority(c *gin.Context) {
var authority model.SysAuthority
_ = c.ShouldBindJSON(&authority)
if err := utils.Verify(authority, utils.AuthorityVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
authority.Appid = GetUserAppid(c)
authority.Type = "admin"
if err, authBack := service.CreateAuthority(authority); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.SysAuthorityResponse{Authority: authBack}, "创建成功", c)
}
}
// @Tags Authority
// @Summary 拷贝角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body response.SysAuthorityCopyResponse true "旧角色id, 新权限id, 新权限名, 新父角色id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"拷贝成功"}"
// @Router /authority/copyAuthority [post]
func CopyAuthority(c *gin.Context) {
var copyInfo response.SysAuthorityCopyResponse
_ = c.ShouldBindJSON(&copyInfo)
if err := utils.Verify(copyInfo, utils.OldAuthorityVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := utils.Verify(copyInfo.Authority, utils.AuthorityVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
copyInfo.Authority.Appid = GetUserAppid(c)
if err, authBack := service.CopyAuthority(copyInfo); err != nil {
global.MG_LOG.Error("拷贝失败!", zap.Any("err", err))
response.FailWithMessage("拷贝失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.SysAuthorityResponse{Authority: authBack}, "拷贝成功", c)
}
}
// @Tags Authority
// @Summary 删除角色
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysAuthority true "删除角色"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /authority/deleteAuthority [post]
func DeleteAuthority(c *gin.Context) {
var authority model.SysAuthority
_ = c.ShouldBindJSON(&authority)
if err := utils.Verify(authority, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.DeleteAuthority(&authority); err != nil { // 删除角色之前需要判断是否有用户正在使用此角色
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败"+err.Error(), c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Authority
// @Summary 更新角色信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysAuthority true "权限id, 权限名, 父角色id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /authority/updateAuthority [put]
func UpdateAuthority(c *gin.Context) {
var auth model.SysAuthority
_ = c.ShouldBindJSON(&auth)
if err := utils.Verify(auth, utils.AuthorityVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, authority := service.UpdateAuthority(auth); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.SysAuthorityResponse{Authority: authority}, "更新成功", c)
}
}
// @Tags Authority
// @Summary 分页获取角色列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /authority/getAuthorityList [post]
func GetAuthorityList(c *gin.Context) {
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
if err := utils.Verify(pageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total := service.GetAuthorityInfoList(pageInfo, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败"+err.Error(), c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

99
api/sys/sys_auto_code.go

@ -0,0 +1,99 @@
package sys
import (
"errors"
"fmt"
"net/url"
"os"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func PreviewTemp(c *gin.Context) {
var a model.AutoCodeStruct
_ = c.ShouldBindJSON(&a)
if err := utils.Verify(a, utils.AutoCodeVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
autoCode, err := service.PreviewTemp(a)
if err != nil {
global.MG_LOG.Error("预览失败!", zap.Any("err", err))
response.FailWithMessage("预览失败", c)
} else {
response.OkWithDetailed(gin.H{"autoCode": autoCode}, "预览成功", c)
}
}
func CreateTemp(c *gin.Context) {
var a model.AutoCodeStruct
_ = c.ShouldBindJSON(&a)
if err := utils.Verify(a, utils.AutoCodeVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if a.AutoCreateApiToSql {
if err := service.AutoCreateApi(&a); err != nil {
global.MG_LOG.Error("自动化创建失败!请自行清空垃圾数据!", zap.Any("err", err))
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msg", url.QueryEscape("自动化创建失败!请自行清空垃圾数据!"))
return
}
}
err := service.CreateTemp(a)
if err != nil {
fmt.Println(err)
if errors.Is(err, model.AutoMoveErr) {
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msgtype", "success")
c.Writer.Header().Add("msg", url.QueryEscape(err.Error()))
} else {
c.Writer.Header().Add("success", "false")
c.Writer.Header().Add("msg", url.QueryEscape(err.Error()))
_ = os.Remove("./ginvueadmin.zip")
}
} else {
c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", "ginvueadmin.zip")) // fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
c.Writer.Header().Add("Content-Type", "application/json")
c.Writer.Header().Add("success", "true")
c.File("./ginvueadmin.zip")
_ = os.Remove("./ginvueadmin.zip")
}
}
func GetTables(c *gin.Context) {
dbName := c.DefaultQuery("dbName", "")
err, tables := service.GetTables(dbName)
if err != nil {
global.MG_LOG.Error("查询table失败!", zap.Any("err", err))
response.FailWithMessage("查询table失败", c)
} else {
response.OkWithDetailed(gin.H{"tables": tables}, "获取成功", c)
}
}
func GetDB(c *gin.Context) {
if err, dbs := service.GetDB(); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"dbs": dbs}, "获取成功", c)
}
}
func GetColumn(c *gin.Context) {
dbName := c.DefaultQuery("dbName", "")
tableName := c.Query("tableName")
if err, columns := service.GetColumn(tableName, dbName); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"columns": columns}, "获取成功", c)
}
}

37
api/sys/sys_captcha.go

@ -0,0 +1,37 @@
package sys
import (
"pure-admin/global"
"pure-admin/model/response"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"go.uber.org/zap"
)
//var store = base64Captcha.DefaultMemStore
var store = utils.RedisStore{}
// @Tags Base
// @Summary 生成验证码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"验证码获取成功"}"
// @Router /base/captcha [post]
func Captcha(c *gin.Context) {
// 字符,公式,验证码配置
// 生成默认数字的driver
driver := base64Captcha.NewDriverDigit(global.MG_CONFIG.Captcha.ImgHeight, global.MG_CONFIG.Captcha.ImgWidth, global.MG_CONFIG.Captcha.KeyLong, 0.7, 80)
cp := base64Captcha.NewCaptcha(driver, store)
if id, b64s, err := cp.Generate(); err != nil {
global.MG_LOG.Error("验证码获取失败!", zap.Any("err", err))
response.FailWithMessage("验证码获取失败", c)
} else {
response.OkWithDetailed(response.SysCaptchaResponse{
CaptchaId: id,
PicPath: b64s,
}, "验证码获取成功", c)
}
}

54
api/sys/sys_casbin.go

@ -0,0 +1,54 @@
package sys
import (
"pure-admin/global"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags Casbin
// @Summary 更新角色api权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CasbinInReceive true "权限id, 权限模型列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /casbin/UpdateCasbin [post]
func UpdateCasbin(c *gin.Context) {
var cmr request.CasbinInReceive
_ = c.ShouldBindJSON(&cmr)
if err := utils.Verify(cmr, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.UpdateCasbin(cmr.AuthorityId, GetUserAppid(c), cmr.CasbinInfos); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Casbin
// @Summary 获取权限列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CasbinInReceive true "权限id, 权限模型列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /casbin/getPolicyPathByAuthorityId [post]
func GetPolicyPathByAuthorityId(c *gin.Context) {
var casbin request.CasbinInReceive
_ = c.ShouldBindJSON(&casbin)
if err := utils.Verify(casbin, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
paths := service.GetPolicyPathByAuthorityId(casbin.AuthorityId, GetUserAppid(c))
response.OkWithDetailed(response.PolicyPathResponse{Paths: paths}, "获取成功", c)
}

77
api/sys/sys_dictionary.go

@ -0,0 +1,77 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func CreateSysDictionary(c *gin.Context) {
var dictionary model.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := service.CreateSysDictionary(dictionary); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
func DeleteSysDictionary(c *gin.Context) {
var dictionary model.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := service.DeleteSysDictionary(dictionary); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
func UpdateSysDictionary(c *gin.Context) {
var dictionary model.SysDictionary
_ = c.ShouldBindJSON(&dictionary)
if err := service.UpdateSysDictionary(&dictionary); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
func FindSysDictionary(c *gin.Context) {
var dictionary model.SysDictionary
_ = c.ShouldBindQuery(&dictionary)
if err, sysDictionary := service.GetSysDictionary(dictionary.Type, dictionary.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysDictionary": sysDictionary}, "查询成功", c)
}
}
func GetSysDictionaryList(c *gin.Context) {
var pageInfo request.SysDictionarySearch
_ = c.ShouldBindQuery(&pageInfo)
if err := utils.Verify(pageInfo.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total := service.GetSysDictionaryInfoList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

77
api/sys/sys_dictionary_detail.go

@ -0,0 +1,77 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func CreateSysDictionaryDetail(c *gin.Context) {
var detail model.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := service.CreateSysDictionaryDetail(detail); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
func DeleteSysDictionaryDetail(c *gin.Context) {
var detail model.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := service.DeleteSysDictionaryDetail(detail); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
func UpdateSysDictionaryDetail(c *gin.Context) {
var detail model.SysDictionaryDetail
_ = c.ShouldBindJSON(&detail)
if err := service.UpdateSysDictionaryDetail(&detail); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
func FindSysDictionaryDetail(c *gin.Context) {
var detail model.SysDictionaryDetail
_ = c.ShouldBindQuery(&detail)
if err := utils.Verify(detail, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, resysDictionaryDetail := service.GetSysDictionaryDetail(detail.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysDictionaryDetail": resysDictionaryDetail}, "查询成功", c)
}
}
func GetSysDictionaryDetailList(c *gin.Context) {
var pageInfo request.SysDictionaryDetailSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetSysDictionaryDetailInfoList(pageInfo); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

19
api/sys/sys_email.go

@ -0,0 +1,19 @@
package sys
import (
"pure-admin/global"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func EmailTest(c *gin.Context) {
if err := service.EmailTest(); err != nil {
global.MG_LOG.Error("发送失败!", zap.Any("err", err))
response.FailWithMessage("发送失败", c)
} else {
response.OkWithData("发送成功", c)
}
}

22
api/sys/sys_jwt_blacklist.go

@ -0,0 +1,22 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func JsonInBlacklist(c *gin.Context) {
token := c.Request.Header.Get("x-token")
jwt := model.JwtBlacklist{Jwt: token}
if err := service.JsonInBlacklist(jwt); err != nil {
global.MG_LOG.Error("jwt作废失败!", zap.Any("err", err))
response.FailWithMessage("jwt作废失败", c)
} else {
response.OkWithMessage("jwt作废成功", c)
}
}

237
api/sys/sys_menu.go

@ -0,0 +1,237 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags AuthorityMenu
// @Summary 获取用户动态路由
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getMenu [post]
func GetMenu(c *gin.Context) {
if err, menus := service.GetMenuTree(GetUserAuthorityId(c), GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SysMenusResponse{Menus: menus}, "获取成功", c)
}
}
// @Tags AuthorityMenu
// @Summary 获取用户动态路由List
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getMenuForList [post]
func GetMenuForList(c *gin.Context) {
if err, menus := service.GetMenuAuthority(GetUserAuthorityId(c), GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
paths := service.GetPolicyPathByAuthorityId(GetUserAuthorityId(c), GetUserAppid(c))
response.OkWithDetailed(gin.H{"menus": menus, "apis": paths}, "获取成功", c)
}
}
// @Tags AuthorityMenu
// @Summary 获取用户动态路由
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getBaseMenuTree [post]
func GetBaseMenuTree(c *gin.Context) {
if err, menus := service.GetBaseMenuTree(); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SysBaseMenusResponse{Menus: menus}, "获取成功", c)
}
}
// @Tags AuthorityMenu
// @Summary 增加menu和角色关联关系
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.AddMenuAuthorityInfo true "角色ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"添加成功"}"
// @Router /menu/addMenuAuthority [post]
func AddMenuAuthority(c *gin.Context) {
var authorityMenu request.AddMenuAuthorityInfo
_ = c.ShouldBindJSON(&authorityMenu)
if err := utils.Verify(authorityMenu, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.AddMenuAuthority(authorityMenu.Menus, authorityMenu.AuthorityId, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("添加失败!", zap.Any("err", err))
response.FailWithMessage("添加失败", c)
} else {
response.OkWithMessage("添加成功", c)
}
}
// @Tags AuthorityMenu
// @Summary 获取指定角色menu
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetAuthorityId true "角色ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getMenuAuthority [post]
func GetMenuAuthority(c *gin.Context) {
var param request.GetAuthorityId
_ = c.ShouldBindJSON(&param)
if err := utils.Verify(param, utils.AuthorityIdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, menus := service.GetMenuAuthority(param.AuthorityId, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"menus": menus}, "获取成功", c)
}
}
// @Tags Menu
// @Summary 新增菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysBaseMenu true "路由path, 父菜单ID, 路由name, 对应前端文件路径, 排序标记"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"添加成功"}"
// @Router /menu/addBaseMenu [post]
func AddBaseMenu(c *gin.Context) {
var menu model.SysBaseMenu
_ = c.ShouldBindJSON(&menu)
if err := utils.Verify(menu, utils.MenuVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := utils.Verify(menu.Meta, utils.MenuMetaVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.AddBaseMenu(menu, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("添加失败!", zap.Any("err", err))
response.FailWithMessage("添加失败,"+err.Error(), c)
} else {
response.OkWithMessage("添加成功", c)
}
}
// @Tags Menu
// @Summary 删除菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "菜单id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /menu/deleteBaseMenu [post]
func DeleteBaseMenu(c *gin.Context) {
var menu request.GetById
_ = c.ShouldBindJSON(&menu)
if err := utils.Verify(menu, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.DeleteBaseMenu(menu.ID, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags Menu
// @Summary 更新菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysBaseMenu true "路由path, 父菜单ID, 路由name, 对应前端文件路径, 排序标记"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /menu/updateBaseMenu [post]
func UpdateBaseMenu(c *gin.Context) {
var menu model.SysBaseMenu
_ = c.ShouldBindJSON(&menu)
if err := utils.Verify(menu, utils.MenuVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := utils.Verify(menu.Meta, utils.MenuMetaVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err := service.UpdateBaseMenu(menu); err != nil {
global.MG_LOG.Error("更新失败!", zap.Any("err", err))
response.FailWithMessage("更新失败", c)
} else {
response.OkWithMessage("更新成功", c)
}
}
// @Tags Menu
// @Summary 根据id获取菜单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "菜单id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getBaseMenuById [post]
func GetBaseMenuById(c *gin.Context) {
var idInfo request.GetById
_ = c.ShouldBindJSON(&idInfo)
if err := utils.Verify(idInfo, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, menu := service.GetBaseMenuById(idInfo.ID); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SysBaseMenuResponse{Menu: menu}, "获取成功", c)
}
}
// @Tags Menu
// @Summary 分页获取基础menu列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.PageInfo true "页码, 每页大小"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /menu/getMenuList [post]
func GetMenuList(c *gin.Context) {
var pageInfo request.PageInfo
_ = c.ShouldBindJSON(&pageInfo)
if err := utils.Verify(pageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, menuList, total := service.GetInfoList(); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: menuList,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

117
api/sys/sys_operation_record.go

@ -0,0 +1,117 @@
package sys
import (
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// @Tags SysOperationRecord
// @Summary 创建SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysOperationRecord true "创建SysOperationRecord"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /sysOperationRecord/createSysOperationRecord [post]
func CreateSysOperationRecord(c *gin.Context) {
var sysOperationRecord model.SysOperationRecord
_ = c.ShouldBindJSON(&sysOperationRecord)
if err := service.CreateSysOperationRecord(sysOperationRecord); err != nil {
global.MG_LOG.Error("创建失败!", zap.Any("err", err))
response.FailWithMessage("创建失败", c)
} else {
response.OkWithMessage("创建成功", c)
}
}
// @Tags SysOperationRecord
// @Summary 删除SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysOperationRecord true "SysOperationRecord模型"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /sysOperationRecord/deleteSysOperationRecord [delete]
func DeleteSysOperationRecord(c *gin.Context) {
var sysOperationRecord model.SysOperationRecord
_ = c.ShouldBindJSON(&sysOperationRecord)
if err := service.DeleteSysOperationRecord(sysOperationRecord); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags SysOperationRecord
// @Summary 批量删除SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除SysOperationRecord"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /sysOperationRecord/deleteSysOperationRecordByIds [delete]
func DeleteSysOperationRecordByIds(c *gin.Context) {
var IDS request.IdsReq
_ = c.ShouldBindJSON(&IDS)
if err := service.DeleteSysOperationRecordByIds(IDS); err != nil {
global.MG_LOG.Error("批量删除失败!", zap.Any("err", err))
response.FailWithMessage("批量删除失败", c)
} else {
response.OkWithMessage("批量删除成功", c)
}
}
// @Tags SysOperationRecord
// @Summary 用id查询SysOperationRecord
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysOperationRecord true "Id"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /sysOperationRecord/findSysOperationRecord [get]
func FindSysOperationRecord(c *gin.Context) {
var sysOperationRecord model.SysOperationRecord
_ = c.ShouldBindQuery(&sysOperationRecord)
if err := utils.Verify(sysOperationRecord, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, resysOperationRecord := service.GetSysOperationRecord(sysOperationRecord.ID); err != nil {
global.MG_LOG.Error("查询失败!", zap.Any("err", err))
response.FailWithMessage("查询失败", c)
} else {
response.OkWithDetailed(gin.H{"resysOperationRecord": resysOperationRecord}, "查询成功", c)
}
}
// @Tags SysOperationRecord
// @Summary 分页获取SysOperationRecord列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SysOperationRecordSearch true "页码, 每页大小, 搜索条件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /sysOperationRecord/getSysOperationRecordList [get]
func GetSysOperationRecordList(c *gin.Context) {
var pageInfo request.SysOperationRecordSearch
_ = c.ShouldBindQuery(&pageInfo)
if err, list, total := service.GetSysOperationRecordInfoList(pageInfo, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: pageInfo.Page,
PageSize: pageInfo.PageSize,
}, "获取成功", c)
}
}

65
api/sys/sys_system.go

@ -0,0 +1,65 @@
package sys
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
)
// @Tags System
// @Summary 获取配置文件内容
// @Security ApiKeyAuth
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /system/getSystemConfig [post]
func GetSystemConfig(c *gin.Context) {
if err, config := service.GetSystemConfig(); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.SysConfigResponse{Config: config}, "获取成功", c)
}
}
// @Tags System
// @Summary 设置配置文件内容
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body model.System true "设置配置文件内容"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"设置成功"}"
// @Router /system/setSystemConfig [post]
func SetSystemConfig(c *gin.Context) {
var sys model.System
_ = c.ShouldBindJSON(&sys)
if err := service.SetSystemConfig(sys); err != nil {
global.MG_LOG.Error("设置失败!", zap.Any("err", err))
response.FailWithMessage("设置失败", c)
} else {
response.OkWithData("设置成功", c)
}
}
// @Tags System
// @Summary 重启系统
// @Security ApiKeyAuth
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"重启系统成功"}"
// @Router /system/reloadSystem [post]
func ReloadSystem(c *gin.Context) {
err := utils.Reload()
if err != nil {
global.MG_LOG.Error("重启系统失败!", zap.Any("err", err))
response.FailWithMessage("重启系统失败", c)
} else {
response.OkWithMessage("重启系统成功", c)
}
}
func MonitorTest(c *gin.Context) {
response.OkWithMessage("ok", c)
}

395
api/sys/sys_user.go

@ -0,0 +1,395 @@
package sys
import (
"pure-admin/global"
"pure-admin/middleware"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"pure-admin/utils"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis"
"go.uber.org/zap"
)
// @Tags Base
// @Summary 用户登录
// @Produce application/json
// @Param data body request.Login true "用户名, 密码, 验证码"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}"
// @Router /base/login [post]
func Login(c *gin.Context) {
var l request.Login
_ = c.ShouldBindJSON(&l)
if err := utils.Verify(l, utils.LoginVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if store.Verify(l.CaptchaId, l.Captcha, true) {
u := &model.User{Username: l.Username, Password: l.Password, Appid: l.Appid}
if err, user := service.Login(u); err != nil {
global.MG_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Any("err", err))
response.FailWithMessage(err.Error(), c)
} else {
tokenNext(c, *user)
}
} else {
response.FailWithMessage("验证码错误", c)
}
}
// 登录以后签发jwt
func tokenNext(c *gin.Context, user model.User) {
j := &middleware.JWT{SigningKey: []byte(global.MG_CONFIG.JWT.SigningKey)} // 唯一签名
claims := request.CustomClaims{
UUID: user.UUID,
ID: user.ID,
NickName: user.NickName,
AuthorityId: user.AuthorityID,
Organization: user.Organization,
Appid: user.Appid,
Type: user.Type,
BufferTime: global.MG_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
StandardClaims: jwt.StandardClaims{
NotBefore: time.Now().Unix() - 1000, // 签名生效时间
ExpiresAt: time.Now().Unix() + global.MG_CONFIG.JWT.ExpiresTime, // 过期时间 7天 配置文件
Issuer: "qmPlus", // 签名的发行者
},
}
token, err := j.CreateToken(claims)
if err != nil {
global.MG_LOG.Error("获取token失败!", zap.Any("err", err))
response.FailWithMessage("获取token失败", c)
return
}
if !global.MG_CONFIG.System.UseMultipoint {
response.OkWithDetailed(response.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登录成功", c)
return
}
if err, jwtStr := service.GetRedisJWT(user.UUID.String()); err == redis.Nil {
if err := service.SetRedisJWT(token, user.UUID.String()); err != nil {
global.MG_LOG.Error("设置登录状态失败!", zap.Any("err", err))
response.FailWithMessage("设置登录状态失败", c)
return
}
response.OkWithDetailed(response.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登录成功", c)
} else if err != nil {
global.MG_LOG.Error("设置登录状态失败!", zap.Any("err", err))
response.FailWithMessage("设置登录状态失败", c)
} else {
var blackJWT model.JwtBlacklist
blackJWT.Jwt = jwtStr
if err := service.JsonInBlacklist(blackJWT); err != nil {
response.FailWithMessage("jwt作废失败", c)
return
}
if err := service.SetRedisJWT(token, user.UUID.String()); err != nil {
response.FailWithMessage("设置登录状态失败", c)
return
}
response.OkWithDetailed(response.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登录成功", c)
}
}
// @Tags SysUser
// @Summary 用户注册账号
// @Produce application/json
// @Param data body model.SysUser true "用户名, 昵称, 密码, 角色ID,姓名,手机"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
// @Router /user/register [post]
func Register(c *gin.Context) {
var r request.Register
_ = c.ShouldBindJSON(&r)
if err := utils.Verify(r, utils.RegisterVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
var authorities []model.SysAuthority
for _, v := range r.AuthorityIds {
authorities = append(authorities, model.SysAuthority{
AuthorityId: v,
})
}
user := &model.User{Username: r.Username, NickName: r.NickName, Phone: r.Phone, Password: r.Password, AuthorityID: r.AuthorityId, Authorities: authorities}
err, userReturn := service.Register(*user)
if err != nil {
global.MG_LOG.Error("注册失败!", zap.Any("err", err))
response.FailWithMessage(err.Error(), c)
} else {
response.OkWithDetailed(response.SysUserResponse{User: userReturn}, "注册成功", c)
}
}
// @Tags SysUser
// @Summary 用户修改密码
// @Security ApiKeyAuth
// @Produce application/json
// @Param data body request.ChangePasswordStruct true "用户名, 原密码, 新密码"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/changePassword [put]
func ChangePassword(c *gin.Context) {
var user request.ChangePasswordStruct
_ = c.ShouldBindJSON(&user)
if err := utils.Verify(user, utils.ChangePasswordVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
u := &model.SysUser{Username: user.Username, Password: user.Password}
if err, _ := service.ChangePassword(u, user.NewPassword); err != nil {
global.MG_LOG.Error("修改失败!", zap.Any("err", err))
response.FailWithMessage("修改失败,原密码与当前账户不符", c)
} else {
response.OkWithMessage("修改成功", c)
}
}
// @Tags SysUser
// @Summary 分页获取用户列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SearchSysUserParams true "页码, 每页大小"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /suser/getUserList [post]
func GetUserList(c *gin.Context) {
var info request.SearchSysUserParams
_ = c.ShouldBindJSON(&info)
if err := utils.Verify(info.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, list, total := service.GetUserInfoList1(info, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(response.PageResult{
List: list,
Total: total,
Page: info.Page,
PageSize: info.PageSize,
}, "获取成功", c)
}
}
// @Tags SysUser
// @Summary 设置用户权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SetUserAuth true "用户UUID, 角色ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/setUserAuthority [post]
func SetUserAuthority(c *gin.Context) {
var sua request.SetUserAuth
_ = c.ShouldBindJSON(&sua)
if UserVerifyErr := utils.Verify(sua, utils.SetUserAuthorityVerify); UserVerifyErr != nil {
response.FailWithMessage(UserVerifyErr.Error(), c)
return
}
if err := service.SetUserAuthority(GetUserUuid(c), sua.AuthorityId); err != nil {
global.MG_LOG.Error("修改失败!", zap.Any("err", err))
response.FailWithMessage("修改失败", c)
} else {
if err, user := service.GetUserInfo(GetUserUuid(c), GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取用户信息失败!", zap.Any("err", err))
response.FailWithMessage("获取用户信息失败", c)
} else {
tokenNext(c, user)
}
//claims := getUserInfo(c)
//j := &middleware.JWT{SigningKey: []byte(global.MG_CONFIG.JWT.SigningKey)} // 唯一签名
//claims.AuthorityId = sua.AuthorityId
//if token, err := j.CreateToken(*claims); err != nil {
// global.MG_LOG.Error("修改失败!", zap.Any("err", err))
// response.FailWithMessage(err.Error(), c)
//} else {
// response.OkWithDataMessage(token, "修改成功", c)
//}
}
}
// @Tags SysUser
// @Summary 删除用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.GetById true "用户ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /suser/deleteUser [delete]
func DeleteUser(c *gin.Context) {
var reqId request.GetById
_ = c.ShouldBindJSON(&reqId)
if err := utils.Verify(reqId, utils.IdVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
jwtId := getUserID(c)
if jwtId == uint(reqId.ID) {
response.FailWithMessage("删除失败, 自杀失败", c)
return
}
if err := service.DeleteUser1(reqId.ID); err != nil {
global.MG_LOG.Error("删除失败!", zap.Any("err", err))
response.FailWithMessage("删除失败", c)
} else {
response.OkWithMessage("删除成功", c)
}
}
// @Tags SysUser
// @Summary 设置用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body model.SysUser true "ID, 用户名, 昵称, 头像链接"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"设置成功"}"
// @Router /user/setUserInfo [put]
func SetUserInfo(c *gin.Context) {
var user model.SysUser
_ = c.ShouldBindJSON(&user)
if err := utils.Verify(user.MG_MODEL, utils.UUIDVerity); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
if err, ReqUser := service.SetUserInfo(user); err != nil {
global.MG_LOG.Error("设置失败!", zap.Any("err", err))
response.FailWithMessage("设置失败", c)
} else {
response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "设置成功", c)
}
}
// @Tags SysUser
// @Summary 获取用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserInfo [get]
func GetUserInfo(c *gin.Context) {
if err, ReqUser := service.GetUserInfo(GetUserUuid(c), GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
}
}
// @Tags SysUser
// @Summary 获取用户选择器列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param nickName query string true "nickName"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /user/getUserSelectList [get]
func GetUserSelectList(c *gin.Context) {
nickName := c.Query("nickName")
if list, err := service.GetUserSelectList(nickName, GetUserAppid(c)); err != nil {
global.MG_LOG.Error("获取失败!", zap.Any("err", err))
response.FailWithMessage("获取失败", c)
} else {
response.OkWithDetailed(list, "获取成功", c)
}
}
// 从Gin的Context中获取从jwt解析出来的用户ID
func getUserID(c *gin.Context) uint {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户ID失败, 请检查路由是否使用jwt中间件!")
return 0
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse.ID
}
}
// 从Gin的Context中获取从jwt解析出来的用户UUID
func GetUserUuid(c *gin.Context) string {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
return ""
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse.UUID.String()
}
}
// 从Gin的Context中获取从jwt解析出来的用户UUID
func GetUserAppid(c *gin.Context) string {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
return ""
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse.Appid
}
}
// 从Gin的Context中获取从jwt解析出来的用户昵称
func GetUserNickName(c *gin.Context) string {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
return ""
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse.NickName
}
}
// 从Gin的Context中获取从jwt解析出来的用户角色id
func GetUserAuthorityId(c *gin.Context) uint {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
return 0
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse.AuthorityId
}
}
func getUserInfo(c *gin.Context) *request.CustomClaims {
if claims, exists := c.Get("claims"); !exists {
global.MG_LOG.Error("从Gin的Context中获取从jwt解析出来的用户UUID失败, 请检查路由是否使用jwt中间件!")
return nil
} else {
waitUse := claims.(*request.CustomClaims)
return waitUse
}
}
// @Tags SysUser
// @Summary 设置用户权限
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.SetUserAuthorities true "用户UUID, 角色ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
// @Router /user/setUserAuthorities [post]
func SetUserAuthorities(c *gin.Context) {
var sua request.SetUserAuthorities
_ = c.ShouldBindJSON(&sua)
if err := service.SetUserAuthorities(sua.UUID, sua.AuthorityIds); err != nil {
global.MG_LOG.Error("修改失败!", zap.Any("err", err))
response.FailWithMessage("修改失败", c)
} else {
response.OkWithMessage("修改成功", c)
}
}

78
config-prod.yaml

@ -0,0 +1,78 @@
autocode:
transfer-restart: true
root: /Users/wenwu/Desktop/project/BKB-N
server: /admin-api
server-api: /api/admin
server-initialize: /initialize
server-model: /model
server-request: /model/request/
server-router: /router
server-service: /service
web: /web/src
web-api: /api
web-form: /view
web-table: /view
web-flow: /view
captcha:
key-long: 6
img-width: 240
img-height: 80
casbin:
model-path: ./resource/rbac_model.conf
email:
to: xxx@qq.com
port: 465
from: xxx@163.com
host: smtp.163.com
is-ssl: true
secret: xxx
nickname: test
jwt:
signing-key: qmPlus
expires-time: 604800
buffer-time: 86400
local:
path: uploads/file
mysql:
path: 172.16.0.26:3306
config: charset=utf8mb4&parseTime=True&loc=Local
db-name: bkb_prod
username: bkbrd
password: yJGQ3hlV#*4nTJrn
max-idle-conns: 10
max-open-conns: 100
log-mode: info
log-zap: ""
redis:
db: 1
# addr: 172.16.0.239:6379
# password: bkbrd:!Fgcye*HGs*Z&q0p
addr: redis-6715eafa-8e3f-4014-9659-ac647bd1ef46.cn-north-4.dcs.myhuaweicloud.com:6379
password: rMof*kkr!mfO7MHW
system:
env: develop
addr: 8001
db-type: mysql
oss-type: local
use-multipoint: false
zap:
level: warn
format: console
prefix: '[NFT-ADMIN]'
director: log
link-name: nft.log
showLine: true
encode-level: LowercaseColorLevelEncoder
stacktrace-key: stacktrace
log-in-console: true
paypal:
env: SandBox
client-id: Af7cbDvcc0qBEZDWgGU3ATZFJePJnFl-UH6foaGzmOu6w_8l1ewZRv88CO39HA0X_ATSR-TP_ZvM_t55
secret: EFsM94NOvKscr6J-U18rtVp0AIZXlrqWwjXP-vqnNXQ8s2c9TpLQo2hFuf0gYUJg4pjPonqCD4T7nrdW
return-url: https://admin-dev.bkbackground.com
cancel-url: https://admin-dev.bkbackground.com
notify-url: https://admin-api-dev.bkbackground.com

78
config.yaml

@ -0,0 +1,78 @@
autocode:
transfer-restart: true
root: /Users/wenwu/Desktop/project/BKB-N
server: /admin-api
server-api: /api/admin
server-initialize: /initialize
server-model: /model
server-request: /model/request/
server-router: /router
server-service: /service
web: /web/src
web-api: /api
web-form: /view
web-table: /view
web-flow: /view
captcha:
key-long: 6
img-width: 240
img-height: 80
casbin:
model-path: ./resource/rbac_model.conf
email:
to: xxx@qq.com
port: 465
from: xxx@163.com
host: smtp.163.com
is-ssl: true
secret: xxx
nickname: test
jwt:
signing-key: qmPlus
expires-time: 604800
buffer-time: 86400
local:
path: uploads/file
mysql:
path: 172.16.0.26:3306
config: charset=utf8mb4&parseTime=True&loc=Local
db-name: bkb
username: bkbrd
password: yJGQ3hlV#*4nTJrn
max-idle-conns: 10
max-open-conns: 100
log-mode: info
log-zap: ""
redis:
db: 1
# addr: 172.16.0.239:6379
# password: bkbrd:!Fgcye*HGs*Z&q0p
addr: redis-6715eafa-8e3f-4014-9659-ac647bd1ef46.cn-north-4.dcs.myhuaweicloud.com:6379
password: rMof*kkr!mfO7MHW
system:
env: develop
addr: 8001
db-type: mysql
oss-type: local
use-multipoint: false
zap:
level: warn
format: console
prefix: '[NFT-ADMIN]'
director: log
link-name: nft.log
showLine: true
encode-level: LowercaseColorLevelEncoder
stacktrace-key: stacktrace
log-in-console: true
paypal:
env: SandBox
client-id: Af7cbDvcc0qBEZDWgGU3ATZFJePJnFl-UH6foaGzmOu6w_8l1ewZRv88CO39HA0X_ATSR-TP_ZvM_t55
secret: EFsM94NOvKscr6J-U18rtVp0AIZXlrqWwjXP-vqnNXQ8s2c9TpLQo2hFuf0gYUJg4pjPonqCD4T7nrdW
return-url: https://admin-dev.bkbackground.com
cancel-url: https://admin-dev.bkbackground.com
notify-url: https://admin-api-dev.bkbackground.com

18
config/auto_code.go

@ -0,0 +1,18 @@
package config
type Autocode struct {
TransferRestart bool `mapstructure:"transfer-restart" json:"transferRestart" yaml:"transfer-restart"`
Root string `mapstructure:"root" json:"root" yaml:"root"`
Server string `mapstructure:"server" json:"server" yaml:"server"`
SApi string `mapstructure:"server-api" json:"serverApi" yaml:"server-api"`
SInitialize string `mapstructure:"server-initialize" json:"serverInitialize" yaml:"server-initialize"`
SModel string `mapstructure:"server-model" json:"serverModel" yaml:"server-model"`
SRequest string `mapstructure:"server-request" json:"serverRequest" yaml:"server-request"`
SRouter string `mapstructure:"server-router" json:"serverRouter" yaml:"server-router"`
SService string `mapstructure:"server-service" json:"serverService" yaml:"server-service"`
Web string `mapstructure:"web" json:"web" yaml:"web"`
WApi string `mapstructure:"web-api" json:"webApi" yaml:"web-api"`
WForm string `mapstructure:"web-form" json:"webForm" yaml:"web-form"`
WTable string `mapstructure:"web-table" json:"webTable" yaml:"web-table"`
WFlow string `mapstructure:"web-flow" json:"webFlow" yaml:"web-flow"`
}

7
config/captcha.go

@ -0,0 +1,7 @@
package config
type Captcha struct {
KeyLong int `mapstructure:"key-long" json:"keyLong" yaml:"key-long"` // 验证码长度
ImgWidth int `mapstructure:"img-width" json:"imgWidth" yaml:"img-width"` // 验证码宽度
ImgHeight int `mapstructure:"img-height" json:"imgHeight" yaml:"img-height"` // 验证码高度
}

5
config/casbin.go

@ -0,0 +1,5 @@
package config
type Casbin struct {
ModelPath string `mapstructure:"model-path" json:"modelPath" yaml:"model-path"` // 存放casbin模型的相对路径
}

26
config/config.go

@ -0,0 +1,26 @@
package config
type Server struct {
JWT JWT `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"`
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
Email Email `mapstructure:"email" json:"email" yaml:"email"`
Casbin Casbin `mapstructure:"casbin" json:"casbin" yaml:"casbin"`
System System `mapstructure:"system" json:"system" yaml:"system"`
Captcha Captcha `mapstructure:"captcha" json:"captcha" yaml:"captcha"`
// auto
AutoCode Autocode `mapstructure:"autoCode" json:"autoCode" yaml:"autoCode"`
// gorm
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
GormSettings GormSettings `mapstructure:"gorm-settings" json:"gormSettings" yaml:"gorm-settings"`
// oss
Minio Minio `mapstructure:"minio" json:"minio" yaml:"minio"`
Local Local `mapstructure:"local" json:"local" yaml:"local"`
Qiniu Qiniu `mapstructure:"qiniu" json:"qiniu" yaml:"qiniu"`
AliyunOSS AliyunOSS `mapstructure:"aliyun-oss" json:"aliyunOSS" yaml:"aliyun-oss"`
TencentCOS TencentCOS `mapstructure:"tencent-cos" json:"tencentCOS" yaml:"tencent-cos"`
Excel Excel `mapstructure:"excel" json:"excel" yaml:"excel"`
Timer Timer `mapstructure:"timer" json:"timer" yaml:"timer"`
JPush JPush `mapstructure:"jpush" json:"jpush" yaml:"jpush"`
Paypal Paypal `mapstructure:"paypal" json:"paypal" yaml:"paypal"`
}

11
config/email.go

@ -0,0 +1,11 @@
package config
type Email struct {
To string `mapstructure:"to" json:"to" yaml:"to"` // 收件人:多个以英文逗号分隔
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口
From string `mapstructure:"from" json:"from" yaml:"from"` // 收件人
Host string `mapstructure:"host" json:"host" yaml:"host"` // 服务器地址
IsSSL bool `mapstructure:"is-ssl" json:"isSSL" yaml:"is-ssl"` // 是否SSL
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // 密钥
Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称
}

5
config/excel.go

@ -0,0 +1,5 @@
package config
type Excel struct {
Dir string `mapstructure:"dir" json:"dir" yaml:"dir"`
}

21
config/gorm.go

@ -0,0 +1,21 @@
package config
type Mysql struct {
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址:端口
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
}
func (m *Mysql) Dsn() string {
return m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
}
func (m *Mysql) GetLogMode() string {
return m.LogMode
}

10
config/gorm_settings.go

@ -0,0 +1,10 @@
package config
type GormSettings struct {
Settings []Settings `mapstructure:"settings" json:"settings" yaml:"settings"`
}
type Settings struct {
DsnName string `mapstructure:"dsn-name" json:"dsnName" yaml:"dsn-name"`
BindTables []interface{} `mapstructure:"bind-tables" json:"bindTables" yaml:"bind-tables"`
}

8
config/jpush.go

@ -0,0 +1,8 @@
package config
type JPush struct {
Appkey string `mapstructure:"appkey" json:"appkey" yaml:"appkey"` //appkey
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` //密钥
AllUserSign string `mapstructure:"all-user-sign" json:"allUserSign" yaml:"all-user-sign"` //所有用户标签
AndroidIntent string `mapstructure:"android-intent" json:"androidIntent" yaml:"android-intent"` //安卓厂商通道包名
}

7
config/jwt.go

@ -0,0 +1,7 @@
package config
type JWT struct {
SigningKey string `mapstructure:"signing-key" json:"signingKey" yaml:"signing-key"` // jwt签名
ExpiresTime int64 `mapstructure:"expires-time" json:"expiresTime" yaml:"expires-time"` // 过期时间
BufferTime int64 `mapstructure:"buffer-time" json:"bufferTime" yaml:"buffer-time"` // 缓冲时间
}

8
config/minio.go

@ -0,0 +1,8 @@
package config
type Minio struct {
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"` //端点
AccessKeyID string `mapstructure:"accessKeyID" json:"accessKeyID" yaml:"access-key-id"` //用户ID
SecretAccessKey string `mapstructure:"secretAccessKey" json:"secretAccessKey" yaml:"secret-access-key"` //密钥
UseSSL bool `mapstructure:"useSSL" json:"useSSL" yaml:"use-ssl"` //是否使用ssl
}

31
config/oss.go

@ -0,0 +1,31 @@
package config
type Local struct {
Path string `mapstructure:"path" json:"path" yaml:"path"` // 本地文件路径
}
type Qiniu struct {
Zone string `mapstructure:"zone" json:"zone" yaml:"zone"` // 存储区域
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"` // 空间名称
ImgPath string `mapstructure:"img-path" json:"imgPath" yaml:"img-path"` // CDN加速域名
UseHTTPS bool `mapstructure:"use-https" json:"useHttps" yaml:"use-https"` // 是否使用https
AccessKey string `mapstructure:"access-key" json:"accessKey" yaml:"access-key"` // 秘钥AK
SecretKey string `mapstructure:"secret-key" json:"secretKey" yaml:"secret-key"` // 秘钥SK
UseCdnDomains bool `mapstructure:"use-cdn-domains" json:"useCdnDomains" yaml:"use-cdn-domains"` // 上传是否使用CDN上传加速
}
type AliyunOSS struct {
Endpoint string `mapstructure:"endpoint" json:"endpoint" yaml:"endpoint"`
AccessKeyId string `mapstructure:"access-key-id" json:"accessKeyId" yaml:"access-key-id"`
AccessKeySecret string `mapstructure:"access-key-secret" json:"accessKeySecret" yaml:"access-key-secret"`
BucketName string `mapstructure:"bucket-name" json:"bucketName" yaml:"bucket-name"`
BucketUrl string `mapstructure:"bucket-url" json:"bucketUrl" yaml:"bucket-url"`
}
type TencentCOS struct {
Bucket string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`
Region string `mapstructure:"region" json:"region" yaml:"region"`
SecretID string `mapstructure:"secret-id" json:"secretID" yaml:"secret-id"`
SecretKey string `mapstructure:"secret-key" json:"secretKey" yaml:"secret-key"`
BaseURL string `mapstructure:"base-url" json:"baseURL" yaml:"base-url"`
PathPrefix string `mapstructure:"path-prefix" json:"pathPrefix" yaml:"path-prefix"`
}

10
config/paypal.go

@ -0,0 +1,10 @@
package config
type Paypal struct {
Env string `mapstructure:"env" json:"env" yaml:"env"` //端点
ClientID string `mapstructure:"client-id" json:"client-id" yaml:"client-id"` //用户ID
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` //密钥
ReturnUrl string `mapstructure:"return-url" json:"return-url" yaml:"return-url"` //支付完成跳转
CancelUrl string `mapstructure:"cancel-url" json:"cancel-url" yaml:"cancel-url"` //取消支付跳转
NotifyUrl string `mapstructure:"notify-url" json:"notify-url" yaml:"notify-url"` // 支付结果通知
}

7
config/redis.go

@ -0,0 +1,7 @@
package config
type Redis struct {
DB int `mapstructure:"db" json:"db" yaml:"db"` // redis的哪个数据库
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"` // 服务器地址:端口
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码
}

9
config/system.go

@ -0,0 +1,9 @@
package config
type System struct {
Env string `mapstructure:"env" json:"env" yaml:"env"` // 环境值
Addr int `mapstructure:"addr" json:"addr" yaml:"addr"` // 端口值
DbType string `mapstructure:"db-type" json:"dbType" yaml:"db-type"` // 数据库类型:mysql(默认)|sqlite|sqlserver|postgresql
OssType string `mapstructure:"oss-type" json:"ossType" yaml:"oss-type"` // Oss类型
UseMultipoint bool `mapstructure:"use-multipoint" json:"useMultipoint" yaml:"use-multipoint"` // 多点登录拦截
}

13
config/timer.go

@ -0,0 +1,13 @@
package config
type Timer struct {
Start bool `mapstructure:"start" json:"start" yaml:"start"` // 是否启用
Spec string `mapstructure:"spec" json:"spec" yaml:"spec"` // CRON表达式
Detail []Detail `mapstructure:"detail" json:"detail" yaml:"detail"`
}
type Detail struct {
TableName string `mapstructure:"tableName" json:"tableName" yaml:"tableName"` // 需要清理的表名
CompareField string `mapstructure:"compareField" json:"compareField" yaml:"compareField"` // 需要比较时间的字段
Interval string `mapstructure:"interval" json:"interval" yaml:"interval"` // 时间间隔
}

13
config/zap.go

@ -0,0 +1,13 @@
package config
type Zap struct {
Level string `mapstructure:"level" json:"level" yaml:"level"` // 级别
Format string `mapstructure:"format" json:"format" yaml:"format"` // 输出
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 日志前缀
Director string `mapstructure:"director" json:"director" yaml:"director"` // 日志文件夹
LinkName string `mapstructure:"link-name" json:"linkName" yaml:"link-name"` // 软链接名称
ShowLine bool `mapstructure:"show-line" json:"showLine" yaml:"showLine"` // 显示行
EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"` // 编码级
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"` // 栈名
LogInConsole bool `mapstructure:"log-in-console" json:"logInConsole" yaml:"log-in-console"` // 输出控制台
}

38
core/server.go

@ -0,0 +1,38 @@
package core
import (
"fmt"
"pure-admin/global"
"pure-admin/initialize"
"time"
"go.uber.org/zap"
)
type server interface {
ListenAndServe() error
}
func RunWindowsServer() {
// 初始化redis服务
initialize.Redis()
//NewRedisEventSink(global.MG_CONFIG.Redis.DB, "expired")
Router := initialize.Routers()
Router.Static("/form-generator", "./resource/page")
address := fmt.Sprintf(":%d", global.MG_CONFIG.System.Addr)
s := initServer(address, Router)
// 保证文本顺序输出
// In order to ensure that the text order output can be deleted
time.Sleep(10 * time.Microsecond)
global.MG_LOG.Info("server run success on ", zap.String("address", address))
fmt.Printf(`
欢迎使用 MangGuoNews-Admin
当前版本:V2.4.2
默认自动化文档地址:http://127.0.0.1%s/swagger/index.html
默认前端文件运行地址:http://127.0.0.1%s
`, address, address)
global.MG_LOG.Error(s.ListenAndServe().Error())
}

17
core/server_other.go

@ -0,0 +1,17 @@
// +build !windows
package core
import (
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
"time"
)
func initServer(address string, router *gin.Engine) server {
s := endless.NewServer(address, router)
s.ReadHeaderTimeout = 10 * time.Millisecond
s.WriteTimeout = 10 * time.Second
s.MaxHeaderBytes = 1 << 20
return s
}

19
core/server_win.go

@ -0,0 +1,19 @@
// +build windows
package core
import (
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func initServer(address string, router *gin.Engine) server {
return &http.Server{
Addr: address,
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
}

57
core/viper.go

@ -0,0 +1,57 @@
package core
import (
"flag"
"fmt"
"os"
"path/filepath"
"pure-admin/global"
_ "pure-admin/packfile"
"pure-admin/utils"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
func Viper(path ...string) *viper.Viper {
var config string
if len(path) == 0 {
flag.StringVar(&config, "c", "", "choose config file.")
flag.Parse()
if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
if configEnv := os.Getenv(utils.ConfigEnv); configEnv == "" {
config = utils.ConfigFile
fmt.Printf("您正在使用config的默认值,config的路径为%v\n", utils.ConfigFile)
} else {
config = configEnv
fmt.Printf("您正在使用MG_CONFIG环境变量,config的路径为%v\n", config)
}
} else {
fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
}
} else {
config = path[0]
fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
}
v := viper.New()
v.SetConfigFile(config)
v.SetConfigType("yaml")
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&global.MG_CONFIG); err != nil {
fmt.Println(err)
}
})
if err := v.Unmarshal(&global.MG_CONFIG); err != nil {
fmt.Println(err)
}
global.MG_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
return v
}

103
core/zap.go

@ -0,0 +1,103 @@
package core
import (
"fmt"
"os"
"pure-admin/global"
"pure-admin/utils"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var level zapcore.Level
func Zap() (logger *zap.Logger) {
if ok, _ := utils.PathExists(global.MG_CONFIG.Zap.Director); !ok { // 判断是否有Director文件夹
fmt.Printf("create %v directory\n", global.MG_CONFIG.Zap.Director)
_ = os.Mkdir(global.MG_CONFIG.Zap.Director, os.ModePerm)
}
switch global.MG_CONFIG.Zap.Level { // 初始化配置文件的Level
case "debug":
level = zap.DebugLevel
case "info":
level = zap.InfoLevel
case "warn":
level = zap.WarnLevel
case "error":
level = zap.ErrorLevel
case "dpanic":
level = zap.DPanicLevel
case "panic":
level = zap.PanicLevel
case "fatal":
level = zap.FatalLevel
default:
level = zap.InfoLevel
}
if level == zap.DebugLevel || level == zap.ErrorLevel {
logger = zap.New(getEncoderCore(), zap.AddStacktrace(level))
} else {
logger = zap.New(getEncoderCore())
}
if global.MG_CONFIG.Zap.ShowLine {
logger = logger.WithOptions(zap.AddCaller())
}
return logger
}
// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig() (config zapcore.EncoderConfig) {
config = zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: global.MG_CONFIG.Zap.StacktraceKey,
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: CustomTimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
}
switch {
case global.MG_CONFIG.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
config.EncodeLevel = zapcore.LowercaseLevelEncoder
case global.MG_CONFIG.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
config.EncodeLevel = zapcore.LowercaseColorLevelEncoder
case global.MG_CONFIG.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
config.EncodeLevel = zapcore.CapitalLevelEncoder
case global.MG_CONFIG.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
config.EncodeLevel = zapcore.CapitalColorLevelEncoder
default:
config.EncodeLevel = zapcore.LowercaseLevelEncoder
}
return config
}
// getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
if global.MG_CONFIG.Zap.Format == "json" {
return zapcore.NewJSONEncoder(getEncoderConfig())
}
return zapcore.NewConsoleEncoder(getEncoderConfig())
}
// getEncoderCore 获取Encoder的zapcore.Core
func getEncoderCore() (core zapcore.Core) {
writer, err := utils.GetWriteSyncer() // 使用file-rotatelogs进行日志分割
if err != nil {
fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
return
}
return zapcore.NewCore(getEncoder(), writer, level)
}
// 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format(global.MG_CONFIG.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}

0
deploy/.gitkeep

24
deploy/admin-api-deployment.yaml

@ -0,0 +1,24 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{project}}
namespace: {{nameSpace}}
spec:
replicas: 1
selector:
matchLabels:
app: {{project}}
template:
metadata:
labels:
app: {{project}}
spec:
containers:
- name: {{project}}
image: {{dockerServer}}/{{dockerOrg}}/{{project}}:{{version}}
imagePullPolicy: Always
ports:
- containerPort: 8001
imagePullSecrets:
- name: bkb-images-secret

13
deploy/admin-api-service.yaml

@ -0,0 +1,13 @@
apiVersion: v1
kind: Service
metadata:
name: {{project}}
namespace: {{nameSpace}}
spec:
ports:
- port: 80
targetPort: 8001
name: {{project}}
selector:
app: {{project}}
type: ClusterIP

11770
docs/docs.go

File diff suppressed because it is too large

11745
docs/swagger.json

File diff suppressed because it is too large

7674
docs/swagger.yaml

File diff suppressed because it is too large

1006
dto/customer.pb.go

File diff suppressed because it is too large

73
dto/customer.proto

@ -0,0 +1,73 @@
syntax = "proto3";
package api;
option go_package = "shop-api/dto";
message LoginRequest{
string phone = 1;
string code = 2;
}
message SmsRequest {
string phone = 1;
}
message WithdrawRequest {
string phone = 1;//
string code = 2; //
double amount = 3;//
int32 accountID = 4;//id
}
message CreateAddressRequest{
string firstName = 1;
string lastName = 2;
string street = 3;
string phone = 4;
string bldg = 5;
string city = 6;
string state = 7;
string zipCode = 8;
int32 default = 9;
}
message UpdateAddressRequest{
int64 id = 1;
string firstName = 2;
string lastName = 3;
string street = 4;
string phone = 5;
string bldg = 6;
string city = 7;
string state = 8;
string zipCode = 9;
int32 default = 10;
}
message IdRequest{
int64 id = 1;
}
message CreateOrderRequest {
string code = 1;//
int32 skuID = 2;// skuId
int32 number = 3;//
int32 addressID = 4;// id
int32 payMode = 5;// 1:paypal
string platform = 6;
}
message PaybackBody{
string attach = 1;
string out_trade_no = 2;
string transaction_id = 3;
string pay_id = 4;
string capture_id = 5;
string status = 6;
string message = 7;
string resource_type = 8;
}
message OrderData{
int64 all = 1;//
int64 unpaid = 2;//
int64 unship = 3;//
int64 shipped = 4;//
int64 finished = 5;//
int64 cancel = 6;//
}

24
global/global.go

@ -0,0 +1,24 @@
package global
import (
"pure-admin/config"
"pure-admin/initialize/api"
"pure-admin/utils/timer"
"github.com/go-redis/redis"
"github.com/minio/minio-go/v7"
"github.com/spf13/viper"
"go.uber.org/zap"
"gorm.io/gorm"
)
var (
MG_DB *gorm.DB
MG_REDIS *redis.Client
MG_CONFIG config.Server
MG_VP *viper.Viper
MG_LOG *zap.Logger
PAY_CLIENT api.GreeterClient
MG_MINIO *minio.Client
MG_Timer timer.Timer = timer.NewTimerTask()
)

56
global/model.go

@ -0,0 +1,56 @@
package global
import (
"time"
"gorm.io/gorm"
)
type MG_MODEL struct {
ID uint `gorm:"AUTO_INCREMENT;PRIMARY_KEY;" json:"id"` // 主键ID
CreatedAt time.Time `gorm:"index" json:"createdAt"` // 创建时间
UpdatedAt time.Time `gorm:"index" json:"updatedAt"` // 更新时间
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` // 删除时间
}
type TIME_MODEL struct {
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt gorm.DeletedAt `json:"-"`
}
type TIME_MODEL_VIEW struct {
CreatedAtStr string `gorm:"-" json:"createdAt"`
UpdatedAtStr string `gorm:"-" json:"updatedAt"`
}
type BASE_ID_STR struct {
ID string `gorm:"primary_key;size:50" json:"id" form:"id"` //主键
}
type ID_BACKUP_STR struct {
ID string `gorm:"primary_key;size:50" json:"id" form:"id"` //主键
// Kid int `json:"kid" form:"kid"`
Backup int `json:"backup" form:"backup"`
Check int `json:"check" form:"check"`
CurrentCheck string `json:"currentCheck" form:"currentCheck"`
}
type BASE_ID struct {
ID uint `gorm:"AUTO_INCREMENT;primary_key;" json:"id" form:"id"` //主键
}
type ID_SORT struct {
ID string `json:"id"`
Sort int `json:"sort"`
}
type ID_COUNT struct {
ID string `json:"id"`
Count int `json:"count"`
}
type BASE_ID_SORT struct {
ID uint `json:"id"`
Sort int `json:"sort"`
}

159
go.mod

@ -0,0 +1,159 @@
module pure-admin
go 1.20
require (
github.com/aliyun/aliyun-oss-go-sdk v2.2.9+incompatible
github.com/casbin/casbin/v2 v2.77.2
github.com/casbin/gorm-adapter/v3 v3.20.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fsnotify/fsnotify v1.6.0
github.com/fvbock/endless v0.0.0-20170109170031-447134032cb6
github.com/gin-gonic/gin v1.9.1
github.com/go-kratos/kratos/contrib/registry/nacos/v2 v2.0.0-20231219111544-85740b179b09
github.com/go-kratos/kratos/v2 v2.7.2
github.com/go-redis/redis v6.15.9+incompatible
github.com/go-sql-driver/mysql v1.7.1
github.com/gookit/color v1.5.4
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/minio/minio-go/v7 v7.0.63
github.com/mojocn/base64Captcha v1.3.5
github.com/nacos-group/nacos-sdk-go v1.1.4
github.com/pili-engineering/pili-sdk-go.v2 v0.0.0-20200608105005-bb506e708987
github.com/qiniu/api.v7/v7 v7.8.2
github.com/robfig/cron/v3 v3.0.1
github.com/satori/go.uuid v1.2.0
github.com/spf13/viper v1.17.0
github.com/swaggo/swag v1.16.2
github.com/taskcluster/slugid-go v1.1.0
github.com/tencentyun/cos-go-sdk-v5 v0.7.44
github.com/unrolled/secure v1.13.0
github.com/xuri/excelize/v2 v2.8.0
go.uber.org/zap v1.26.0
google.golang.org/genproto/googleapis/api v0.0.0-20230913181813-007df8e322eb
google.golang.org/grpc v1.58.2
gorm.io/driver/mysql v1.5.2
gorm.io/gorm v1.25.5
)
require (
github.com/aliyun/alibaba-cloud-sdk-go v1.61.18 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-kratos/aegis v0.2.0 // indirect
github.com/go-playground/form/v4 v4.2.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
google.golang.org/genproto v0.0.0-20230913181813-007df8e322eb // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230920204549-e6e6cdab5c13 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
)
require (
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/clbanning/mxj v1.8.4 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/gzip v0.0.6 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/glebarez/go-sqlite v1.20.3 // indirect
github.com/glebarez/sqlite v1.7.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.13.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.1 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.12.0 // indirect
github.com/jackc/pgx/v4 v4.17.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jonboulle/clockwork v0.4.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lestrrat-go/strftime v1.0.6 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/microsoft/go-mssqldb v0.17.0 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/mozillazg/go-httpheader v0.2.1 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/onsi/gomega v1.28.0 // indirect
github.com/pborman/uuid v1.2.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/qiniu/x v1.10.5 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/sagikazarmark/locafero v0.3.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.10.0 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/swaggo/gin-swagger v1.3.0
github.com/tidwall/gjson v1.14.4 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca // indirect
github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/image v0.11.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.13.0 // indirect
google.golang.org/protobuf v1.31.0
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/postgres v1.4.4 // indirect
gorm.io/driver/sqlserver v1.4.1 // indirect
gorm.io/plugin/dbresolver v1.3.0 // indirect
modernc.org/libc v1.22.2 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.20.3 // indirect
)

1046
go.sum

File diff suppressed because it is too large

2205
initialize/api/greeter.pb.go

File diff suppressed because it is too large

203
initialize/api/greeter.proto

@ -0,0 +1,203 @@
syntax = "proto3";
package api;
import "google/api/annotations.proto";
import "google/protobuf/empty.proto";
option go_package = "bkb-payment/api";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc Ping (google.protobuf.Empty) returns (PingReply) {
option (google.api.http) = {
get: "/ping"
};
}
rpc CountryList (google.protobuf.Empty) returns (CountryReply) {
option (google.api.http) = {
get: "/country/list"
};
}
rpc DistrictCascade (DistrictRequest) returns (DistrictReply) {
option (google.api.http) = {
get: "/district/cascade"
};
}
rpc PayTransactionApp(PayTransRequest) returns (PayTransResponse) {
option (google.api.http) = {
post: "/pay/transaction"
body: "*"
};
}
rpc GetPaymentUrl(PayUrlRequest) returns (PayUrlResponse) {
option (google.api.http) = {
get: "/pay/url"
};
}
rpc PayTransactionAppUrl(PayTransRequest) returns (PayUrlResponse) {
option (google.api.http) = {
post: "/pay/transaction/url"
body: "*"
};
}
rpc SuccessPayback(PaybackRequest) returns (PaybackResp) {
option (google.api.http) = {
post: "/pay/payback"
body: "*"
};
}
rpc PaypalPayback(PaypalWebhook) returns (PaybackResp) {
option (google.api.http) = {
post: "/paypal/callback"
body: "*"
};
}
rpc PayoutsAppUrl(PayoutRequest) returns (PayUrlResponse) {
option (google.api.http) = {
post: "/pay/payouts"
body: "*"
};
}
rpc GetPayTransaction(google.protobuf.Empty) returns (GetPayTransactionResp) {
option (google.api.http) = {
get: "/pay/transaction/outTradeNo"
};
}
rpc CloseBill(CloseBillRequest) returns (PingReply) {
}
// rpc ClosePayTransaction(google.protobuf.Empty) returns (PingReply) {
// option (google.api.http) = {
// post: "/pay/transaction/outTradeNo/close"
// };
// }
}
// The response message containing the greetings
message PingReply {
string message = 1;
}
message Country{
int32 id = 1;
string name = 2;
}
message CountryReply{
repeated Country list = 1;
}
message DistrictRequest {
int32 country = 1;
}
message District {
string label = 1;
string adcode = 2;
int32 parentId = 3;
repeated District children = 4;
}
message DistrictReply{
repeated District list = 1;
}
message PayTransRequest{
string appid = 1;
string mchid = 2;
string out_trade_no = 3;
string attach = 4;
string notify_url = 5;
double amount = 6;
string currency = 7;
string pay_channel = 8;
string return_url = 9;
string cancel_url = 10;
}
message PayTransResponse{
string transaction_id = 1;
string status = 2;
string message = 3;
}
message PayUrlRequest{
string mchid = 1;
string pay_channel = 2;
string transaction_id = 3;
}
message PayUrlResponse{
string pay_channel = 1;
string pay_id = 2;
string pay_return = 3;
string pay_status = 4;
}
message PaybackRequest{
string mchid = 1;
string pay_channel = 2;
string pay_id = 3;
string event_type = 4;
}
message PaybackResp{
string out_trade_no = 1;
string trade_state = 2;
string message = 3;
}
message PayoutRequest{
string appid = 1;
string mchid = 2;
string out_trade_no = 3;
string attach = 4;
string notify_url = 5;
double amount = 6;
string currency = 7;
string pay_channel = 8;
string paypal_name = 9;
}
message GetPayTransOutTradeNoRequest{
string appid = 1;
string mchid = 2;
string out_trade_no = 3;
}
message GetPayTransactionResp{
GetPayTransaction data = 1;
}
message GetPayTransaction{
string appid = 1;
string mchid = 2;
}
message CloseBillRequest{
string transaction_id = 1;
}
message PaypalWebhook{
string id = 1;
string create_time = 2;
string resource_type = 3;
string event_type = 4;
string summary = 5;
PaybackResource resource = 6;
}
message PaybackResource{
string id = 1;
string create_time = 2;
string update_time = 3;
string state = 4;
string status = 5;
repeated PurchaseUnit purchase_units = 6;
BatchHeader batch_header = 7;
}
message PurchaseUnit{
Payment payments = 1;
}
message Payment{
repeated Capture captures = 1;
}
message BatchHeader{
string batch_status = 1;
string payout_batch_id = 2;
SenderBatchHeader sender_batch_header = 3;
}
message SenderBatchHeader{
string sender_batch_id = 1;
}
message Capture{
string id = 1;
string status = 2;
string create_time = 3;
string update_time = 4;
}

482
initialize/api/greeter_grpc.pb.go

@ -0,0 +1,482 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.3.0
// - protoc v3.21.12
// source: greeter.proto
package api
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
emptypb "google.golang.org/protobuf/types/known/emptypb"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
const (
Greeter_Ping_FullMethodName = "/api.Greeter/Ping"
Greeter_CountryList_FullMethodName = "/api.Greeter/CountryList"
Greeter_DistrictCascade_FullMethodName = "/api.Greeter/DistrictCascade"
Greeter_PayTransactionApp_FullMethodName = "/api.Greeter/PayTransactionApp"
Greeter_GetPaymentUrl_FullMethodName = "/api.Greeter/GetPaymentUrl"
Greeter_PayTransactionAppUrl_FullMethodName = "/api.Greeter/PayTransactionAppUrl"
Greeter_SuccessPayback_FullMethodName = "/api.Greeter/SuccessPayback"
Greeter_PaypalPayback_FullMethodName = "/api.Greeter/PaypalPayback"
Greeter_PayoutsAppUrl_FullMethodName = "/api.Greeter/PayoutsAppUrl"
Greeter_GetPayTransaction_FullMethodName = "/api.Greeter/GetPayTransaction"
Greeter_CloseBill_FullMethodName = "/api.Greeter/CloseBill"
)
// GreeterClient is the client API for Greeter service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GreeterClient interface {
// Sends a greeting
Ping(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*PingReply, error)
CountryList(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*CountryReply, error)
DistrictCascade(ctx context.Context, in *DistrictRequest, opts ...grpc.CallOption) (*DistrictReply, error)
PayTransactionApp(ctx context.Context, in *PayTransRequest, opts ...grpc.CallOption) (*PayTransResponse, error)
GetPaymentUrl(ctx context.Context, in *PayUrlRequest, opts ...grpc.CallOption) (*PayUrlResponse, error)
PayTransactionAppUrl(ctx context.Context, in *PayTransRequest, opts ...grpc.CallOption) (*PayUrlResponse, error)
SuccessPayback(ctx context.Context, in *PaybackRequest, opts ...grpc.CallOption) (*PaybackResp, error)
PaypalPayback(ctx context.Context, in *PaypalWebhook, opts ...grpc.CallOption) (*PaybackResp, error)
PayoutsAppUrl(ctx context.Context, in *PayoutRequest, opts ...grpc.CallOption) (*PayUrlResponse, error)
GetPayTransaction(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetPayTransactionResp, error)
CloseBill(ctx context.Context, in *CloseBillRequest, opts ...grpc.CallOption) (*PingReply, error)
}
type greeterClient struct {
cc grpc.ClientConnInterface
}
func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
return &greeterClient{cc}
}
func (c *greeterClient) Ping(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*PingReply, error) {
out := new(PingReply)
err := c.cc.Invoke(ctx, Greeter_Ping_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) CountryList(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*CountryReply, error) {
out := new(CountryReply)
err := c.cc.Invoke(ctx, Greeter_CountryList_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) DistrictCascade(ctx context.Context, in *DistrictRequest, opts ...grpc.CallOption) (*DistrictReply, error) {
out := new(DistrictReply)
err := c.cc.Invoke(ctx, Greeter_DistrictCascade_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) PayTransactionApp(ctx context.Context, in *PayTransRequest, opts ...grpc.CallOption) (*PayTransResponse, error) {
out := new(PayTransResponse)
err := c.cc.Invoke(ctx, Greeter_PayTransactionApp_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) GetPaymentUrl(ctx context.Context, in *PayUrlRequest, opts ...grpc.CallOption) (*PayUrlResponse, error) {
out := new(PayUrlResponse)
err := c.cc.Invoke(ctx, Greeter_GetPaymentUrl_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) PayTransactionAppUrl(ctx context.Context, in *PayTransRequest, opts ...grpc.CallOption) (*PayUrlResponse, error) {
out := new(PayUrlResponse)
err := c.cc.Invoke(ctx, Greeter_PayTransactionAppUrl_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) SuccessPayback(ctx context.Context, in *PaybackRequest, opts ...grpc.CallOption) (*PaybackResp, error) {
out := new(PaybackResp)
err := c.cc.Invoke(ctx, Greeter_SuccessPayback_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) PaypalPayback(ctx context.Context, in *PaypalWebhook, opts ...grpc.CallOption) (*PaybackResp, error) {
out := new(PaybackResp)
err := c.cc.Invoke(ctx, Greeter_PaypalPayback_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) PayoutsAppUrl(ctx context.Context, in *PayoutRequest, opts ...grpc.CallOption) (*PayUrlResponse, error) {
out := new(PayUrlResponse)
err := c.cc.Invoke(ctx, Greeter_PayoutsAppUrl_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) GetPayTransaction(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetPayTransactionResp, error) {
out := new(GetPayTransactionResp)
err := c.cc.Invoke(ctx, Greeter_GetPayTransaction_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *greeterClient) CloseBill(ctx context.Context, in *CloseBillRequest, opts ...grpc.CallOption) (*PingReply, error) {
out := new(PingReply)
err := c.cc.Invoke(ctx, Greeter_CloseBill_FullMethodName, in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
// Sends a greeting
Ping(context.Context, *emptypb.Empty) (*PingReply, error)
CountryList(context.Context, *emptypb.Empty) (*CountryReply, error)
DistrictCascade(context.Context, *DistrictRequest) (*DistrictReply, error)
PayTransactionApp(context.Context, *PayTransRequest) (*PayTransResponse, error)
GetPaymentUrl(context.Context, *PayUrlRequest) (*PayUrlResponse, error)
PayTransactionAppUrl(context.Context, *PayTransRequest) (*PayUrlResponse, error)
SuccessPayback(context.Context, *PaybackRequest) (*PaybackResp, error)
PaypalPayback(context.Context, *PaypalWebhook) (*PaybackResp, error)
PayoutsAppUrl(context.Context, *PayoutRequest) (*PayUrlResponse, error)
GetPayTransaction(context.Context, *emptypb.Empty) (*GetPayTransactionResp, error)
CloseBill(context.Context, *CloseBillRequest) (*PingReply, error)
mustEmbedUnimplementedGreeterServer()
}
// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}
func (UnimplementedGreeterServer) Ping(context.Context, *emptypb.Empty) (*PingReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
}
func (UnimplementedGreeterServer) CountryList(context.Context, *emptypb.Empty) (*CountryReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method CountryList not implemented")
}
func (UnimplementedGreeterServer) DistrictCascade(context.Context, *DistrictRequest) (*DistrictReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method DistrictCascade not implemented")
}
func (UnimplementedGreeterServer) PayTransactionApp(context.Context, *PayTransRequest) (*PayTransResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method PayTransactionApp not implemented")
}
func (UnimplementedGreeterServer) GetPaymentUrl(context.Context, *PayUrlRequest) (*PayUrlResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetPaymentUrl not implemented")
}
func (UnimplementedGreeterServer) PayTransactionAppUrl(context.Context, *PayTransRequest) (*PayUrlResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method PayTransactionAppUrl not implemented")
}
func (UnimplementedGreeterServer) SuccessPayback(context.Context, *PaybackRequest) (*PaybackResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method SuccessPayback not implemented")
}
func (UnimplementedGreeterServer) PaypalPayback(context.Context, *PaypalWebhook) (*PaybackResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method PaypalPayback not implemented")
}
func (UnimplementedGreeterServer) PayoutsAppUrl(context.Context, *PayoutRequest) (*PayUrlResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method PayoutsAppUrl not implemented")
}
func (UnimplementedGreeterServer) GetPayTransaction(context.Context, *emptypb.Empty) (*GetPayTransactionResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetPayTransaction not implemented")
}
func (UnimplementedGreeterServer) CloseBill(context.Context, *CloseBillRequest) (*PingReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method CloseBill not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}
// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
mustEmbedUnimplementedGreeterServer()
}
func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
s.RegisterService(&Greeter_ServiceDesc, srv)
}
func _Greeter_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).Ping(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_Ping_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).Ping(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_CountryList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).CountryList(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_CountryList_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).CountryList(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_DistrictCascade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DistrictRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).DistrictCascade(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_DistrictCascade_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).DistrictCascade(ctx, req.(*DistrictRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_PayTransactionApp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PayTransRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).PayTransactionApp(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_PayTransactionApp_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).PayTransactionApp(ctx, req.(*PayTransRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_GetPaymentUrl_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PayUrlRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).GetPaymentUrl(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_GetPaymentUrl_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).GetPaymentUrl(ctx, req.(*PayUrlRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_PayTransactionAppUrl_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PayTransRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).PayTransactionAppUrl(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_PayTransactionAppUrl_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).PayTransactionAppUrl(ctx, req.(*PayTransRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_SuccessPayback_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PaybackRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).SuccessPayback(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_SuccessPayback_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).SuccessPayback(ctx, req.(*PaybackRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_PaypalPayback_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PaypalWebhook)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).PaypalPayback(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_PaypalPayback_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).PaypalPayback(ctx, req.(*PaypalWebhook))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_PayoutsAppUrl_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PayoutRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).PayoutsAppUrl(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_PayoutsAppUrl_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).PayoutsAppUrl(ctx, req.(*PayoutRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_GetPayTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).GetPayTransaction(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_GetPayTransaction_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).GetPayTransaction(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
func _Greeter_CloseBill_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CloseBillRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GreeterServer).CloseBill(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Greeter_CloseBill_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GreeterServer).CloseBill(ctx, req.(*CloseBillRequest))
}
return interceptor(ctx, in, info, handler)
}
// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
ServiceName: "api.Greeter",
HandlerType: (*GreeterServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Ping",
Handler: _Greeter_Ping_Handler,
},
{
MethodName: "CountryList",
Handler: _Greeter_CountryList_Handler,
},
{
MethodName: "DistrictCascade",
Handler: _Greeter_DistrictCascade_Handler,
},
{
MethodName: "PayTransactionApp",
Handler: _Greeter_PayTransactionApp_Handler,
},
{
MethodName: "GetPaymentUrl",
Handler: _Greeter_GetPaymentUrl_Handler,
},
{
MethodName: "PayTransactionAppUrl",
Handler: _Greeter_PayTransactionAppUrl_Handler,
},
{
MethodName: "SuccessPayback",
Handler: _Greeter_SuccessPayback_Handler,
},
{
MethodName: "PaypalPayback",
Handler: _Greeter_PaypalPayback_Handler,
},
{
MethodName: "PayoutsAppUrl",
Handler: _Greeter_PayoutsAppUrl_Handler,
},
{
MethodName: "GetPayTransaction",
Handler: _Greeter_GetPayTransaction_Handler,
},
{
MethodName: "CloseBill",
Handler: _Greeter_CloseBill_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "greeter.proto",
}

100
initialize/gorm.go

@ -0,0 +1,100 @@
package initialize
import (
"os"
"pure-admin/global"
"pure-admin/initialize/internal"
"pure-admin/model"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//@function: Gorm
//@description: 初始化数据库并产生数据库全局变量
//@return: *gorm.DB
func Gorm() *gorm.DB {
switch global.MG_CONFIG.System.DbType {
case "mysql":
return GormMysql()
default:
return GormMysql()
}
}
// MysqlTables
//@function: MysqlTables
//@description: 注册数据库表专用
//@param: db *gorm.DB
func MysqlTables(db *gorm.DB) {
err := db.AutoMigrate(
model.SysAuthority{},
model.SysApi{},
model.SysBaseMenu{},
model.JwtBlacklist{},
model.SysOperationRecord{},
model.SellerStore{},
model.Withdrawal{},
//model.SysDictionary{},
//model.SysDictionaryDetail{},
//model.ExaFileUploadAndDownload{},
//model.ExaFile{},
//model.ExaFileChunk{},
//model.ExaCustomer{},
//model.ExaSimpleUploader{},
// Code generated by pure-admin Begin; DO NOT EDIT.
model.User{},
model.Application{},
model.Organization{},
model.Provider{},
model.Business{},
model.MissionRecommend{},
model.MissionClaimVideo{},
model.Tags{},
model.PlatformAuth{},
model.TagRelation{},
model.Banner{},
model.StatisticMissionDaily{},
// Code generated by pure-admin End; DO NOT EDIT.
)
if err != nil {
global.MG_LOG.Error("register table failed", zap.Any("err", err))
os.Exit(0)
}
global.MG_LOG.Info("register table success")
}
// @function: GormMysql
// @description: 初始化Mysql数据库
// @return: *gorm.DB
func GormMysql() *gorm.DB {
m := global.MG_CONFIG.Mysql
if m.Dbname == "" {
return nil
}
dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), internal.Gorm.Config()); err != nil {
//global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
//os.Exit(0)
//return nil
return nil
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}

54
initialize/grpc.go

@ -0,0 +1,54 @@
package initialize
import (
"context"
"fmt"
"github.com/go-kratos/kratos/contrib/registry/nacos/v2"
"pure-admin/global"
"pure-admin/initialize/api"
"time"
"github.com/go-kratos/kratos/v2/middleware/recovery"
"github.com/go-kratos/kratos/v2/transport/grpc"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
)
func init() {
sc := []constant.ServerConfig{
*constant.NewServerConfig("72535c70-8d6d-400f-9893-4bb3e634f682.nacos.cn-north-4.cse.myhuaweicloud.com", 8848),
}
cc := constant.ClientConfig{
NamespaceId: "dev",
TimeoutMs: 5000,
Username: "nacos",
Password: "nacos",
}
func() {
client, err := clients.NewNamingClient(
vo.NacosClientParam{
ServerConfigs: sc,
ClientConfig: &cc,
},
)
if err != nil {
fmt.Println(err)
panic(err)
}
r := nacos.New(client)
conn, err := grpc.DialInsecure(
context.Background(),
grpc.WithEndpoint("discovery:///bkb.payment.grpc"),
grpc.WithDiscovery(r),
grpc.WithMiddleware(recovery.Recovery()),
grpc.WithTimeout(10*time.Second),
)
if err != nil {
panic(err)
}
global.PAY_CLIENT = api.NewGreeterClient(conn)
}()
}

52
initialize/internal/gorm.go

@ -0,0 +1,52 @@
package internal
import (
"log"
"os"
"pure-admin/global"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type DBBASE interface {
GetLogMode() string
}
var Gorm = new(_gorm)
type _gorm struct{}
// Config gorm 自定义配置
// Author [SliverHorn](https://github.com/SliverHorn)
func (g *_gorm) Config() *gorm.Config {
config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
_default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{
SlowThreshold: 200 * time.Millisecond,
LogLevel: logger.Warn,
Colorful: true,
})
var logMode DBBASE
switch global.MG_CONFIG.System.DbType {
case "mysql":
logMode = &global.MG_CONFIG.Mysql
break
default:
logMode = &global.MG_CONFIG.Mysql
}
switch logMode.GetLogMode() {
case "silent", "Silent":
config.Logger = _default.LogMode(logger.Silent)
case "error", "Error":
config.Logger = _default.LogMode(logger.Error)
case "warn", "Warn":
config.Logger = _default.LogMode(logger.Warn)
case "info", "Info":
config.Logger = _default.LogMode(logger.Info)
default:
config.Logger = _default.LogMode(logger.Info)
}
return config
}

33
initialize/internal/logger.go

@ -0,0 +1,33 @@
package internal
import (
"fmt"
"pure-admin/global"
"gorm.io/gorm/logger"
)
type writer struct {
logger.Writer
}
// NewWriter writer 构造函数
// Author [SliverHorn](https://github.com/SliverHorn)
func NewWriter(w logger.Writer) *writer {
return &writer{Writer: w}
}
// Printf 格式化打印日志
// Author [SliverHorn](https://github.com/SliverHorn)
func (w *writer) Printf(message string, data ...interface{}) {
var logZap bool
switch global.MG_CONFIG.System.DbType {
case "mysql":
logZap = global.MG_CONFIG.Mysql.LogZap
}
if logZap {
global.MG_LOG.Info(fmt.Sprintf(message+"\n", data...))
} else {
w.Writer.Printf(message, data...)
}
}

22
initialize/minio.go

@ -0,0 +1,22 @@
package initialize
import (
"log"
"pure-admin/global"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func Minio() {
minioCfg := global.MG_CONFIG.Minio
// Initialize minio client object.
minioClient, err := minio.New(minioCfg.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(minioCfg.AccessKeyID, minioCfg.SecretAccessKey, ""),
Secure: minioCfg.UseSSL,
})
if err != nil {
log.Fatalln(err)
}
global.MG_MINIO = minioClient
}

24
initialize/redis.go

@ -0,0 +1,24 @@
package initialize
import (
"pure-admin/global"
"github.com/go-redis/redis"
"go.uber.org/zap"
)
func Redis() {
redisCfg := global.MG_CONFIG.Redis
client := redis.NewClient(&redis.Options{
Addr: redisCfg.Addr,
Password: redisCfg.Password, // no password set
DB: redisCfg.DB, // use default DB
})
pong, err := client.Ping().Result()
if err != nil {
global.MG_LOG.Error("redis connect ping failed, err:", zap.Any("err", err))
} else {
global.MG_LOG.Info("redis connect ping response:", zap.String("pong", pong))
global.MG_REDIS = client
}
}

75
initialize/router.go

@ -0,0 +1,75 @@
package initialize
import (
"net/http"
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "pure-admin/docs"
"pure-admin/global"
"pure-admin/middleware"
"pure-admin/router"
"pure-admin/service"
)
// 初始化总路由
func Routers() *gin.Engine {
var Router = gin.Default()
Router.StaticFS(global.MG_CONFIG.Local.Path, http.Dir(global.MG_CONFIG.Local.Path)) // 为用户头像和文件提供静态地址
// 跨域
// Router.Use(middleware.Cors()) // 如需跨域可以打开
Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
Router.Any("/ueditor/controller", service.UeditorAction) // 百度富文本编辑器
// 方便统一添加路由组前缀 多服务器上线使用
PublicGroup := Router.Group("")
{
router.InitBaseRouter(PublicGroup) // 注册基础功能路由 不做鉴权
// router.InitInitRouter(PublicGroup) // 自动初始化相关
router.InitAutoCodeRouter(PublicGroup) // 创建自动化代码
}
PrivateGroup := Router.Group("")
PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
{
router.InitApiRouter(PrivateGroup) // 注册功能api路由
// router.InitUserRouter(PrivateGroup) // 注册用户路由
router.InitMenuRouter(PrivateGroup) // 注册menu路由
router.InitCasbinRouter(PrivateGroup) // 权限相关路由
router.InitAuthorityRouter(PrivateGroup) // 注册角色路由
router.InitSysOperationRecordRouter(PrivateGroup) // 操作记录
// router.InitJwtRouter(PrivateGroup) // jwt相关路由
// router.InitCustomerRouter(PrivateGroup) // 客户路由
// router.InitSystemRouter(PrivateGroup) // system相关路由
// router.InitSimpleUploaderRouter(PrivateGroup) // 断点续传(插件版)
// router.InitEmailRouter(PrivateGroup) // 邮件相关路由
// router.InitSysDictionaryRouter(PrivateGroup) // 字典管理
// router.InitSysDictionaryDetailRouter(PrivateGroup) // 字典详情管理
// router.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
// router.InitExcelRouter(PrivateGroup) // 表格导入导出
// Code generated by pure-admin Begin; DO NOT EDIT.
router.InitUserRouter(PrivateGroup)
router.InitApplicationRouter(PrivateGroup)
router.InitOrganizationRouter(PrivateGroup)
router.InitProviderRouter(PrivateGroup)
router.InitBusinessRouter(PrivateGroup)
router.InitMissionRouter(PrivateGroup) //任务相关路由
router.InitDictRouter(PrivateGroup) //字典相关路由
router.InitOrderRouter(PrivateGroup) // 订单
router.InitBillRouter(PrivateGroup) // 账单
router.InitWithdrawalRouter(PrivateGroup) // 提现
router.InitWalletRouter(PrivateGroup) // 钱包
// Code generated by pure-admin End; DO NOT EDIT.
router.InitCategory(PrivateGroup)
router.InitTagRouter(PrivateGroup)
router.InitGoodsRouter(PrivateGroup)
router.InitBanner(PrivateGroup)
}
return Router
}

27
initialize/timer.go

@ -0,0 +1,27 @@
package initialize
import (
"fmt"
"pure-admin/config"
"pure-admin/global"
"pure-admin/service"
"pure-admin/utils"
)
func Timer() {
if global.MG_CONFIG.Timer.Start {
for _, detail := range global.MG_CONFIG.Timer.Detail {
go func(detail config.Detail) {
global.MG_Timer.AddTaskByFunc("ClearDB", global.MG_CONFIG.Timer.Spec, func() {
err := utils.ClearTable(global.MG_DB, detail.TableName, detail.CompareField, detail.Interval)
if err != nil {
fmt.Println("timer error:", err)
}
})
}(detail)
}
}
//定时任务
service.TimingTask()
}

22
initialize/validator.go

@ -0,0 +1,22 @@
package initialize
import "pure-admin/utils"
func init() {
_ = utils.RegisterRule("PageVerify",
utils.Rules{
"Page": {utils.NotEmpty()},
"PageSize": {utils.NotEmpty()},
},
)
_ = utils.RegisterRule("IdVerify",
utils.Rules{
"Id": {utils.NotEmpty()},
},
)
_ = utils.RegisterRule("AuthorityIdVerify",
utils.Rules{
"AuthorityId": {utils.NotEmpty()},
},
)
}

33
main.go

@ -0,0 +1,33 @@
package main
import (
"pure-admin/core"
"pure-admin/global"
"pure-admin/initialize"
)
//go:generate go env -w GO111MODULE=on
//go:generate go env -w GOPROXY=https://goproxy.cn,direct
//go:generate go mod tidy
//go:generate go mod download
// @title Swagger Example API
// @version 0.0.1
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name x-token
// @BasePath /
func main() {
global.MG_VP = core.Viper() // 初始化Viper
global.MG_LOG = core.Zap() // 初始化zap日志库
global.MG_DB = initialize.Gorm() // gorm连接数据库
//initialize.Minio()
initialize.Timer()
if global.MG_DB != nil {
// initialize.MysqlTables(global.MG_DB) //初始化表
// 程序结束前关闭数据库链接
db, _ := global.MG_DB.DB()
defer db.Close()
}
core.RunWindowsServer()
}

36
middleware/casbin_rbac.go

@ -0,0 +1,36 @@
package middleware
import (
"pure-admin/global"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"github.com/gin-gonic/gin"
)
// 拦截器
func CasbinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse := claims.(*request.CustomClaims)
// 获取请求的URI
obj := c.Request.URL.RequestURI()
// 获取请求方法
act := c.Request.Method
// 获取用户的角色
sub := waitUse.AuthorityId
appid := waitUse.Appid
types := waitUse.Type
e := service.Casbin()
// 判断策略中是否存在
success, _ := e.Enforce("api", appid, sub, obj, act, types)
if global.MG_CONFIG.System.Env == "develop" || success {
c.Next()
} else {
response.FailWithDetailed(gin.H{}, "权限不足", c)
c.Abort()
return
}
}
}

26
middleware/cors.go

@ -0,0 +1,26 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id,X-Requested-With,X_Requested_With")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
// 放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}

61
middleware/error.go

@ -0,0 +1,61 @@
package middleware
import (
"net"
"net/http"
"net/http/httputil"
"os"
"pure-admin/global"
"runtime/debug"
"strings"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// GinRecovery recover掉项目可能出现的panic,并使用zap记录相关日志
func GinRecovery(stack bool) gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// Check for a broken connection, as it is not really a
// condition that warrants a panic stack trace.
var brokenPipe bool
if ne, ok := err.(*net.OpError); ok {
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true
}
}
}
httpRequest, _ := httputil.DumpRequest(c.Request, false)
if brokenPipe {
global.MG_LOG.Error(c.Request.URL.Path,
zap.Any("error", err),
zap.String("request", string(httpRequest)),
)
// If the connection is dead, we can't write a status to it.
_ = c.Error(err.(error)) // nolint: errcheck
c.Abort()
return
}
if stack {
global.MG_LOG.Error("[Recovery from panic]",
zap.Any("error", err),
zap.String("request", string(httpRequest)),
zap.String("stack", string(debug.Stack())),
)
} else {
global.MG_LOG.Error("[Recovery from panic]",
zap.Any("error", err),
zap.String("request", string(httpRequest)),
)
}
c.AbortWithStatus(http.StatusInternalServerError)
}
}()
c.Next()
}
}

144
middleware/jwt.go

@ -0,0 +1,144 @@
package middleware
import (
"errors"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/model/response"
"pure-admin/service"
"strconv"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
token := c.Request.Header.Get("x-token")
if token == "" {
response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
c.Abort()
return
}
if service.IsBlacklist(token) {
response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
c.Abort()
return
}
j := NewJWT()
// parseToken 解析token包含的信息
claims, err := j.ParseToken(token)
if err != nil {
if err == TokenExpired {
response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
c.Abort()
return
}
response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
c.Abort()
return
}
if err, _ = service.FindUserByUuid(claims.UUID.String()); err != nil {
_ = service.JsonInBlacklist(model.JwtBlacklist{Jwt: token})
response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
c.Abort()
}
if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
claims.ExpiresAt = time.Now().Unix() + global.MG_CONFIG.JWT.ExpiresTime
newToken, _ := j.CreateToken(*claims)
newClaims, _ := j.ParseToken(newToken)
c.Header("new-token", newToken)
c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
if global.MG_CONFIG.System.UseMultipoint {
err, RedisJwtToken := service.GetRedisJWT(newClaims.UUID.String())
if err != nil {
global.MG_LOG.Error("get redis jwt failed", zap.Any("err", err))
} else { // 当之前的取成功时才进行拉黑操作
_ = service.JsonInBlacklist(model.JwtBlacklist{Jwt: RedisJwtToken})
}
// 无论如何都要记录当前的活跃状态
_ = service.SetRedisJWT(newToken, newClaims.UUID.String())
}
}
c.Set("claims", claims)
c.Next()
}
}
type JWT struct {
SigningKey []byte
}
var (
TokenExpired = errors.New("Token is expired")
TokenNotValidYet = errors.New("Token not active yet")
TokenMalformed = errors.New("That's not even a token")
TokenInvalid = errors.New("Couldn't handle this token:")
)
func NewJWT() *JWT {
return &JWT{
[]byte(global.MG_CONFIG.JWT.SigningKey),
}
}
// 创建一个token
func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
// 解析 token
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
} else {
return nil, TokenInvalid
}
}
// 更新token
//func (j *JWT) RefreshToken(tokenString string) (string, error) {
// jwt.TimeFunc = func() time.Time {
// return time.Unix(0, 0)
// }
// token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
// return j.SigningKey, nil
// })
// if err != nil {
// return "", err
// }
// if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
// jwt.TimeFunc = time.Now
// claims.StandardClaims.ExpiresAt = time.Now().Unix() + 60*60*24*7
// return j.CreateToken(*claims)
// }
// return "", TokenInvalid
//}

26
middleware/loadtls.go

@ -0,0 +1,26 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
// 用https把这个中间件在router里面use一下就好
func LoadTls() gin.HandlerFunc {
return func(c *gin.Context) {
middleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: "localhost:443",
})
err := middleware.Process(c.Writer, c.Request)
if err != nil {
// 如果出现错误,请不要继续
fmt.Println(err)
return
}
// 继续往下处理
c.Next()
}
}

23
middleware/need_init.go

@ -0,0 +1,23 @@
package middleware
import (
"pure-admin/global"
"pure-admin/model/response"
"github.com/gin-gonic/gin"
)
// 处理跨域请求,支持options访问
func NeedInit() gin.HandlerFunc {
return func(c *gin.Context) {
if global.MG_DB == nil {
response.OkWithDetailed(gin.H{
"needInit": true,
}, "前往初始化数据库", c)
c.Abort()
} else {
c.Next()
}
// 处理请求
}
}

87
middleware/operation.go

@ -0,0 +1,87 @@
package middleware
import (
"bytes"
"io/ioutil"
"net/http"
"pure-admin/global"
"pure-admin/model"
"pure-admin/model/request"
"pure-admin/service"
"strconv"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func OperationRecord() gin.HandlerFunc {
return func(c *gin.Context) {
var (
body []byte
userId int
appid string
)
if c.Request.Method != http.MethodGet {
var err error
body, err = ioutil.ReadAll(c.Request.Body)
if err != nil {
global.MG_LOG.Error("read body from request error:", zap.Any("err", err))
} else {
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
}
}
if claims, ok := c.Get("claims"); ok {
waitUse := claims.(*request.CustomClaims)
userId = int(waitUse.ID)
appid = waitUse.Appid
} else {
id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
if err != nil {
userId = 0
}
userId = id
}
record := model.SysOperationRecord{
Ip: c.ClientIP(),
Method: c.Request.Method,
Path: c.Request.URL.Path,
Agent: c.Request.UserAgent(),
Body: string(body),
UserID: userId,
Appid: appid,
}
// 存在某些未知错误 TODO
//values := c.Request.Header.Values("content-type")
//if len(values) >0 && strings.Contains(values[0], "boundary") {
// record.Body = "file"
//}
writer := responseBodyWriter{
ResponseWriter: c.Writer,
body: &bytes.Buffer{},
}
c.Writer = writer
now := time.Now()
c.Next()
latency := time.Now().Sub(now)
record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
record.Status = c.Writer.Status()
record.Latency = latency
record.Resp = writer.body.String()
if err := service.CreateSysOperationRecord(record); err != nil {
global.MG_LOG.Error("create operation record error:", zap.Any("err", err))
}
}
}
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (r responseBodyWriter) Write(b []byte) (int, error) {
r.body.Write(b)
return r.ResponseWriter.Write(b)
}

30
model/account.go

@ -0,0 +1,30 @@
package model
import "pure-admin/global"
type BankCard struct {
AccountName string `gorm:"size:50" json:"account_name"` // 户名
BankCode string `gorm:"size:50" json:"bank_code"` // 收款行
SwiftCode string `gorm:"size:20" json:"swift_code"` // 银行国际代码
CardNumber string `gorm:"size:50" json:"card_number"` // 银行卡号
Address string `gorm:"size:255" json:"address"` // 收款人地址
Country string `gorm:"size:255" json:"country"` // 国家/地区
Currency string `gorm:"size:10" json:"currency"` // 币种 USD:美元
}
type Account struct {
global.MG_MODEL
Platform string `gorm:"size:50" json:"platform"` //平台 saller(买家端) / customer(客户端) / influencer(网红端)
UserID string `gorm:"size:50;index" json:"userID"` //用户id
Type int `gorm:"type:int(1)" json:"type"` // 类型 1:paypal 2:银行卡
BankCard
IDCard string `gorm:"size:30" json:"idCard"` //身份证
Phone string `gorm:"size:20" json:"phone"` //手机号
Sort int `gorm:"type:int" json:"sort"` // 排序值
IsDefault bool `gorm:"type:tinyint" json:"is_default"` // 是否为默认 0:非默认 1:默认
}
func (Account) TableName() string {
return "account"
}

22
model/address.go

@ -0,0 +1,22 @@
package model
import "pure-admin/global"
type Address struct {
global.MG_MODEL
UserID string `gorm:"size:50" json:"userId"`
FirstName string `gorm:"size:50" json:"firstName"` //first name
LastName string `gorm:"size:50" json:"lastName"` //last name
Phone string `gorm:"size:20" json:"phone"` //手机号
Street string `gorm:"size:50" json:"street"` //street
Bldg string `gorm:"size:100" json:"bldg"` //apt,ste,bldg
City string `gorm:"size:50" json:"city"` //city
State string `gorm:"size:50" json:"state"` //state
ZipCode string `gorm:"size:50" json:"zipCode"` //zip code
Default int `gorm:"tinyint(1)" json:"default"` //是否默认地址 1-是 2-否
Platform string `gorm:"size:50" json:"platform"` //平台 saller(买家端) / customer(客户端) / influencer(网红端)
}
func (Address) TableName() string {
return "address"
}

23
model/application.go

@ -0,0 +1,23 @@
// 自动生成模板Application
package model
import (
"pure-admin/global"
)
// 如果含有time.Time 请自行import time包
type Application struct {
global.MG_MODEL
Owner string `gorm:"size:50;comment:用户所属" json:"owner" ` // 用户所属
Name string `gorm:"size:50;comment:应用名称" json:"name" ` // 应用名称
Appid string `gorm:"size:50;comment:应用ID" json:"appid" ` // 应用ID
Logo string `gorm:"size:255;comment:应用logo" json:"logo" ` // 应用logo
Organization string `gorm:"size:50;comment:组织" json:"organization" ` // 组织
Provider string `gorm:"type:text;comment:提供者" json:"provider" ` // 提供者
ClientID string `gorm:"size:50;comment:客户端ID" json:"clientID" ` // 客户端ID
ClientSecret string `gorm:"size:50;comment:客户端密钥" json:"clientSecret" ` // 客户端密钥
}
func (Application) TableName() string {
return "application"
}

28
model/banner.go

@ -0,0 +1,28 @@
package model
import "pure-admin/global"
const MAX_BANNER_LIMIT = 20
type Banner struct {
RelationId string `gorm:"size:50" json:"relationId"` //关联项目id
RelationType string `gorm:"size:4" json:"relationType"` //关联类型 01-任务
Title string `gorm:"size:80" json:"title"` //标题
CoverUrl string `gorm:"size:500" json:"coverUrl"` //封面图
LinkType string `gorm:"size:2" json:"linkType" form:"linkType"` //链接类型 0:内链 1:外链
Link string `gorm:"size:500" json:"link"` //链接地址
Type string `gorm:"size:4" json:"type"` //任务-0101 平台奖励页-0102
Sort int `gorm:"" json:"sort"` //排序
Status string `gorm:"size:4" json:"status"` //状态 0=下架 1=上架
CreateBy string `gorm:"size:64" json:"createBy"` //创建人
UpdateBy string `gorm:"size:64" json:"updateBy"` //更新人
global.MG_MODEL
}
func (q *Banner) New() error {
return global.MG_DB.Model(&Banner{}).Create(&q).Error
}
func (Banner) TableName() string {
return "banner"
}

42
model/bill.go

@ -0,0 +1,42 @@
package model
import (
"pure-admin/global"
)
type Bill struct {
global.MG_MODEL
UserID string `gorm:"size:50;index" json:"userID"` //用户id
Type string `gorm:"size:1;default:1" json:"type"` //类型 1-佣金 2-订单 3-提现
Title string `gorm:"size:255" json:"title"` // 账单标题
Account string `gorm:"size:50" json:"account"` //收款账户(提现)
OrderID string `gorm:"size:50" json:"order_id"` //关联订单id
Price float64 `gorm:"type:decimal(10,2)" json:"price"` //价格
Balance float64 `gorm:"type:decimal(10,2)" json:"balance"` //余额
Status int `gorm:"type:int(1);default:0" json:"status"` //类型 1-支出 2-收入
Receipt int `gorm:"type:tinyint(1)" json:"receipt"` //是否已到账 1-是 2-否 3-已取消付款
Remark string `gorm:"size:50" json:"remark"` //备注
Platform string `gorm:"size:50" json:"platform"` //平台 seller / customer / influencer
TransactionId string `gorm:"size:50" json:"transaction_id"` // 交易编号
}
type BillList struct {
global.MG_MODEL
UserID string `json:"user_id"` // 用户id
Title string `json:"title"` // 标题
OrderID string `json:"order_id"` // 订单号
Price float64 `json:"price"` // 金额
Status int `json:"status"` // 类型 1-支出 2-收入
Remark string `json:"remark"` // 备注
Platform string `json:"platform"` // 平台 seller / customer / influencer
TransactionId string `json:"transaction_id"` // 交易编号
User UserView `gorm:"-" json:"user"` // 用户信息
}
func (Bill) TableName() string {
return "bill"
}
func (BillList) TableName() string {
return "bill"
}

47
model/bill_fund.go

@ -0,0 +1,47 @@
package model
import "pure-admin/global"
type BillFund struct { // 账户
global.MG_MODEL
UserID string `gorm:"size:50;index" json:"userID"` // 用户id
TransactionType int `gorm:"type:int(1);default:1" json:"transaction_type"` // 类型 1-支出 2-收入
TransactionId string `gorm:"size:50;unique" json:"transaction_id"` // 交易编号
Title string `gorm:"size:255" json:"title"` // 账单标题
Price float64 `gorm:"type:decimal(10,2)" json:"price"` // 金额
Balance float64 `gorm:"type:decimal(10,2)" json:"balance"` // 余额
Platform string `gorm:"size:20" json:"platform"` // 平台 seller bkb
Remark string `gorm:"size:50" json:"remark"` // 备注
RelatedId string `gorm:"size:50" json:"related_id"` // 关联id 任务id
PayId string `gorm:"size:50" json:"pay_id"` // 支付id
Status int `gorm:"size:1" json:"status"` // 状态 1:进行中 2:已完成 3:已失败
}
type SellerBillFund struct {
global.MG_MODEL
UserID string `json:"user_id"` // 商家storeNo
TransactionType int `json:"transaction_type"` // 类型 1-支出 2-收入
TransactionId string `json:"transaction_id"` // 交易编号
Price float64 `json:"price"` // 金额
Remark string `json:"remark"` // 备注
RelatedId string `json:"related_id"` // 关联id 任务id
Status int `json:"status"` // 状态 1:进行中 2:已完成 3:已失败
Seller StoreInfo `json:"seller"` // 店铺信息
Mission MissionClaimView `json:"mission"` // 领取任务信息
}
type AdminBillFund struct {
global.MG_MODEL
UserID string `json:"user_id"` //
TransactionType int `json:"transaction_type"` // 类型 1-支出 2-收入
TransactionId string `json:"transaction_id"` // 交易编号
Price float64 `json:"price"` // 金额
Remark string `json:"remark"` // 备注
RelatedId string `json:"related_id"` // 关联id 任务id
Status int `json:"status"` // 状态 1:进行中 2:已完成 3:已失败
InfluencerUser InfluencerUserClaimView `gorm:"-" json:"influencer"` // 网红信息
}
func (BillFund) TableName() string {
return "bill_fund"
}

28
model/brochure.go

@ -0,0 +1,28 @@
package model
import "pure-admin/global"
type SysBrochure struct { //单页 协议、条款等
global.BASE_ID
Title string `gorm:"size:10" json:"title"` //标题
Type string `gorm:"size:30" sql:"index" json:"type"` //类型
Content string `gorm:"type:text" json:"content"` //内容
Src string `gorm:"size:500" json:"src"` //静态页面html
global.TIME_MODEL
}
type SysBrochure4List struct {
global.BASE_ID
Title string `gorm:"size:10" json:"title"` //标题
global.TIME_MODEL
global.TIME_MODEL_VIEW
}
func (SysBrochure) TableName() string {
return "sys_brochure"
}
func (SysBrochure4List) TableName() string {
return "sys_brochure"
}

18
model/business.go

@ -0,0 +1,18 @@
// 自动生成模板Business
package model
import (
"pure-admin/global"
)
// 如果含有time.Time 请自行import time包
type Business struct {
global.MG_MODEL
Name string `json:"name" form:"" gorm:"size:20"`
Email string `json:"email" form:"" gorm:"size:100"`
Phone string `json:"phone" form:"" gorm:"size:20"`
}
func (Business) TableName() string {
return "business"
}

39
model/category.go

@ -0,0 +1,39 @@
package model
import (
"gorm.io/gorm"
"pure-admin/global"
)
type TbCategory struct { // 商品分类
global.MG_MODEL
Name string `gorm:"type:varchar(100);not null;comment:商品分类名称" json:"name"` // 名称
Pid uint `gorm:"type:int(11);comment:父id" json:"pid"` // 父id
Layer int `gorm:"type:int(1)" json:"layer"` // 层数
IsLeaf bool `gorm:"type:tinyint(1)" json:"is_leaf"` // 是否叶子分类
Status int `gorm:"type:tinyint(1);comment:状态 1:正常" json:"status"` // 状态
}
type TbCategoryTree struct {
ID uint `json:"id"` //
DeletedAt gorm.DeletedAt `json:"-"` // 删除时间
Layer int `json:"-"` //
Name string `json:"name"` // 名称
Pid uint `json:"pid"` // 父id
IsLeaf bool `json:"is_leaf"` // 是否叶子分类
Children []*TbCategoryTree `gorm:"-" json:"children"` // 子节点
}
func (TbCategory) TableName() string {
return "tb_category"
}
func (TbCategoryTree) TableName() string {
return "tb_category"
}
type CategoryParentTree struct {
TbCategory
Parent *CategoryParentTree `json:"-"` // 父节点
}

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

Loading…
Cancel
Save