first commit

This commit is contained in:
2025-08-05 22:50:44 +08:00
commit a981187a8c
377 changed files with 35686 additions and 0 deletions

View File

@@ -0,0 +1,91 @@
package admin_auth
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
jwtx "aedata-server/common/jwt"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLoginLogic {
return &AdminLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminLoginLogic) AdminLogin(req *types.AdminLoginReq) (resp *types.AdminLoginResp, err error) {
// 1. 验证验证码
if !req.Captcha {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码错误"), "用户登录, 验证码错误, 验证码: %v", req.Captcha)
}
// 2. 验证用户名和密码
user, err := l.svcCtx.AdminUserModel.FindOneByUsername(l.ctx, req.Username)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("用户名或密码错误"), "用户登录, 用户名或密码错误, 用户名: %s", req.Username)
}
// 3. 验证密码
if !crypto.PasswordVerify(req.Password, user.Password) {
return nil, errors.Wrapf(xerr.NewErrMsg("用户名或密码错误"), "用户登录, 用户名或密码错误, 用户名: %s", req.Username)
}
// 4. 获取权限
adminUserRoleBuilder := l.svcCtx.AdminUserRoleModel.SelectBuilder().Where(squirrel.Eq{"user_id": user.Id})
permissions, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, adminUserRoleBuilder, "role_id DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("获取权限失败"), "用户登录, 获取权限失败, 用户名: %s", req.Username)
}
// 获取角色ID数组
roleIds := make([]int64, 0)
for _, permission := range permissions {
roleIds = append(roleIds, permission.RoleId)
}
// 获取角色名称
roles := make([]string, 0)
for _, roleId := range roleIds {
role, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, roleId)
if err != nil {
continue
}
roles = append(roles, role.RoleCode)
}
// 5. 生成token
refreshToken := l.svcCtx.Config.JwtAuth.RefreshAfter
expiresAt := l.svcCtx.Config.JwtAuth.AccessExpire
claims := jwtx.JwtClaims{
UserId: user.Id,
Platform: model.PlatformAdmin,
UserType: model.UserTypeAdmin,
}
token, err := jwtx.GenerateJwtToken(claims, l.svcCtx.Config.JwtAuth.AccessSecret, expiresAt)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("生成token失败"), "用户登录, 生成token失败, 用户名: %s", req.Username)
}
return &types.AdminLoginResp{
AccessToken: token,
AccessExpire: expiresAt,
RefreshAfter: refreshToken,
Roles: roles,
}, nil
}

View File

@@ -0,0 +1,46 @@
package admin_feature
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminCreateFeatureLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreateFeatureLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateFeatureLogic {
return &AdminCreateFeatureLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreateFeatureLogic) AdminCreateFeature(req *types.AdminCreateFeatureReq) (resp *types.AdminCreateFeatureResp, err error) {
// 1. 数据转换
data := &model.Feature{
ApiId: req.ApiId,
Name: req.Name,
}
// 2. 数据库操作
result, err := l.svcCtx.FeatureModel.Insert(l.ctx, nil, data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"创建功能失败, err: %v, req: %+v", err, req)
}
// 3. 返回结果
id, _ := result.LastInsertId()
return &types.AdminCreateFeatureResp{Id: id}, nil
}

View File

@@ -0,0 +1,45 @@
package admin_feature
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminDeleteFeatureLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeleteFeatureLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeleteFeatureLogic {
return &AdminDeleteFeatureLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeleteFeatureLogic) AdminDeleteFeature(req *types.AdminDeleteFeatureReq) (resp *types.AdminDeleteFeatureResp, err error) {
// 1. 查询记录是否存在
record, err := l.svcCtx.FeatureModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查找功能失败, err: %v, id: %d", err, req.Id)
}
// 2. 执行软删除
err = l.svcCtx.FeatureModel.DeleteSoft(l.ctx, nil, record)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"删除功能失败, err: %v, id: %d", err, req.Id)
}
// 3. 返回结果
return &types.AdminDeleteFeatureResp{Success: true}, nil
}

View File

@@ -0,0 +1,46 @@
package admin_feature
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetFeatureDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetFeatureDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetFeatureDetailLogic {
return &AdminGetFeatureDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetFeatureDetailLogic) AdminGetFeatureDetail(req *types.AdminGetFeatureDetailReq) (resp *types.AdminGetFeatureDetailResp, err error) {
// 1. 查询记录
record, err := l.svcCtx.FeatureModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查找功能失败, err: %v, id: %d", err, req.Id)
}
// 2. 构建响应
resp = &types.AdminGetFeatureDetailResp{
Id: record.Id,
ApiId: record.ApiId,
Name: record.Name,
CreateTime: record.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: record.UpdateTime.Format("2006-01-02 15:04:05"),
}
return resp, nil
}

View File

@@ -0,0 +1,66 @@
package admin_feature
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetFeatureListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetFeatureListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetFeatureListLogic {
return &AdminGetFeatureListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetFeatureListLogic) AdminGetFeatureList(req *types.AdminGetFeatureListReq) (resp *types.AdminGetFeatureListResp, err error) {
// 1. 构建查询条件
builder := l.svcCtx.FeatureModel.SelectBuilder()
// 2. 添加查询条件
if req.ApiId != nil && *req.ApiId != "" {
builder = builder.Where("api_id LIKE ?", "%"+*req.ApiId+"%")
}
if req.Name != nil && *req.Name != "" {
builder = builder.Where("name LIKE ?", "%"+*req.Name+"%")
}
// 3. 执行分页查询
list, total, err := l.svcCtx.FeatureModel.FindPageListByPageWithTotal(
l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查询功能列表失败, err: %v, req: %+v", err, req)
}
// 4. 构建响应列表
items := make([]types.FeatureListItem, 0, len(list))
for _, item := range list {
listItem := types.FeatureListItem{
Id: item.Id,
ApiId: item.ApiId,
Name: item.Name,
CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
}
items = append(items, listItem)
}
// 5. 返回结果
return &types.AdminGetFeatureListResp{
Total: total,
Items: items,
}, nil
}

View File

@@ -0,0 +1,30 @@
package admin_feature
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminUpdateFeatureLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateFeatureLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateFeatureLogic {
return &AdminUpdateFeatureLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateFeatureLogic) AdminUpdateFeature(req *types.AdminUpdateFeatureReq) (resp *types.AdminUpdateFeatureResp, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,97 @@
package admin_menu
import (
"context"
"database/sql"
"encoding/json"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type CreateMenuLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMenuLogic {
return &CreateMenuLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CreateMenuLogic) CreateMenu(req *types.CreateMenuReq) (resp *types.CreateMenuResp, err error) {
// 1. 参数验证
if req.Name == "" {
return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称不能为空"), "菜单名称不能为空")
}
if req.Type == "menu" && req.Component == "" {
return nil, errors.Wrapf(xerr.NewErrMsg("组件路径不能为空"), "组件路径不能为空")
}
// 2. 检查名称和路径是否重复
exists, err := l.svcCtx.AdminMenuModel.FindOneByNamePath(l.ctx, req.Name, req.Path)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, err: %v", err)
}
if exists != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称或路径已存在"), "菜单名称或路径已存在")
}
// 3. 检查父菜单是否存在(如果不是根菜单)
if req.Pid > 0 {
parentMenu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Pid)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询父菜单失败, id: %d, err: %v", req.Pid, err)
}
if parentMenu == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "父菜单不存在, id: %d", req.Pid)
}
}
// 4. 将类型标签转换为值
typeValue, err := l.svcCtx.DictService.GetDictValue(l.ctx, "admin_menu_type", req.Type)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单类型无效: %v", err)
}
// 5. 创建菜单记录
menu := &model.AdminMenu{
Pid: req.Pid,
Name: req.Name,
Path: req.Path,
Component: req.Component,
Redirect: sql.NullString{String: req.Redirect, Valid: req.Redirect != ""},
Status: req.Status,
Type: typeValue,
Sort: req.Sort,
CreateTime: time.Now(),
UpdateTime: time.Now(),
}
// 将Meta转换为JSON字符串
metaJson, err := json.Marshal(req.Meta)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "Meta数据格式错误: %v", err)
}
menu.Meta = string(metaJson)
// 6. 保存到数据库
_, err = l.svcCtx.AdminMenuModel.Insert(l.ctx, nil, menu)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建菜单失败, err: %v", err)
}
return &types.CreateMenuResp{
Id: menu.Id,
}, nil
}

View File

@@ -0,0 +1,30 @@
package admin_menu
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type DeleteMenuLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteMenuLogic {
return &DeleteMenuLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeleteMenuLogic) DeleteMenu(req *types.DeleteMenuReq) (resp *types.DeleteMenuResp, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,250 @@
package admin_menu
import (
"context"
"sort"
"strconv"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/bytedance/sonic"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type GetMenuAllLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMenuAllLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuAllLogic {
return &GetMenuAllLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMenuAllLogic) GetMenuAll(req *types.GetMenuAllReq) (resp *[]types.GetMenuAllResp, err error) {
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败, %+v", err)
}
// 使用MapReduceVoid并发获取用户角色
var roleIds []int64
var permissions []*struct {
RoleId int64
}
type UserRoleResult struct {
RoleId int64
}
err = mr.MapReduceVoid(
func(source chan<- interface{}) {
adminUserRoleBuilder := l.svcCtx.AdminUserRoleModel.SelectBuilder().Where(squirrel.Eq{"user_id": userId})
source <- adminUserRoleBuilder
},
func(item interface{}, writer mr.Writer[*UserRoleResult], cancel func(error)) {
builder := item.(squirrel.SelectBuilder)
result, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, builder, "role_id DESC")
if err != nil {
cancel(errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户角色信息失败, %+v", err))
return
}
for _, r := range result {
writer.Write(&UserRoleResult{RoleId: r.RoleId})
}
},
func(pipe <-chan *UserRoleResult, cancel func(error)) {
for item := range pipe {
permissions = append(permissions, &struct{ RoleId int64 }{RoleId: item.RoleId})
}
},
)
if err != nil {
return nil, err
}
for _, permission := range permissions {
roleIds = append(roleIds, permission.RoleId)
}
// 使用MapReduceVoid并发获取角色菜单
var menuIds []int64
var roleMenus []*struct {
MenuId int64
}
type RoleMenuResult struct {
MenuId int64
}
err = mr.MapReduceVoid(
func(source chan<- interface{}) {
getRoleMenuBuilder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().Where(squirrel.Eq{"role_id": roleIds})
source <- getRoleMenuBuilder
},
func(item interface{}, writer mr.Writer[*RoleMenuResult], cancel func(error)) {
builder := item.(squirrel.SelectBuilder)
result, err := l.svcCtx.AdminRoleMenuModel.FindAll(l.ctx, builder, "id DESC")
if err != nil {
cancel(errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取角色菜单信息失败, %+v", err))
return
}
for _, r := range result {
writer.Write(&RoleMenuResult{MenuId: r.MenuId})
}
},
func(pipe <-chan *RoleMenuResult, cancel func(error)) {
for item := range pipe {
roleMenus = append(roleMenus, &struct{ MenuId int64 }{MenuId: item.MenuId})
}
},
)
if err != nil {
return nil, err
}
for _, roleMenu := range roleMenus {
menuIds = append(menuIds, roleMenu.MenuId)
}
// 使用MapReduceVoid并发获取菜单
type AdminMenuStruct struct {
Id int64
Pid int64
Name string
Path string
Component string
Redirect struct {
String string
Valid bool
}
Meta string
Sort int64
Type int64
Status int64
}
var menus []*AdminMenuStruct
err = mr.MapReduceVoid(
func(source chan<- interface{}) {
adminMenuBuilder := l.svcCtx.AdminMenuModel.SelectBuilder().Where(squirrel.Eq{"id": menuIds})
source <- adminMenuBuilder
},
func(item interface{}, writer mr.Writer[*AdminMenuStruct], cancel func(error)) {
builder := item.(squirrel.SelectBuilder)
result, err := l.svcCtx.AdminMenuModel.FindAll(l.ctx, builder, "sort ASC")
if err != nil {
cancel(errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取菜单信息失败, %+v", err))
return
}
for _, r := range result {
menu := &AdminMenuStruct{
Id: r.Id,
Pid: r.Pid,
Name: r.Name,
Path: r.Path,
Component: r.Component,
Redirect: r.Redirect,
Meta: r.Meta,
Sort: r.Sort,
Type: r.Type,
Status: r.Status,
}
writer.Write(menu)
}
},
func(pipe <-chan *AdminMenuStruct, cancel func(error)) {
for item := range pipe {
menus = append(menus, item)
}
},
)
if err != nil {
return nil, err
}
// 转换为types.Menu结构并存储到映射表
menuMap := make(map[string]types.GetMenuAllResp)
for _, menu := range menus {
// 只处理状态正常的菜单
if menu.Status != 1 {
continue
}
meta := make(map[string]interface{})
err = sonic.Unmarshal([]byte(menu.Meta), &meta)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解析菜单Meta信息失败, %+v", err)
}
redirect := func() string {
if menu.Redirect.Valid {
return menu.Redirect.String
}
return ""
}()
menuId := strconv.FormatInt(menu.Id, 10)
menuMap[menuId] = types.GetMenuAllResp{
Name: menu.Name,
Path: menu.Path,
Redirect: redirect,
Component: menu.Component,
Sort: menu.Sort,
Meta: meta,
Children: make([]types.GetMenuAllResp, 0),
}
}
// 按ParentId将菜单分组
menuGroups := lo.GroupBy(menus, func(item *AdminMenuStruct) int64 {
return item.Pid
})
// 递归构建菜单树
var buildMenuTree func(parentId int64) []types.GetMenuAllResp
buildMenuTree = func(parentId int64) []types.GetMenuAllResp {
children := make([]types.GetMenuAllResp, 0)
childMenus, ok := menuGroups[parentId]
if !ok {
return children
}
// 按Sort排序
sort.Slice(childMenus, func(i, j int) bool {
return childMenus[i].Sort < childMenus[j].Sort
})
for _, childMenu := range childMenus {
menuId := strconv.FormatInt(childMenu.Id, 10)
if menu, exists := menuMap[menuId]; exists && childMenu.Status == 1 {
// 递归构建子菜单
menu.Children = buildMenuTree(childMenu.Id)
children = append(children, menu)
}
}
return children
}
// 从根菜单开始构建ParentId为0的是根菜单
menuTree := buildMenuTree(0)
return &menuTree, nil
}

View File

@@ -0,0 +1,30 @@
package admin_menu
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetMenuDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMenuDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuDetailLogic {
return &GetMenuDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMenuDetailLogic) GetMenuDetail(req *types.GetMenuDetailReq) (resp *types.GetMenuDetailResp, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,109 @@
package admin_menu
import (
"context"
"encoding/json"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type GetMenuListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMenuListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuListLogic {
return &GetMenuListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMenuListLogic) GetMenuList(req *types.GetMenuListReq) (resp []types.MenuListItem, err error) {
// 构建查询条件
builder := l.svcCtx.AdminMenuModel.SelectBuilder()
// 添加筛选条件
if len(req.Name) > 0 {
builder = builder.Where("name LIKE ?", "%"+req.Name+"%")
}
if len(req.Path) > 0 {
builder = builder.Where("path LIKE ?", "%"+req.Path+"%")
}
if req.Status != -1 {
builder = builder.Where("status = ?", req.Status)
}
if req.Type != "" {
builder = builder.Where("type = ?", req.Type)
}
// 排序但不分页,获取所有符合条件的菜单
builder = builder.OrderBy("sort ASC")
// 获取所有菜单
menus, err := l.svcCtx.AdminMenuModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, err: %v", err)
}
// 将菜单按ID存入map
menuMap := make(map[int64]types.MenuListItem)
for _, menu := range menus {
var meta map[string]interface{}
err := json.Unmarshal([]byte(menu.Meta), &meta)
if err != nil {
logx.Errorf("解析Meta字段失败: %v", err)
meta = make(map[string]interface{})
}
menuType, err := l.svcCtx.DictService.GetDictLabel(l.ctx, "admin_menu_type", menu.Type)
if err != nil {
logx.Errorf("获取菜单类型失败: %v", err)
menuType = ""
}
item := types.MenuListItem{
Id: menu.Id,
Pid: menu.Pid,
Name: menu.Name,
Path: menu.Path,
Component: menu.Component,
Redirect: menu.Redirect.String,
Meta: meta,
Status: menu.Status,
Type: menuType,
Sort: menu.Sort,
CreateTime: menu.CreateTime.Format("2006-01-02 15:04:05"),
Children: make([]types.MenuListItem, 0),
}
menuMap[menu.Id] = item
}
// 构建父子关系
for _, menu := range menus {
if menu.Pid > 0 {
// 找到父菜单
if parent, exists := menuMap[menu.Pid]; exists {
// 添加当前菜单到父菜单的子菜单列表
children := append(parent.Children, menuMap[menu.Id])
parent.Children = children
menuMap[menu.Pid] = parent
}
}
}
// 提取顶级菜单ParentId为0到响应列表
result := make([]types.MenuListItem, 0)
for _, menu := range menus {
if menu.Pid == 0 {
result = append(result, menuMap[menu.Id])
}
}
return result, nil
}

View File

@@ -0,0 +1,96 @@
package admin_menu
import (
"context"
"database/sql"
"encoding/json"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateMenuLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMenuLogic {
return &UpdateMenuLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateMenuLogic) UpdateMenu(req *types.UpdateMenuReq) (resp *types.UpdateMenuResp, err error) {
// 1. 检查菜单是否存在
menu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, id: %d, err: %v", req.Id, err)
}
if menu == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单不存在, id: %d", req.Id)
}
// 2. 将类型标签转换为值
typeValue, err := l.svcCtx.DictService.GetDictValue(l.ctx, "admin_menu_type", req.Type)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单类型无效: %v", err)
}
// 3. 检查父菜单是否存在(如果不是根菜单)
if req.Pid > 0 {
parentMenu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Pid)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询父菜单失败, id: %d, err: %v", req.Pid, err)
}
if parentMenu == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "父菜单不存在, id: %d", req.Pid)
}
}
// 4. 检查名称和路径是否重复
if req.Name != menu.Name || req.Path != menu.Path {
exists, err := l.svcCtx.AdminMenuModel.FindOneByNamePath(l.ctx, req.Name, req.Path)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, err: %v", err)
}
if exists != nil && exists.Id != req.Id {
return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称或路径已存在"), "菜单名称或路径已存在")
}
}
// 5. 更新菜单信息
menu.Pid = req.Pid
menu.Name = req.Name
menu.Path = req.Path
menu.Component = req.Component
menu.Redirect = sql.NullString{String: req.Redirect, Valid: req.Redirect != ""}
menu.Status = req.Status
menu.Type = typeValue
menu.Sort = req.Sort
// 将Meta转换为JSON字符串
metaJson, err := json.Marshal(req.Meta)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "Meta数据格式错误: %v", err)
}
menu.Meta = string(metaJson)
// 6. 保存更新
_, err = l.svcCtx.AdminMenuModel.Update(l.ctx, nil, menu)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新菜单失败, err: %v", err)
}
return &types.UpdateMenuResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,50 @@
package admin_notification
import (
"context"
"database/sql"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminCreateNotificationLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreateNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateNotificationLogic {
return &AdminCreateNotificationLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreateNotificationLogic) AdminCreateNotification(req *types.AdminCreateNotificationReq) (resp *types.AdminCreateNotificationResp, err error) {
startDate, _ := time.Parse("2006-01-02", req.StartDate)
endDate, _ := time.Parse("2006-01-02", req.EndDate)
data := &model.GlobalNotifications{
Title: req.Title,
Content: req.Content,
NotificationPage: req.NotificationPage,
StartDate: sql.NullTime{Time: startDate, Valid: req.StartDate != ""},
EndDate: sql.NullTime{Time: endDate, Valid: req.EndDate != ""},
StartTime: req.StartTime,
EndTime: req.EndTime,
Status: req.Status,
}
result, err := l.svcCtx.GlobalNotificationsModel.Insert(l.ctx, nil, data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建通知失败, err: %v, req: %+v", err, req)
}
id, _ := result.LastInsertId()
return &types.AdminCreateNotificationResp{Id: id}, nil
}

View File

@@ -0,0 +1,38 @@
package admin_notification
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminDeleteNotificationLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeleteNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeleteNotificationLogic {
return &AdminDeleteNotificationLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeleteNotificationLogic) AdminDeleteNotification(req *types.AdminDeleteNotificationReq) (resp *types.AdminDeleteNotificationResp, err error) {
notification, err := l.svcCtx.GlobalNotificationsModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查找通知失败, err: %v, id: %d", err, req.Id)
}
err = l.svcCtx.GlobalNotificationsModel.DeleteSoft(l.ctx, nil, notification)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除通知失败, err: %v, id: %d", err, req.Id)
}
return &types.AdminDeleteNotificationResp{Success: true}, nil
}

View File

@@ -0,0 +1,53 @@
package admin_notification
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetNotificationDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetNotificationDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetNotificationDetailLogic {
return &AdminGetNotificationDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetNotificationDetailLogic) AdminGetNotificationDetail(req *types.AdminGetNotificationDetailReq) (resp *types.AdminGetNotificationDetailResp, err error) {
notification, err := l.svcCtx.GlobalNotificationsModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查找通知失败, err: %v, id: %d", err, req.Id)
}
resp = &types.AdminGetNotificationDetailResp{
Id: notification.Id,
Title: notification.Title,
Content: notification.Content,
NotificationPage: notification.NotificationPage,
StartDate: "",
StartTime: notification.StartTime,
EndDate: "",
EndTime: notification.EndTime,
Status: notification.Status,
CreateTime: notification.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: notification.UpdateTime.Format("2006-01-02 15:04:05"),
}
if notification.StartDate.Valid {
resp.StartDate = notification.StartDate.Time.Format("2006-01-02")
}
if notification.EndDate.Valid {
resp.EndDate = notification.EndDate.Time.Format("2006-01-02")
}
return resp, nil
}

View File

@@ -0,0 +1,82 @@
package admin_notification
import (
"context"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetNotificationListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetNotificationListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetNotificationListLogic {
return &AdminGetNotificationListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetNotificationListLogic) AdminGetNotificationList(req *types.AdminGetNotificationListReq) (resp *types.AdminGetNotificationListResp, err error) {
builder := l.svcCtx.GlobalNotificationsModel.SelectBuilder()
if req.Title != nil {
builder = builder.Where("title LIKE ?", "%"+*req.Title+"%")
}
if req.NotificationPage != nil {
builder = builder.Where("notification_page = ?", *req.NotificationPage)
}
if req.Status != nil {
builder = builder.Where("status = ?", *req.Status)
}
if req.StartDate != nil {
if t, err := time.Parse("2006-01-02", *req.StartDate); err == nil {
builder = builder.Where("start_date >= ?", t)
}
}
if req.EndDate != nil {
if t, err := time.Parse("2006-01-02", *req.EndDate); err == nil {
builder = builder.Where("end_date <= ?", t)
}
}
list, total, err := l.svcCtx.GlobalNotificationsModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询通知列表失败, err: %v, req: %+v", err, req)
}
items := make([]types.NotificationListItem, 0, len(list))
for _, n := range list {
item := types.NotificationListItem{
Id: n.Id,
Title: n.Title,
NotificationPage: n.NotificationPage,
Content: n.Content,
StartDate: "",
StartTime: n.StartTime,
EndDate: "",
EndTime: n.EndTime,
Status: n.Status,
CreateTime: n.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: n.UpdateTime.Format("2006-01-02 15:04:05"),
}
if n.StartDate.Valid {
item.StartDate = n.StartDate.Time.Format("2006-01-02")
}
if n.EndDate.Valid {
item.EndDate = n.EndDate.Time.Format("2006-01-02")
}
items = append(items, item)
}
resp = &types.AdminGetNotificationListResp{
Total: total,
Items: items,
}
return resp, nil
}

View File

@@ -0,0 +1,66 @@
package admin_notification
import (
"context"
"database/sql"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminUpdateNotificationLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateNotificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateNotificationLogic {
return &AdminUpdateNotificationLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateNotificationLogic) AdminUpdateNotification(req *types.AdminUpdateNotificationReq) (resp *types.AdminUpdateNotificationResp, err error) {
notification, err := l.svcCtx.GlobalNotificationsModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查找通知失败, err: %v, id: %d", err, req.Id)
}
if req.StartDate != nil {
startDate, _ := time.Parse("2006-01-02", *req.StartDate)
notification.StartDate = sql.NullTime{Time: startDate, Valid: true}
}
if req.EndDate != nil {
endDate, _ := time.Parse("2006-01-02", *req.EndDate)
notification.EndDate = sql.NullTime{Time: endDate, Valid: true}
}
if req.Title != nil {
notification.Title = *req.Title
}
if req.Content != nil {
notification.Content = *req.Content
}
if req.NotificationPage != nil {
notification.NotificationPage = *req.NotificationPage
}
if req.StartTime != nil {
notification.StartTime = *req.StartTime
}
if req.EndTime != nil {
notification.EndTime = *req.EndTime
}
if req.Status != nil {
notification.Status = *req.Status
}
_, err = l.svcCtx.GlobalNotificationsModel.Update(l.ctx, nil, notification)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新通知失败, err: %v, req: %+v", err, req)
}
return &types.AdminUpdateNotificationResp{Success: true}, nil
}

View File

@@ -0,0 +1,85 @@
package admin_order
import (
"context"
"database/sql"
"fmt"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminCreateOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateOrderLogic {
return &AdminCreateOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreateOrderLogic) AdminCreateOrder(req *types.AdminCreateOrderReq) (resp *types.AdminCreateOrderResp, err error) {
// 生成订单号
orderNo := fmt.Sprintf("%dADMIN", time.Now().UnixNano())
// 根据产品名称查询产品ID
builder := l.svcCtx.ProductModel.SelectBuilder()
builder = builder.Where("product_name = ? AND del_state = ?", req.ProductName, 0)
products, err := l.svcCtx.ProductModel.FindAll(l.ctx, builder, "")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 查询产品失败 err: %v", err)
}
if len(products) == 0 {
return nil, errors.Wrapf(xerr.NewErrMsg(fmt.Sprintf("产品不存在: %s", req.ProductName)), "AdminCreateOrder, 查询产品失败 err: %v", err)
}
product := products[0]
// 创建订单对象
order := &model.Order{
OrderNo: orderNo,
PlatformOrderId: sql.NullString{String: req.PlatformOrderId, Valid: req.PlatformOrderId != ""},
ProductId: product.Id,
PaymentPlatform: req.PaymentPlatform,
PaymentScene: req.PaymentScene,
Amount: req.Amount,
Status: req.Status,
}
// 使用事务处理订单创建
var orderId int64
err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 插入订单
result, err := l.svcCtx.OrderModel.Insert(ctx, session, order)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 创建订单失败 err: %v", err)
}
// 获取订单ID
orderId, err = result.LastInsertId()
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 获取订单ID失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
return &types.AdminCreateOrderResp{
Id: orderId,
}, nil
}

View File

@@ -0,0 +1,54 @@
package admin_order
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminDeleteOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeleteOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeleteOrderLogic {
return &AdminDeleteOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeleteOrderLogic) AdminDeleteOrder(req *types.AdminDeleteOrderReq) (resp *types.AdminDeleteOrderResp, err error) {
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminDeleteOrder, 查询订单失败 err: %v", err)
}
// 使用事务删除订单
err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 软删除订单
err := l.svcCtx.OrderModel.DeleteSoft(ctx, session, order)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminDeleteOrder, 删除订单失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
return &types.AdminDeleteOrderResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,96 @@
package admin_order
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/globalkey"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetOrderDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetOrderDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetOrderDetailLogic {
return &AdminGetOrderDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetOrderDetailLogic) AdminGetOrderDetail(req *types.AdminGetOrderDetailReq) (resp *types.AdminGetOrderDetailResp, err error) {
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询订单失败 err: %v", err)
}
// 获取产品信息
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, order.ProductId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询产品失败 err: %v", err)
}
// 获取查询状态
var queryState string
builder := l.svcCtx.QueryModel.SelectBuilder().Where("order_id = ?", order.Id).Columns("query_state")
queries, err := l.svcCtx.QueryModel.FindAll(l.ctx, builder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询查询状态失败 err: %v", err)
}
if len(queries) > 0 {
queryState = queries[0].QueryState
} else {
// 查询清理日志
cleanupBuilder := l.svcCtx.QueryCleanupDetailModel.SelectBuilder().
Where("order_id = ?", order.Id).
Where("del_state = ?", globalkey.DelStateNo).
OrderBy("create_time DESC").
Limit(1)
cleanupDetails, err := l.svcCtx.QueryCleanupDetailModel.FindAll(l.ctx, cleanupBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询清理日志失败 err: %v", err)
}
if len(cleanupDetails) > 0 {
queryState = model.QueryStateCleaned
} else {
queryState = ""
}
}
// 构建响应
resp = &types.AdminGetOrderDetailResp{
Id: order.Id,
OrderNo: order.OrderNo,
PlatformOrderId: order.PlatformOrderId.String,
ProductName: product.ProductName,
PaymentPlatform: order.PaymentPlatform,
PaymentScene: order.PaymentScene,
Amount: order.Amount,
Status: order.Status,
CreateTime: order.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: order.UpdateTime.Format("2006-01-02 15:04:05"),
QueryState: queryState,
}
// 处理可选字段
if order.PayTime.Valid {
resp.PayTime = order.PayTime.Time.Format("2006-01-02 15:04:05")
}
if order.RefundTime.Valid {
resp.RefundTime = order.RefundTime.Time.Format("2006-01-02 15:04:05")
}
return resp, nil
}

View File

@@ -0,0 +1,222 @@
package admin_order
import (
"context"
"sync"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/globalkey"
"aedata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetOrderListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetOrderListLogic {
return &AdminGetOrderListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetOrderListLogic) AdminGetOrderList(req *types.AdminGetOrderListReq) (resp *types.AdminGetOrderListResp, err error) {
// 构建查询条件
builder := l.svcCtx.OrderModel.SelectBuilder()
if req.OrderNo != "" {
builder = builder.Where("order_no = ?", req.OrderNo)
}
if req.PlatformOrderId != "" {
builder = builder.Where("platform_order_id = ?", req.PlatformOrderId)
}
if req.ProductName != "" {
builder = builder.Where("product_id IN (SELECT id FROM product WHERE product_name LIKE ?)", "%"+req.ProductName+"%")
}
if req.PaymentPlatform != "" {
builder = builder.Where("payment_platform = ?", req.PaymentPlatform)
}
if req.PaymentScene != "" {
builder = builder.Where("payment_scene = ?", req.PaymentScene)
}
if req.Amount > 0 {
builder = builder.Where("amount = ?", req.Amount)
}
if req.Status != "" {
builder = builder.Where("status = ?", req.Status)
}
// 时间范围查询
if req.CreateTimeStart != "" {
builder = builder.Where("create_time >= ?", req.CreateTimeStart)
}
if req.CreateTimeEnd != "" {
builder = builder.Where("create_time <= ?", req.CreateTimeEnd)
}
if req.PayTimeStart != "" {
builder = builder.Where("pay_time >= ?", req.PayTimeStart)
}
if req.PayTimeEnd != "" {
builder = builder.Where("pay_time <= ?", req.PayTimeEnd)
}
if req.RefundTimeStart != "" {
builder = builder.Where("refund_time >= ?", req.RefundTimeStart)
}
if req.RefundTimeEnd != "" {
builder = builder.Where("refund_time <= ?", req.RefundTimeEnd)
}
// 并发获取总数和列表
var total int64
var orders []*model.Order
err = mr.Finish(func() error {
var err error
total, err = l.svcCtx.OrderModel.FindCount(l.ctx, builder, "id")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询订单总数失败 err: %v", err)
}
return nil
}, func() error {
var err error
orders, err = l.svcCtx.OrderModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询订单列表失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
// 并发获取产品信息和查询状态
productMap := make(map[int64]string)
queryStateMap := make(map[int64]string)
var mu sync.Mutex
// 批量获取查询状态
if len(orders) > 0 {
orderIds := make([]int64, 0, len(orders))
for _, order := range orders {
orderIds = append(orderIds, order.Id)
}
// 1. 先查询当前查询状态
builder := l.svcCtx.QueryModel.SelectBuilder().
Where(squirrel.Eq{"order_id": orderIds}).
Columns("order_id", "query_state")
queries, err := l.svcCtx.QueryModel.FindAll(l.ctx, builder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 批量查询查询状态失败 err: %v", err)
}
// 2. 记录已找到查询状态的订单ID
foundOrderIds := make(map[int64]bool)
for _, query := range queries {
queryStateMap[query.OrderId] = query.QueryState
foundOrderIds[query.OrderId] = true
}
// 3. 查找未找到查询状态的订单是否在清理日志中
notFoundOrderIds := make([]int64, 0)
for _, orderId := range orderIds {
if !foundOrderIds[orderId] {
notFoundOrderIds = append(notFoundOrderIds, orderId)
}
}
if len(notFoundOrderIds) > 0 {
// 查询清理日志
cleanupBuilder := l.svcCtx.QueryCleanupDetailModel.SelectBuilder().
Where(squirrel.Eq{"order_id": notFoundOrderIds}).
Where("del_state = ?", globalkey.DelStateNo).
OrderBy("create_time DESC")
cleanupDetails, err := l.svcCtx.QueryCleanupDetailModel.FindAll(l.ctx, cleanupBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询清理日志失败 err: %v", err)
}
// 记录已清理的订单状态
for _, detail := range cleanupDetails {
if _, exists := queryStateMap[detail.OrderId]; !exists {
queryStateMap[detail.OrderId] = model.QueryStateCleaned // 使用常量标记为已清除状态
}
}
// 对于既没有查询状态也没有清理记录的订单,不设置状态(保持为空字符串)
for _, orderId := range notFoundOrderIds {
if _, exists := queryStateMap[orderId]; !exists {
queryStateMap[orderId] = "" // 未知状态保持为空字符串
}
}
}
}
// 并发获取产品信息
err = mr.MapReduceVoid(func(source chan<- interface{}) {
for _, order := range orders {
source <- order
}
}, func(item interface{}, writer mr.Writer[struct{}], cancel func(error)) {
order := item.(*model.Order)
// 获取产品信息
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, order.ProductId)
if err != nil && !errors.Is(err, model.ErrNotFound) {
cancel(errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询产品信息失败 err: %v", err))
return
}
mu.Lock()
if product != nil {
productMap[product.Id] = product.ProductName
} else {
productMap[order.ProductId] = "" // 产品不存在时设置为空字符串
}
mu.Unlock()
writer.Write(struct{}{})
}, func(pipe <-chan struct{}, cancel func(error)) {
for range pipe {
}
})
if err != nil {
return nil, err
}
// 构建响应
resp = &types.AdminGetOrderListResp{
Total: total,
Items: make([]types.OrderListItem, 0, len(orders)),
}
for _, order := range orders {
item := types.OrderListItem{
Id: order.Id,
OrderNo: order.OrderNo,
PlatformOrderId: order.PlatformOrderId.String,
ProductName: productMap[order.ProductId],
PaymentPlatform: order.PaymentPlatform,
PaymentScene: order.PaymentScene,
Amount: order.Amount,
Status: order.Status,
CreateTime: order.CreateTime.Format("2006-01-02 15:04:05"),
QueryState: queryStateMap[order.Id],
}
if order.PayTime.Valid {
item.PayTime = order.PayTime.Time.Format("2006-01-02 15:04:05")
}
if order.RefundTime.Valid {
item.RefundTime = order.RefundTime.Time.Format("2006-01-02 15:04:05")
}
resp.Items = append(resp.Items, item)
}
return resp, nil
}

View File

@@ -0,0 +1,92 @@
package admin_order
import (
"context"
"database/sql"
"fmt"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminRefundOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminRefundOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRefundOrderLogic {
return &AdminRefundOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminRefundOrderLogic) AdminRefundOrder(req *types.AdminRefundOrderReq) (resp *types.AdminRefundOrderResp, err error) {
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminRefundOrder, 查询订单失败 err: %v", err)
}
// 检查订单状态
if order.Status != "paid" {
return nil, errors.Wrapf(xerr.NewErrMsg("订单状态不正确,无法退款"), "AdminRefundOrder, 订单状态不正确,无法退款 err: %v", err)
}
// 检查退款金额
if req.RefundAmount > order.Amount {
return nil, errors.Wrapf(xerr.NewErrMsg("退款金额不能大于订单金额"), "AdminRefundOrder, 退款金额不能大于订单金额 err: %v", err)
}
refundResp, err := l.svcCtx.AlipayService.AliRefund(l.ctx, order.OrderNo, req.RefundAmount)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "AdminRefundOrder, 退款失败 err: %v", err)
}
if refundResp.IsSuccess() {
err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建退款记录
refund := &model.OrderRefund{
RefundNo: fmt.Sprintf("refund-%s", order.OrderNo),
PlatformRefundId: sql.NullString{String: refundResp.TradeNo, Valid: true},
OrderId: order.Id,
UserId: order.UserId,
ProductId: order.ProductId,
RefundAmount: req.RefundAmount,
RefundReason: sql.NullString{String: req.RefundReason, Valid: true},
Status: model.OrderRefundStatusPending,
RefundTime: sql.NullTime{Time: time.Now(), Valid: true},
}
if _, err := l.svcCtx.OrderRefundModel.Insert(ctx, session, refund); err != nil {
return fmt.Errorf("创建退款记录失败: %v", err)
}
// 更新订单状态
order.Status = model.OrderStatusRefunded
order.RefundTime = sql.NullTime{Time: time.Now(), Valid: true}
if _, err := l.svcCtx.OrderModel.Update(ctx, session, order); err != nil {
return fmt.Errorf("更新订单状态失败: %v", err)
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "AdminRefundOrder, 退款失败 err: %v", err)
}
return &types.AdminRefundOrderResp{
Status: model.OrderStatusRefunded,
RefundNo: fmt.Sprintf("refund-%s", order.OrderNo),
Amount: req.RefundAmount,
}, nil
} else {
return nil, errors.Wrapf(xerr.NewErrMsg(fmt.Sprintf("退款失败, : %v", refundResp.Msg)), "AdminRefundOrder, 退款失败 err: %v", err)
}
}

View File

@@ -0,0 +1,87 @@
package admin_order
import (
"context"
"database/sql"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminUpdateOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateOrderLogic {
return &AdminUpdateOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateOrderLogic) AdminUpdateOrder(req *types.AdminUpdateOrderReq) (resp *types.AdminUpdateOrderResp, err error) {
// 获取原订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 查询订单失败 err: %v", err)
}
// 更新订单字段
if req.OrderNo != nil {
order.OrderNo = *req.OrderNo
}
if req.PlatformOrderId != nil {
order.PlatformOrderId = sql.NullString{String: *req.PlatformOrderId, Valid: true}
}
if req.PaymentPlatform != nil {
order.PaymentPlatform = *req.PaymentPlatform
}
if req.PaymentScene != nil {
order.PaymentScene = *req.PaymentScene
}
if req.Amount != nil {
order.Amount = *req.Amount
}
if req.Status != nil {
order.Status = *req.Status
}
if req.PayTime != nil {
payTime, err := time.Parse("2006-01-02 15:04:05", *req.PayTime)
if err == nil {
order.PayTime = sql.NullTime{Time: payTime, Valid: true}
}
}
if req.RefundTime != nil {
refundTime, err := time.Parse("2006-01-02 15:04:05", *req.RefundTime)
if err == nil {
order.RefundTime = sql.NullTime{Time: refundTime, Valid: true}
}
}
// 使用事务更新订单
err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 更新订单
_, err := l.svcCtx.OrderModel.Update(ctx, session, order)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 更新订单失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
return &types.AdminUpdateOrderResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,57 @@
package admin_platform_user
import (
"context"
"database/sql"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminCreatePlatformUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreatePlatformUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreatePlatformUserLogic {
return &AdminCreatePlatformUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreatePlatformUserLogic) AdminCreatePlatformUser(req *types.AdminCreatePlatformUserReq) (resp *types.AdminCreatePlatformUserResp, err error) {
// 校验手机号唯一性
_, err = l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: req.Mobile, Valid: req.Mobile != ""})
if err == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机号已存在: %s", req.Mobile)
}
if err != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询手机号失败: %v", err)
}
user := &model.User{
Mobile: sql.NullString{String: req.Mobile, Valid: req.Mobile != ""},
Password: sql.NullString{String: req.Password, Valid: req.Password != ""},
Nickname: sql.NullString{String: req.Nickname, Valid: req.Nickname != ""},
Info: req.Info,
Inside: req.Inside,
}
result, err := l.svcCtx.UserModel.Insert(l.ctx, nil, user)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
}
id, err := result.LastInsertId()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取用户ID失败: %v", err)
}
resp = &types.AdminCreatePlatformUserResp{Id: id}
return resp, nil
}

View File

@@ -0,0 +1,43 @@
package admin_platform_user
import (
"context"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminDeletePlatformUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeletePlatformUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeletePlatformUserLogic {
return &AdminDeletePlatformUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeletePlatformUserLogic) AdminDeletePlatformUser(req *types.AdminDeletePlatformUserReq) (resp *types.AdminDeletePlatformUserResp, err error) {
user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %d, err: %v", req.Id, err)
}
user.DelState = 1
user.DeleteTime.Time = time.Now()
user.DeleteTime.Valid = true
err = l.svcCtx.UserModel.DeleteSoft(l.ctx, nil, user)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "软删除用户失败: %v", err)
}
resp = &types.AdminDeletePlatformUserResp{Success: true}
return resp, nil
}

View File

@@ -0,0 +1,53 @@
package admin_platform_user
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetPlatformUserDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetPlatformUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetPlatformUserDetailLogic {
return &AdminGetPlatformUserDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetPlatformUserDetailLogic) AdminGetPlatformUserDetail(req *types.AdminGetPlatformUserDetailReq) (resp *types.AdminGetPlatformUserDetailResp, err error) {
user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %d, err: %v", req.Id, err)
}
key := l.svcCtx.Config.Encrypt.SecretKey
DecryptMobile, err := crypto.DecryptMobile(user.Mobile.String, key)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密手机号失败: %v", err)
}
// 查询平台类型取第一个user_auth
resp = &types.AdminGetPlatformUserDetailResp{
Id: user.Id,
Mobile: DecryptMobile,
Nickname: "",
Info: user.Info,
Inside: user.Inside,
CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: user.UpdateTime.Format("2006-01-02 15:04:05"),
}
if user.Nickname.Valid {
resp.Nickname = user.Nickname.String
}
return resp, nil
}

View File

@@ -0,0 +1,88 @@
package admin_platform_user
import (
"context"
"database/sql"
"fmt"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetPlatformUserListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetPlatformUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetPlatformUserListLogic {
return &AdminGetPlatformUserListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetPlatformUserListLogic) AdminGetPlatformUserList(req *types.AdminGetPlatformUserListReq) (resp *types.AdminGetPlatformUserListResp, err error) {
builder := l.svcCtx.UserModel.SelectBuilder()
if req.Mobile != "" {
builder = builder.Where("mobile = ?", req.Mobile)
}
if req.Nickname != "" {
builder = builder.Where("nickname = ?", req.Nickname)
}
if req.Inside != 0 {
builder = builder.Where("inside = ?", req.Inside)
}
if req.CreateTimeStart != "" {
builder = builder.Where("create_time >= ?", req.CreateTimeStart)
}
if req.CreateTimeEnd != "" {
builder = builder.Where("create_time <= ?", req.CreateTimeEnd)
}
orderBy := "id DESC"
if req.OrderBy != "" && req.OrderType != "" {
orderBy = fmt.Sprintf("%s %s", req.OrderBy, req.OrderType)
}
users, total, err := l.svcCtx.UserModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, orderBy)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户分页失败: %v", err)
}
var items []types.PlatformUserListItem
secretKey := l.svcCtx.Config.Encrypt.SecretKey
for _, user := range users {
mobile := user.Mobile
if mobile.Valid {
encryptedMobile, err := crypto.DecryptMobile(mobile.String, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 解密手机号失败: %+v", err)
}
mobile = sql.NullString{String: encryptedMobile, Valid: true}
}
itemData := types.PlatformUserListItem{
Id: user.Id,
Mobile: mobile.String,
Nickname: "",
Info: user.Info,
Inside: user.Inside,
CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: user.UpdateTime.Format("2006-01-02 15:04:05"),
}
if user.Nickname.Valid {
itemData.Nickname = user.Nickname.String
}
items = append(items, itemData)
}
resp = &types.AdminGetPlatformUserListResp{
Total: total,
Items: items,
}
return resp, nil
}

View File

@@ -0,0 +1,64 @@
package admin_platform_user
import (
"context"
"database/sql"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminUpdatePlatformUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdatePlatformUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdatePlatformUserLogic {
return &AdminUpdatePlatformUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdatePlatformUserLogic) AdminUpdatePlatformUser(req *types.AdminUpdatePlatformUserReq) (resp *types.AdminUpdatePlatformUserResp, err error) {
user, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %d, err: %v", req.Id, err)
}
if req.Mobile != nil {
key := l.svcCtx.Config.Encrypt.SecretKey
EncryptMobile, err := crypto.EncryptMobile(*req.Mobile, key)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
}
user.Mobile = sql.NullString{String: EncryptMobile, Valid: true}
}
if req.Nickname != nil {
user.Nickname = sql.NullString{String: *req.Nickname, Valid: *req.Nickname != ""}
}
if req.Info != nil {
user.Info = *req.Info
}
if req.Inside != nil {
if *req.Inside != 1 && *req.Inside != 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "内部用户状态错误: %d", *req.Inside)
}
user.Inside = *req.Inside
}
if req.Password != nil {
user.Password = sql.NullString{String: *req.Password, Valid: *req.Password != ""}
}
_, err = l.svcCtx.UserModel.Update(l.ctx, nil, user)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新用户失败: %v", err)
}
resp = &types.AdminUpdatePlatformUserResp{Success: true}
return resp, nil
}

View File

@@ -0,0 +1,50 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"database/sql"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminCreateProductLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreateProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateProductLogic {
return &AdminCreateProductLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreateProductLogic) AdminCreateProduct(req *types.AdminCreateProductReq) (resp *types.AdminCreateProductResp, err error) {
// 1. 数据转换
data := &model.Product{
ProductName: req.ProductName,
ProductEn: req.ProductEn,
Description: req.Description,
Notes: sql.NullString{String: req.Notes, Valid: req.Notes != ""},
CostPrice: req.CostPrice,
SellPrice: req.SellPrice,
}
// 2. 数据库操作
result, err := l.svcCtx.ProductModel.Insert(l.ctx, nil, data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"创建产品失败, err: %v, req: %+v", err, req)
}
// 3. 返回结果
id, _ := result.LastInsertId()
return &types.AdminCreateProductResp{Id: id}, nil
}

View File

@@ -0,0 +1,44 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminDeleteProductLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeleteProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeleteProductLogic {
return &AdminDeleteProductLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeleteProductLogic) AdminDeleteProduct(req *types.AdminDeleteProductReq) (resp *types.AdminDeleteProductResp, err error) {
// 1. 查询记录是否存在
record, err := l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查找产品失败, err: %v, id: %d", err, req.Id)
}
// 2. 执行软删除
err = l.svcCtx.ProductModel.DeleteSoft(l.ctx, nil, record)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"删除产品失败, err: %v, id: %d", err, req.Id)
}
// 3. 返回结果
return &types.AdminDeleteProductResp{Success: true}, nil
}

View File

@@ -0,0 +1,49 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetProductDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetProductDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetProductDetailLogic {
return &AdminGetProductDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetProductDetailLogic) AdminGetProductDetail(req *types.AdminGetProductDetailReq) (resp *types.AdminGetProductDetailResp, err error) {
// 1. 查询记录
record, err := l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查找产品失败, err: %v, id: %d", err, req.Id)
}
// 2. 构建响应
resp = &types.AdminGetProductDetailResp{
Id: record.Id,
ProductName: record.ProductName,
ProductEn: record.ProductEn,
Description: record.Description,
Notes: record.Notes.String,
CostPrice: record.CostPrice,
SellPrice: record.SellPrice,
CreateTime: record.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: record.UpdateTime.Format("2006-01-02 15:04:05"),
}
return resp, nil
}

View File

@@ -0,0 +1,119 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetProductFeatureListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetProductFeatureListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetProductFeatureListLogic {
return &AdminGetProductFeatureListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetProductFeatureListLogic) AdminGetProductFeatureList(req *types.AdminGetProductFeatureListReq) (resp *[]types.AdminGetProductFeatureListResp, err error) {
// 1. 构建查询条件
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().
Where("product_id = ?", req.ProductId)
// 2. 执行查询
list, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "sort ASC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查询产品功能列表失败, err: %v, product_id: %d", err, req.ProductId)
}
// 3. 获取所有功能ID
featureIds := make([]int64, 0, len(list))
for _, item := range list {
featureIds = append(featureIds, item.FeatureId)
}
// 4. 并发查询功能详情
type featureResult struct {
feature *model.Feature
err error
}
results := make([]featureResult, len(featureIds))
err = mr.MapReduceVoid(func(source chan<- interface{}) {
for i, id := range featureIds {
source <- struct {
index int
id int64
}{i, id}
}
}, func(item interface{}, writer mr.Writer[featureResult], cancel func(error)) {
data := item.(struct {
index int
id int64
})
feature, err := l.svcCtx.FeatureModel.FindOne(l.ctx, data.id)
writer.Write(featureResult{
feature: feature,
err: err,
})
}, func(pipe <-chan featureResult, cancel func(error)) {
for result := range pipe {
if result.err != nil {
l.Logger.Errorf("查询功能详情失败, feature_id: %d, err: %v", result.feature.Id, result.err)
continue
}
results = append(results, result)
}
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"并发查询功能详情失败, err: %v", err)
}
// 5. 构建功能ID到详情的映射
featureMap := make(map[int64]*model.Feature)
for _, result := range results {
if result.feature != nil {
featureMap[result.feature.Id] = result.feature
}
}
// 6. 构建响应列表
items := make([]types.AdminGetProductFeatureListResp, 0, len(list))
for _, item := range list {
feature, exists := featureMap[item.FeatureId]
if !exists {
continue // 跳过不存在的功能
}
listItem := types.AdminGetProductFeatureListResp{
Id: item.Id,
ProductId: item.ProductId,
FeatureId: item.FeatureId,
ApiId: feature.ApiId,
Name: feature.Name,
Sort: item.Sort,
Enable: item.Enable,
IsImportant: item.IsImportant,
CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
}
items = append(items, listItem)
}
// 7. 返回结果
return &items, nil
}

View File

@@ -0,0 +1,69 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetProductListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetProductListLogic {
return &AdminGetProductListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetProductListLogic) AdminGetProductList(req *types.AdminGetProductListReq) (resp *types.AdminGetProductListResp, err error) {
// 1. 构建查询条件
builder := l.svcCtx.ProductModel.SelectBuilder()
// 2. 添加查询条件
if req.ProductName != nil && *req.ProductName != "" {
builder = builder.Where("product_name LIKE ?", "%"+*req.ProductName+"%")
}
if req.ProductEn != nil && *req.ProductEn != "" {
builder = builder.Where("product_en LIKE ?", "%"+*req.ProductEn+"%")
}
// 3. 执行分页查询
list, total, err := l.svcCtx.ProductModel.FindPageListByPageWithTotal(
l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查询产品列表失败, err: %v, req: %+v", err, req)
}
// 4. 构建响应列表
items := make([]types.ProductListItem, 0, len(list))
for _, item := range list {
listItem := types.ProductListItem{
Id: item.Id,
ProductName: item.ProductName,
ProductEn: item.ProductEn,
Description: item.Description,
Notes: item.Notes.String,
CostPrice: item.CostPrice,
SellPrice: item.SellPrice,
CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
}
items = append(items, listItem)
}
// 5. 返回结果
return &types.AdminGetProductListResp{
Total: total,
Items: items,
}, nil
}

View File

@@ -0,0 +1,159 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"sync"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminUpdateProductFeaturesLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateProductFeaturesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateProductFeaturesLogic {
return &AdminUpdateProductFeaturesLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateProductFeaturesLogic) AdminUpdateProductFeatures(req *types.AdminUpdateProductFeaturesReq) (resp *types.AdminUpdateProductFeaturesResp, err error) {
// 1. 查询现有关联
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().
Where("product_id = ?", req.ProductId)
existingList, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查询现有产品功能关联失败, err: %v, product_id: %d", err, req.ProductId)
}
// 2. 构建现有关联的映射
existingMap := make(map[int64]*model.ProductFeature)
for _, item := range existingList {
existingMap[item.FeatureId] = item
}
// 3. 构建新关联的映射
newMap := make(map[int64]*types.ProductFeatureItem)
for _, item := range req.Features {
newMap[item.FeatureId] = &item
}
// 4. 在事务中执行更新操作
err = l.svcCtx.ProductFeatureModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 4.1 处理需要删除的关联
var mu sync.Mutex
var deleteIds []int64
err = mr.MapReduceVoid(func(source chan<- interface{}) {
for featureId, existing := range existingMap {
if _, exists := newMap[featureId]; !exists {
source <- existing.Id
}
}
}, func(item interface{}, writer mr.Writer[struct{}], cancel func(error)) {
id := item.(int64)
mu.Lock()
deleteIds = append(deleteIds, id)
mu.Unlock()
}, func(pipe <-chan struct{}, cancel func(error)) {
// 等待所有ID收集完成
})
if err != nil {
return errors.Wrapf(err, "收集待删除ID失败")
}
// 批量删除
if len(deleteIds) > 0 {
for _, id := range deleteIds {
err = l.svcCtx.ProductFeatureModel.Delete(ctx, session, id)
if err != nil {
return errors.Wrapf(err, "删除产品功能关联失败, product_id: %d, id: %d",
req.ProductId, id)
}
}
}
// 4.2 并发处理需要新增或更新的关联
var updateErr error
err = mr.MapReduceVoid(func(source chan<- interface{}) {
for featureId, newItem := range newMap {
source <- struct {
featureId int64
newItem *types.ProductFeatureItem
existing *model.ProductFeature
}{
featureId: featureId,
newItem: newItem,
existing: existingMap[featureId],
}
}
}, func(item interface{}, writer mr.Writer[struct{}], cancel func(error)) {
data := item.(struct {
featureId int64
newItem *types.ProductFeatureItem
existing *model.ProductFeature
})
if data.existing != nil {
// 更新现有关联
data.existing.Sort = data.newItem.Sort
data.existing.Enable = data.newItem.Enable
data.existing.IsImportant = data.newItem.IsImportant
_, err = l.svcCtx.ProductFeatureModel.Update(ctx, session, data.existing)
if err != nil {
updateErr = errors.Wrapf(err, "更新产品功能关联失败, product_id: %d, feature_id: %d",
req.ProductId, data.featureId)
cancel(updateErr)
return
}
} else {
// 新增关联
newFeature := &model.ProductFeature{
ProductId: req.ProductId,
FeatureId: data.featureId,
Sort: data.newItem.Sort,
Enable: data.newItem.Enable,
IsImportant: data.newItem.IsImportant,
}
_, err = l.svcCtx.ProductFeatureModel.Insert(ctx, session, newFeature)
if err != nil {
updateErr = errors.Wrapf(err, "新增产品功能关联失败, product_id: %d, feature_id: %d",
req.ProductId, data.featureId)
cancel(updateErr)
return
}
}
}, func(pipe <-chan struct{}, cancel func(error)) {
// 等待所有更新完成
})
if err != nil {
return errors.Wrapf(err, "并发更新产品功能关联失败")
}
if updateErr != nil {
return updateErr
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"更新产品功能关联失败, err: %v, req: %+v", err, req)
}
// 5. 返回结果
return &types.AdminUpdateProductFeaturesResp{Success: true}, nil
}

View File

@@ -0,0 +1,65 @@
package admin_product
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"context"
"database/sql"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminUpdateProductLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateProductLogic {
return &AdminUpdateProductLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateProductLogic) AdminUpdateProduct(req *types.AdminUpdateProductReq) (resp *types.AdminUpdateProductResp, err error) {
// 1. 查询记录是否存在
record, err := l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"查找产品失败, err: %v, id: %d", err, req.Id)
}
// 2. 更新字段
if req.ProductName != nil {
record.ProductName = *req.ProductName
}
if req.ProductEn != nil {
record.ProductEn = *req.ProductEn
}
if req.Description != nil {
record.Description = *req.Description
}
if req.Notes != nil {
record.Notes = sql.NullString{String: *req.Notes, Valid: *req.Notes != ""}
}
if req.CostPrice != nil {
record.CostPrice = *req.CostPrice
}
if req.SellPrice != nil {
record.SellPrice = *req.SellPrice
}
// 3. 执行更新操作
_, err = l.svcCtx.ProductModel.Update(l.ctx, nil, record)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
"更新产品失败, err: %v, req: %+v", err, req)
}
// 4. 返回结果
return &types.AdminUpdateProductResp{Success: true}, nil
}

View File

@@ -0,0 +1,62 @@
package admin_query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/globalkey"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetQueryCleanupConfigListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetQueryCleanupConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetQueryCleanupConfigListLogic {
return &AdminGetQueryCleanupConfigListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetQueryCleanupConfigListLogic) AdminGetQueryCleanupConfigList(req *types.AdminGetQueryCleanupConfigListReq) (resp *types.AdminGetQueryCleanupConfigListResp, err error) {
// 构建查询条件
builder := l.svcCtx.QueryCleanupConfigModel.SelectBuilder().
Where("del_state = ?", globalkey.DelStateNo)
if req.Status > 0 {
builder = builder.Where("status = ?", req.Status)
}
// 查询配置列表
configs, err := l.svcCtx.QueryCleanupConfigModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理配置列表失败 err: %v", err)
}
// 构建响应
resp = &types.AdminGetQueryCleanupConfigListResp{
Items: make([]types.QueryCleanupConfigItem, 0, len(configs)),
}
for _, config := range configs {
item := types.QueryCleanupConfigItem{
Id: config.Id,
ConfigKey: config.ConfigKey,
ConfigValue: config.ConfigValue,
ConfigDesc: config.ConfigDesc,
Status: config.Status,
CreateTime: config.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: config.UpdateTime.Format("2006-01-02 15:04:05"),
}
resp.Items = append(resp.Items, item)
}
return resp, nil
}

View File

@@ -0,0 +1,126 @@
package admin_query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/globalkey"
"aedata-server/common/xerr"
"context"
"sync"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetQueryCleanupDetailListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetQueryCleanupDetailListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetQueryCleanupDetailListLogic {
return &AdminGetQueryCleanupDetailListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetQueryCleanupDetailListLogic) AdminGetQueryCleanupDetailList(req *types.AdminGetQueryCleanupDetailListReq) (resp *types.AdminGetQueryCleanupDetailListResp, err error) {
// 1. 验证清理日志是否存在
_, err = l.svcCtx.QueryCleanupLogModel.FindOne(l.ctx, req.LogId)
if err != nil {
if err == model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "清理日志不存在, log_id: %d", req.LogId)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理日志失败, log_id: %d, err: %v", req.LogId, err)
}
// 2. 构建查询条件
builder := l.svcCtx.QueryCleanupDetailModel.SelectBuilder().
Where("cleanup_log_id = ?", req.LogId).
Where("del_state = ?", globalkey.DelStateNo)
// 3. 并发获取总数和列表
var total int64
var details []*model.QueryCleanupDetail
err = mr.Finish(func() error {
var err error
total, err = l.svcCtx.QueryCleanupDetailModel.FindCount(l.ctx, builder, "id")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理详情总数失败 err: %v", err)
}
return nil
}, func() error {
var err error
details, err = l.svcCtx.QueryCleanupDetailModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理详情列表失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
// 4. 获取所有产品ID
productIds := make([]int64, 0, len(details))
for _, detail := range details {
productIds = append(productIds, detail.ProductId)
}
// 5. 并发获取产品信息
productMap := make(map[int64]string)
var mu sync.Mutex
err = mr.MapReduceVoid(func(source chan<- interface{}) {
for _, productId := range productIds {
source <- productId
}
}, func(item interface{}, writer mr.Writer[struct{}], cancel func(error)) {
productId := item.(int64)
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, productId)
if err != nil && !errors.Is(err, model.ErrNotFound) {
cancel(errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询产品信息失败, product_id: %d, err: %v", productId, err))
return
}
mu.Lock()
if product != nil {
productMap[productId] = product.ProductName
} else {
productMap[productId] = "" // 产品不存在时设置为空字符串
}
mu.Unlock()
writer.Write(struct{}{})
}, func(pipe <-chan struct{}, cancel func(error)) {
for range pipe {
}
})
if err != nil {
return nil, err
}
// 6. 构建响应
resp = &types.AdminGetQueryCleanupDetailListResp{
Total: total,
Items: make([]types.QueryCleanupDetailItem, 0, len(details)),
}
for _, detail := range details {
item := types.QueryCleanupDetailItem{
Id: detail.Id,
CleanupLogId: detail.CleanupLogId,
QueryId: detail.QueryId,
OrderId: detail.OrderId,
UserId: detail.UserId,
ProductName: productMap[detail.ProductId],
QueryState: detail.QueryState,
CreateTimeOld: detail.CreateTimeOld.Format("2006-01-02 15:04:05"),
CreateTime: detail.CreateTime.Format("2006-01-02 15:04:05"),
}
resp.Items = append(resp.Items, item)
}
return resp, nil
}

View File

@@ -0,0 +1,88 @@
package admin_query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/globalkey"
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetQueryCleanupLogListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetQueryCleanupLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetQueryCleanupLogListLogic {
return &AdminGetQueryCleanupLogListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetQueryCleanupLogListLogic) AdminGetQueryCleanupLogList(req *types.AdminGetQueryCleanupLogListReq) (resp *types.AdminGetQueryCleanupLogListResp, err error) {
// 构建查询条件
builder := l.svcCtx.QueryCleanupLogModel.SelectBuilder().
Where("del_state = ?", globalkey.DelStateNo)
if req.Status > 0 {
builder = builder.Where("status = ?", req.Status)
}
if req.StartTime != "" {
builder = builder.Where("cleanup_time >= ?", req.StartTime)
}
if req.EndTime != "" {
builder = builder.Where("cleanup_time <= ?", req.EndTime)
}
// 并发获取总数和列表
var total int64
var logs []*model.QueryCleanupLog
err = mr.Finish(func() error {
var err error
total, err = l.svcCtx.QueryCleanupLogModel.FindCount(l.ctx, builder, "id")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理日志总数失败 err: %v", err)
}
return nil
}, func() error {
var err error
logs, err = l.svcCtx.QueryCleanupLogModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理日志列表失败 err: %v", err)
}
return nil
})
if err != nil {
return nil, err
}
// 构建响应
resp = &types.AdminGetQueryCleanupLogListResp{
Total: total,
Items: make([]types.QueryCleanupLogItem, 0, len(logs)),
}
for _, log := range logs {
item := types.QueryCleanupLogItem{
Id: log.Id,
CleanupTime: log.CleanupTime.Format("2006-01-02 15:04:05"),
CleanupBefore: log.CleanupBefore.Format("2006-01-02 15:04:05"),
Status: log.Status,
AffectedRows: log.AffectedRows,
ErrorMsg: log.ErrorMsg.String,
Remark: log.Remark.String,
CreateTime: log.CreateTime.Format("2006-01-02 15:04:05"),
}
resp.Items = append(resp.Items, item)
}
return resp, nil
}

View File

@@ -0,0 +1,189 @@
package admin_query
import (
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"aedata-server/pkg/lzkit/lzUtils"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminGetQueryDetailByOrderIdLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetQueryDetailByOrderIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetQueryDetailByOrderIdLogic {
return &AdminGetQueryDetailByOrderIdLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetQueryDetailByOrderIdLogic) AdminGetQueryDetailByOrderId(req *types.AdminGetQueryDetailByOrderIdReq) (resp *types.AdminGetQueryDetailByOrderIdResp, err error) {
// 获取报告信息
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %+v", err)
}
var query types.AdminGetQueryDetailByOrderIdResp
query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
// 解密查询数据
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %+v", err)
}
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
if updateFeatureAndProductFeatureErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
}
// 复制报告数据
err = copier.Copy(&query, queryModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.ProductName = product.ProductName
return &types.AdminGetQueryDetailByOrderIdResp{
Id: query.Id,
OrderId: query.OrderId,
UserId: query.UserId,
ProductName: query.ProductName,
QueryParams: query.QueryParams,
QueryData: query.QueryData,
CreateTime: query.CreateTime,
UpdateTime: query.UpdateTime,
QueryState: query.QueryState,
}, nil
}
// ProcessQueryData 解密和反序列化 QueryData
func ProcessQueryData(queryData sql.NullString, target *[]types.AdminQueryItem, key []byte) error {
queryDataStr := lzUtils.NullStringToString(queryData)
if queryDataStr == "" {
return nil
}
// 解密数据
decryptedData, decryptErr := crypto.AesDecrypt(queryDataStr, key)
if decryptErr != nil {
return decryptErr
}
// 解析 JSON 数组
var decryptedArray []map[string]interface{}
unmarshalErr := json.Unmarshal(decryptedData, &decryptedArray)
if unmarshalErr != nil {
return unmarshalErr
}
// 确保 target 具有正确的长度
if len(*target) == 0 {
*target = make([]types.AdminQueryItem, len(decryptedArray))
}
// 填充解密后的数据到 target
for i := 0; i < len(decryptedArray); i++ {
// 直接填充解密数据到 Data 字段
(*target)[i].Data = decryptedArray[i]
}
return nil
}
// ProcessQueryParams解密和反序列化 QueryParams
func ProcessQueryParams(QueryParams string, target *map[string]interface{}, key []byte) error {
// 解密 QueryParams
decryptedData, decryptErr := crypto.AesDecrypt(QueryParams, key)
if decryptErr != nil {
return decryptErr
}
// 反序列化解密后的数据
unmarshalErr := json.Unmarshal(decryptedData, target)
if unmarshalErr != nil {
return unmarshalErr
}
return nil
}
func (l *AdminGetQueryDetailByOrderIdLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.AdminQueryItem) error {
// 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
for i := len(*target) - 1; i >= 0; i-- {
queryItem := &(*target)[i]
// 确保 Data 为 map 类型
data, ok := queryItem.Data.(map[string]interface{})
if !ok {
return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
}
// 从 Data 中获取 apiID
apiID, ok := data["apiID"].(string)
if !ok {
return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
}
// 查询 Feature
feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
if err != nil {
// 如果 Feature 查不到,也要删除当前 QueryItem
*target = append((*target)[:i], (*target)[i+1:]...)
continue
}
// 查询 ProductFeatureModel
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
}
// 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
var featureData map[string]interface{}
sort := 0
for _, pf := range productFeatures {
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{
"featureName": feature.Name,
"sort": sort,
}
// 更新 queryItem 的 Feature 字段(不是数组)
queryItem.Feature = featureData
}
return nil
}

View File

@@ -0,0 +1,63 @@
package admin_query
import (
"context"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminUpdateQueryCleanupConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateQueryCleanupConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateQueryCleanupConfigLogic {
return &AdminUpdateQueryCleanupConfigLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateQueryCleanupConfigLogic) AdminUpdateQueryCleanupConfig(req *types.AdminUpdateQueryCleanupConfigReq) (resp *types.AdminUpdateQueryCleanupConfigResp, err error) {
// 使用事务处理更新操作
err = l.svcCtx.QueryCleanupConfigModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 1. 查询配置是否存在
config, err := l.svcCtx.QueryCleanupConfigModel.FindOne(ctx, req.Id)
if err != nil {
if err == model.ErrNotFound {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "配置不存在, id: %d", req.Id)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询配置失败, id: %d, err: %v", req.Id, err)
}
// 2. 更新配置
config.ConfigValue = req.ConfigValue
config.Status = req.Status
config.UpdateTime = time.Now()
_, err = l.svcCtx.QueryCleanupConfigModel.Update(ctx, session, config)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新配置失败, id: %d, err: %v", req.Id, err)
}
return nil
})
if err != nil {
return nil, err
}
return &types.AdminUpdateQueryCleanupConfigResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,83 @@
package admin_role
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type CreateRoleLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
return &CreateRoleLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CreateRoleLogic) CreateRole(req *types.CreateRoleReq) (resp *types.CreateRoleResp, err error) {
// 检查角色编码是否已存在
roleModel, err := l.svcCtx.AdminRoleModel.FindOneByRoleCode(l.ctx, req.RoleCode)
if err != nil && err != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建角色失败: %v", err)
}
if roleModel != nil && roleModel.RoleName == req.RoleName {
return nil, errors.Wrapf(xerr.NewErrMsg("角色名称已存在"), "创建角色失败, 角色名称已存在: %v", err)
}
// 创建角色
role := &model.AdminRole{
RoleName: req.RoleName,
RoleCode: req.RoleCode,
Description: req.Description,
Status: req.Status,
Sort: req.Sort,
}
var roleId int64
// 使用事务创建角色和关联菜单
err = l.svcCtx.AdminRoleModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建角色
result, err := l.svcCtx.AdminRoleModel.Insert(ctx, session, role)
if err != nil {
return errors.New("插入新角色失败")
}
roleId, err = result.LastInsertId()
if err != nil {
return errors.New("获取新角色ID失败")
}
// 创建角色菜单关联
if len(req.MenuIds) > 0 {
for _, menuId := range req.MenuIds {
roleMenu := &model.AdminRoleMenu{
RoleId: roleId,
MenuId: menuId,
}
_, err = l.svcCtx.AdminRoleMenuModel.Insert(ctx, session, roleMenu)
if err != nil {
return errors.New("插入角色菜单关联失败")
}
}
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建角色失败: %v", err)
}
return &types.CreateRoleResp{
Id: roleId,
}, nil
}

View File

@@ -0,0 +1,84 @@
package admin_role
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type DeleteRoleLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRoleLogic {
return &DeleteRoleLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeleteRoleLogic) DeleteRole(req *types.DeleteRoleReq) (resp *types.DeleteRoleResp, err error) {
// 检查角色是否存在
_, err = l.svcCtx.AdminRoleModel.FindOne(l.ctx, req.Id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("角色不存在"), "删除角色失败, 角色不存在err: %v", err)
}
return nil, err
}
// 使用事务删除角色和关联数据
err = l.svcCtx.AdminRoleModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 删除角色菜单关联
builder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().
Where("role_id = ?", req.Id)
menus, err := l.svcCtx.AdminRoleMenuModel.FindAll(ctx, builder, "id ASC")
if err != nil {
return err
}
for _, menu := range menus {
err = l.svcCtx.AdminRoleMenuModel.Delete(ctx, session, menu.Id)
if err != nil {
return err
}
}
// 删除角色用户关联
builder = l.svcCtx.AdminUserRoleModel.SelectBuilder().
Where("role_id = ?", req.Id)
users, err := l.svcCtx.AdminUserRoleModel.FindAll(ctx, builder, "id ASC")
if err != nil {
return err
}
for _, user := range users {
err = l.svcCtx.AdminUserRoleModel.Delete(ctx, session, user.Id)
if err != nil {
return err
}
}
// 删除角色
err = l.svcCtx.AdminRoleModel.Delete(ctx, session, req.Id)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除角色失败err: %v", err)
}
return &types.DeleteRoleResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,91 @@
package admin_role
import (
"context"
"sync"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type GetRoleDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRoleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleDetailLogic {
return &GetRoleDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRoleDetailLogic) GetRoleDetail(req *types.GetRoleDetailReq) (resp *types.GetRoleDetailResp, err error) {
// 使用MapReduceVoid并发获取角色信息和菜单ID
var role *model.AdminRole
var menuIds []int64
var mutex sync.Mutex
var wg sync.WaitGroup
mr.MapReduceVoid(func(source chan<- interface{}) {
source <- 1 // 获取角色信息
source <- 2 // 获取菜单ID
}, func(item interface{}, writer mr.Writer[interface{}], cancel func(error)) {
taskType := item.(int)
wg.Add(1)
defer wg.Done()
if taskType == 1 {
result, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, req.Id)
if err != nil {
cancel(err)
return
}
mutex.Lock()
role = result
mutex.Unlock()
} else if taskType == 2 {
builder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().
Where("role_id = ?", req.Id)
menus, err := l.svcCtx.AdminRoleMenuModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
cancel(err)
return
}
mutex.Lock()
menuIds = lo.Map(menus, func(item *model.AdminRoleMenu, _ int) int64 {
return item.MenuId
})
mutex.Unlock()
}
}, func(pipe <-chan interface{}, cancel func(error)) {
// 不需要处理pipe中的数据
})
wg.Wait()
if role == nil {
return nil, errors.Wrapf(xerr.NewErrMsg("角色不存在"), "获取角色详情失败, 角色不存在err: %v", err)
}
return &types.GetRoleDetailResp{
Id: role.Id,
RoleName: role.RoleName,
RoleCode: role.RoleCode,
Description: role.Description,
Status: role.Status,
Sort: role.Sort,
CreateTime: role.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: role.UpdateTime.Format("2006-01-02 15:04:05"),
MenuIds: menuIds,
}, nil
}

View File

@@ -0,0 +1,148 @@
package admin_role
import (
"context"
"sync"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type GetRoleListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleListLogic {
return &GetRoleListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRoleListLogic) GetRoleList(req *types.GetRoleListReq) (resp *types.GetRoleListResp, err error) {
resp = &types.GetRoleListResp{
Items: make([]types.RoleListItem, 0),
Total: 0,
}
// 构建查询条件
builder := l.svcCtx.AdminRoleModel.SelectBuilder()
if len(req.Name) > 0 {
builder = builder.Where("role_name LIKE ?", "%"+req.Name+"%")
}
if len(req.Code) > 0 {
builder = builder.Where("role_code LIKE ?", "%"+req.Code+"%")
}
if req.Status != -1 {
builder = builder.Where("status = ?", req.Status)
}
// 设置分页
offset := (req.Page - 1) * req.PageSize
builder = builder.OrderBy("sort ASC").Limit(uint64(req.PageSize)).Offset(uint64(offset))
// 使用MapReduceVoid并发获取总数和列表数据
var roles []*model.AdminRole
var total int64
var mutex sync.Mutex
var wg sync.WaitGroup
mr.MapReduceVoid(func(source chan<- interface{}) {
source <- 1 // 获取角色列表
source <- 2 // 获取总数
}, func(item interface{}, writer mr.Writer[*model.AdminRole], cancel func(error)) {
taskType := item.(int)
wg.Add(1)
defer wg.Done()
if taskType == 1 {
result, err := l.svcCtx.AdminRoleModel.FindAll(l.ctx, builder, "id DESC")
if err != nil {
cancel(err)
return
}
mutex.Lock()
roles = result
mutex.Unlock()
} else if taskType == 2 {
countBuilder := l.svcCtx.AdminRoleModel.SelectBuilder()
if len(req.Name) > 0 {
countBuilder = countBuilder.Where("role_name LIKE ?", "%"+req.Name+"%")
}
if len(req.Code) > 0 {
countBuilder = countBuilder.Where("role_code LIKE ?", "%"+req.Code+"%")
}
if req.Status != -1 {
countBuilder = countBuilder.Where("status = ?", req.Status)
}
count, err := l.svcCtx.AdminRoleModel.FindCount(l.ctx, countBuilder, "id")
if err != nil {
cancel(err)
return
}
mutex.Lock()
total = count
mutex.Unlock()
}
}, func(pipe <-chan *model.AdminRole, cancel func(error)) {
// 不需要处理pipe中的数据
})
wg.Wait()
// 并发获取每个角色的菜单ID
var roleItems []types.RoleListItem
var roleItemsMutex sync.Mutex
mr.MapReduceVoid(func(source chan<- interface{}) {
for _, role := range roles {
source <- role
}
}, func(item interface{}, writer mr.Writer[[]int64], cancel func(error)) {
role := item.(*model.AdminRole)
// 获取角色关联的菜单ID
builder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().
Where("role_id = ?", role.Id)
menus, err := l.svcCtx.AdminRoleMenuModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
cancel(err)
return
}
menuIds := lo.Map(menus, func(item *model.AdminRoleMenu, _ int) int64 {
return item.MenuId
})
writer.Write(menuIds)
}, func(pipe <-chan []int64, cancel func(error)) {
for _, role := range roles {
menuIds := <-pipe
item := types.RoleListItem{
Id: role.Id,
RoleName: role.RoleName,
RoleCode: role.RoleCode,
Description: role.Description,
Status: role.Status,
Sort: role.Sort,
CreateTime: role.CreateTime.Format("2006-01-02 15:04:05"),
MenuIds: menuIds,
}
roleItemsMutex.Lock()
roleItems = append(roleItems, item)
roleItemsMutex.Unlock()
}
})
resp.Items = roleItems
resp.Total = total
return resp, nil
}

View File

@@ -0,0 +1,148 @@
package admin_role
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type UpdateRoleLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRoleLogic {
return &UpdateRoleLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateRoleLogic) UpdateRole(req *types.UpdateRoleReq) (resp *types.UpdateRoleResp, err error) {
// 检查角色是否存在
role, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, req.Id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("角色不存在"), "更新角色失败, 角色不存在err: %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新角色失败err: %v", err)
}
// 检查角色编码是否重复
if req.RoleCode != nil && *req.RoleCode != role.RoleCode {
roleModel, err := l.svcCtx.AdminRoleModel.FindOneByRoleCode(l.ctx, *req.RoleCode)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新角色失败err: %v", err)
}
if roleModel != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("角色编码已存在"), "更新角色失败, 角色编码已存在err: %v", err)
}
}
// 更新角色信息
if req.RoleName != nil {
role.RoleName = *req.RoleName
}
if req.RoleCode != nil {
role.RoleCode = *req.RoleCode
}
if req.Description != nil {
role.Description = *req.Description
}
if req.Status != nil {
role.Status = *req.Status
}
if req.Sort != nil {
role.Sort = *req.Sort
}
// 使用事务更新角色和关联菜单
err = l.svcCtx.AdminRoleModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 更新角色
_, err = l.svcCtx.AdminRoleModel.Update(ctx, session, role)
if err != nil {
return err
}
if req.MenuIds != nil {
// 1. 获取当前关联的菜单ID
builder := l.svcCtx.AdminRoleMenuModel.SelectBuilder().
Where("role_id = ?", req.Id)
currentMenus, err := l.svcCtx.AdminRoleMenuModel.FindAll(ctx, builder, "id ASC")
if err != nil {
return err
}
// 2. 转换为map便于查找
currentMenuMap := make(map[int64]*model.AdminRoleMenu)
for _, menu := range currentMenus {
currentMenuMap[menu.MenuId] = menu
}
// 3. 检查新的菜单ID是否存在
for _, menuId := range req.MenuIds {
exists, err := l.svcCtx.AdminMenuModel.FindOne(ctx, menuId)
if err != nil || exists == nil {
return errors.Wrapf(xerr.NewErrMsg("菜单不存在"), "菜单ID: %d", menuId)
}
}
// 4. 找出需要删除和新增的关联
var toDelete []*model.AdminRoleMenu
var toInsert []int64
// 需要删除的:当前存在但新列表中没有的
for menuId, roleMenu := range currentMenuMap {
if !lo.Contains(req.MenuIds, menuId) {
toDelete = append(toDelete, roleMenu)
}
}
// 需要新增的:新列表中有但当前不存在的
for _, menuId := range req.MenuIds {
if _, exists := currentMenuMap[menuId]; !exists {
toInsert = append(toInsert, menuId)
}
}
// 5. 删除需要移除的关联
for _, roleMenu := range toDelete {
err = l.svcCtx.AdminRoleMenuModel.Delete(ctx, session, roleMenu.Id)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除角色菜单关联失败: %v", err)
}
}
// 6. 添加新的关联
for _, menuId := range toInsert {
roleMenu := &model.AdminRoleMenu{
RoleId: req.Id,
MenuId: menuId,
}
_, err = l.svcCtx.AdminRoleMenuModel.Insert(ctx, session, roleMenu)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "添加角色菜单关联失败: %v", err)
}
}
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新角色失败err: %v", err)
}
return &types.UpdateRoleResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,88 @@
package admin_user
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminCreateUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateUserLogic {
return &AdminCreateUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminCreateUserLogic) AdminCreateUser(req *types.AdminCreateUserReq) (resp *types.AdminCreateUserResp, err error) {
// 检查用户名是否已存在
exists, err := l.svcCtx.AdminUserModel.FindOneByUsername(l.ctx, req.Username)
if err != nil && err != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
}
if exists != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("用户名已存在"), "创建用户失败")
}
password, err := crypto.PasswordHash("123456")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "创建用户失败, 加密密码失败: %v", err)
}
// 创建用户
user := &model.AdminUser{
Username: req.Username,
Password: password, // 注意:实际应用中需要加密密码
RealName: req.RealName,
Status: req.Status,
}
// 使用事务创建用户和关联角色
err = l.svcCtx.AdminUserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建用户
result, err := l.svcCtx.AdminUserModel.Insert(ctx, session, user)
if err != nil {
return err
}
userId, err := result.LastInsertId()
if err != nil {
return err
}
// 创建用户角色关联
if len(req.RoleIds) > 0 {
for _, roleId := range req.RoleIds {
userRole := &model.AdminUserRole{
UserId: userId,
RoleId: roleId,
}
_, err = l.svcCtx.AdminUserRoleModel.Insert(ctx, session, userRole)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建用户失败: %v", err)
}
return &types.AdminCreateUserResp{
Id: user.Id,
}, nil
}

View File

@@ -0,0 +1,68 @@
package admin_user
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminDeleteUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminDeleteUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminDeleteUserLogic {
return &AdminDeleteUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminDeleteUserLogic) AdminDeleteUser(req *types.AdminDeleteUserReq) (resp *types.AdminDeleteUserResp, err error) {
// 检查用户是否存在
_, err = l.svcCtx.AdminUserModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %v", err)
}
// 使用事务删除用户和关联数据
err = l.svcCtx.AdminUserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 删除用户角色关联
builder := l.svcCtx.AdminUserRoleModel.SelectBuilder().
Where("user_id = ?", req.Id)
roles, err := l.svcCtx.AdminUserRoleModel.FindAll(ctx, builder, "id ASC")
if err != nil {
return err
}
for _, role := range roles {
err = l.svcCtx.AdminUserRoleModel.Delete(ctx, session, role.Id)
if err != nil {
return err
}
}
// 删除用户
err = l.svcCtx.AdminUserModel.Delete(ctx, session, req.Id)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除用户失败: %v", err)
}
return &types.AdminDeleteUserResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,88 @@
package admin_user
import (
"context"
"errors"
"sync"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetUserDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetUserDetailLogic {
return &AdminGetUserDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetUserDetailLogic) AdminGetUserDetail(req *types.AdminGetUserDetailReq) (resp *types.AdminGetUserDetailResp, err error) {
// 使用MapReduceVoid并发获取用户信息和角色ID
var user *model.AdminUser
var roleIds []int64
var mutex sync.Mutex
var wg sync.WaitGroup
mr.MapReduceVoid(func(source chan<- interface{}) {
source <- 1 // 获取用户信息
source <- 2 // 获取角色ID
}, func(item interface{}, writer mr.Writer[interface{}], cancel func(error)) {
taskType := item.(int)
wg.Add(1)
defer wg.Done()
if taskType == 1 {
result, err := l.svcCtx.AdminUserModel.FindOne(l.ctx, req.Id)
if err != nil {
cancel(err)
return
}
mutex.Lock()
user = result
mutex.Unlock()
} else if taskType == 2 {
builder := l.svcCtx.AdminUserRoleModel.SelectBuilder().
Where("user_id = ?", req.Id)
roles, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
cancel(err)
return
}
mutex.Lock()
roleIds = lo.Map(roles, func(item *model.AdminUserRole, _ int) int64 {
return item.RoleId
})
mutex.Unlock()
}
}, func(pipe <-chan interface{}, cancel func(error)) {
// 不需要处理pipe中的数据
})
wg.Wait()
if user == nil {
return nil, errors.New("用户不存在")
}
return &types.AdminGetUserDetailResp{
Id: user.Id,
Username: user.Username,
RealName: user.RealName,
Status: user.Status,
CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
UpdateTime: user.UpdateTime.Format("2006-01-02 15:04:05"),
RoleIds: roleIds,
}, nil
}

View File

@@ -0,0 +1,149 @@
package admin_user
import (
"context"
"sync"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mr"
)
type AdminGetUserListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminGetUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetUserListLogic {
return &AdminGetUserListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminGetUserListLogic) AdminGetUserList(req *types.AdminGetUserListReq) (resp *types.AdminGetUserListResp, err error) {
resp = &types.AdminGetUserListResp{
Items: make([]types.AdminUserListItem, 0),
Total: 0,
}
// 构建查询条件
builder := l.svcCtx.AdminUserModel.SelectBuilder().
Where("del_state = ?", 0)
if len(req.Username) > 0 {
builder = builder.Where("username LIKE ?", "%"+req.Username+"%")
}
if len(req.RealName) > 0 {
builder = builder.Where("real_name LIKE ?", "%"+req.RealName+"%")
}
if req.Status != -1 {
builder = builder.Where("status = ?", req.Status)
}
// 设置分页
offset := (req.Page - 1) * req.PageSize
builder = builder.OrderBy("id DESC").Limit(uint64(req.PageSize)).Offset(uint64(offset))
// 使用MapReduceVoid并发获取总数和列表数据
var users []*model.AdminUser
var total int64
var mutex sync.Mutex
var wg sync.WaitGroup
mr.MapReduceVoid(func(source chan<- interface{}) {
source <- 1 // 获取用户列表
source <- 2 // 获取总数
}, func(item interface{}, writer mr.Writer[*model.AdminUser], cancel func(error)) {
taskType := item.(int)
wg.Add(1)
defer wg.Done()
if taskType == 1 {
result, err := l.svcCtx.AdminUserModel.FindAll(l.ctx, builder, "id DESC")
if err != nil {
cancel(err)
return
}
mutex.Lock()
users = result
mutex.Unlock()
} else if taskType == 2 {
countBuilder := l.svcCtx.AdminUserModel.SelectBuilder().
Where("del_state = ?", 0)
if len(req.Username) > 0 {
countBuilder = countBuilder.Where("username LIKE ?", "%"+req.Username+"%")
}
if len(req.RealName) > 0 {
countBuilder = countBuilder.Where("real_name LIKE ?", "%"+req.RealName+"%")
}
if req.Status != -1 {
countBuilder = countBuilder.Where("status = ?", req.Status)
}
count, err := l.svcCtx.AdminUserModel.FindCount(l.ctx, countBuilder, "id")
if err != nil {
cancel(err)
return
}
mutex.Lock()
total = count
mutex.Unlock()
}
}, func(pipe <-chan *model.AdminUser, cancel func(error)) {
// 不需要处理pipe中的数据
})
wg.Wait()
// 并发获取每个用户的角色ID
var userItems []types.AdminUserListItem
var userItemsMutex sync.Mutex
mr.MapReduceVoid(func(source chan<- interface{}) {
for _, user := range users {
source <- user
}
}, func(item interface{}, writer mr.Writer[[]int64], cancel func(error)) {
user := item.(*model.AdminUser)
// 获取用户关联的角色ID
builder := l.svcCtx.AdminUserRoleModel.SelectBuilder().
Where("user_id = ?", user.Id)
roles, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, builder, "id ASC")
if err != nil {
cancel(err)
return
}
roleIds := lo.Map(roles, func(item *model.AdminUserRole, _ int) int64 {
return item.RoleId
})
writer.Write(roleIds)
}, func(pipe <-chan []int64, cancel func(error)) {
for _, user := range users {
roleIds := <-pipe
item := types.AdminUserListItem{
Id: user.Id,
Username: user.Username,
RealName: user.RealName,
Status: user.Status,
CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
RoleIds: roleIds,
}
userItemsMutex.Lock()
userItems = append(userItems, item)
userItemsMutex.Unlock()
}
})
resp.Items = userItems
resp.Total = total
return resp, nil
}

View File

@@ -0,0 +1,141 @@
package admin_user
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type AdminUpdateUserLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUpdateUserLogic {
return &AdminUpdateUserLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUpdateUserLogic) AdminUpdateUser(req *types.AdminUpdateUserReq) (resp *types.AdminUpdateUserResp, err error) {
// 检查用户是否存在
user, err := l.svcCtx.AdminUserModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户不存在: %v", err)
}
// 检查用户名是否重复
if req.Username != nil && *req.Username != user.Username {
exists, err := l.svcCtx.AdminUserModel.FindOneByUsername(l.ctx, *req.Username)
if err != nil && err != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新用户失败: %v", err)
}
if exists != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("用户名已存在"), "更新用户失败")
}
}
// 更新用户信息
if req.Username != nil {
user.Username = *req.Username
}
if req.RealName != nil {
user.RealName = *req.RealName
}
if req.Status != nil {
user.Status = *req.Status
}
// 使用事务更新用户和关联角色
err = l.svcCtx.AdminUserModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 更新用户
_, err = l.svcCtx.AdminUserModel.Update(ctx, session, user)
if err != nil {
return err
}
// 只有当RoleIds不为nil时才更新角色关联
if req.RoleIds != nil {
// 1. 获取当前关联的角色ID
builder := l.svcCtx.AdminUserRoleModel.SelectBuilder().
Where("user_id = ?", req.Id)
currentRoles, err := l.svcCtx.AdminUserRoleModel.FindAll(ctx, builder, "id ASC")
if err != nil {
return err
}
// 2. 转换为map便于查找
currentRoleMap := make(map[int64]*model.AdminUserRole)
for _, role := range currentRoles {
currentRoleMap[role.RoleId] = role
}
// 3. 检查新的角色ID是否存在
for _, roleId := range req.RoleIds {
exists, err := l.svcCtx.AdminRoleModel.FindOne(ctx, roleId)
if err != nil || exists == nil {
return errors.Wrapf(xerr.NewErrMsg("角色不存在"), "角色ID: %d", roleId)
}
}
// 4. 找出需要删除和新增的关联
var toDelete []*model.AdminUserRole
var toInsert []int64
// 需要删除的:当前存在但新列表中没有的
for roleId, userRole := range currentRoleMap {
if !lo.Contains(req.RoleIds, roleId) {
toDelete = append(toDelete, userRole)
}
}
// 需要新增的:新列表中有但当前不存在的
for _, roleId := range req.RoleIds {
if _, exists := currentRoleMap[roleId]; !exists {
toInsert = append(toInsert, roleId)
}
}
// 5. 删除需要移除的关联
for _, userRole := range toDelete {
err = l.svcCtx.AdminUserRoleModel.Delete(ctx, session, userRole.Id)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除用户角色关联失败: %v", err)
}
}
// 6. 添加新的关联
for _, roleId := range toInsert {
userRole := &model.AdminUserRole{
UserId: req.Id,
RoleId: roleId,
}
_, err = l.svcCtx.AdminUserRoleModel.Insert(ctx, session, userRole)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "添加用户角色关联失败: %v", err)
}
}
}
return nil
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新用户失败: %v", err)
}
return &types.AdminUpdateUserResp{
Success: true,
}, nil
}

View File

@@ -0,0 +1,67 @@
package admin_user
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AdminUserInfoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAdminUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserInfoLogic {
return &AdminUserInfoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AdminUserInfoLogic) AdminUserInfo(req *types.AdminUserInfoReq) (resp *types.AdminUserInfoResp, err error) {
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败, %+v", err)
}
user, err := l.svcCtx.AdminUserModel.FindOne(l.ctx, userId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID信息失败, %+v", err)
}
// 获取权限
adminUserRoleBuilder := l.svcCtx.AdminUserRoleModel.SelectBuilder().Where(squirrel.Eq{"user_id": user.Id})
permissions, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, adminUserRoleBuilder, "role_id DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrMsg("获取权限失败"), "用户登录, 获取权限失败, 用户名: %s", user.Username)
}
// 获取角色ID数组
roleIds := make([]int64, 0)
for _, permission := range permissions {
roleIds = append(roleIds, permission.RoleId)
}
// 获取角色名称
roles := make([]string, 0)
for _, roleId := range roleIds {
role, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, roleId)
if err != nil {
continue
}
roles = append(roles, role.RoleCode)
}
return &types.AdminUserInfoResp{
Username: user.Username,
RealName: user.RealName,
Roles: roles,
}, nil
}

View File

@@ -0,0 +1,31 @@
package app
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetAppVersionLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetAppVersionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAppVersionLogic {
return &GetAppVersionLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetAppVersionLogic) GetAppVersion() (resp *types.GetAppVersionResp, err error) {
return &types.GetAppVersionResp{
Version: "1.0.0",
WgtUrl: "https://www.quannengcha.com/app_version/qnc_1.0.0.wgt",
}, nil
}

View File

@@ -0,0 +1,31 @@
package app
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type HealthCheckLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewHealthCheckLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HealthCheckLogic {
return &HealthCheckLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *HealthCheckLogic) HealthCheck() (resp *types.HealthCheckResp, err error) {
return &types.HealthCheckResp{
Status: "UP",
Message: "Service is healthy HahaHa",
}, nil
}

View File

@@ -0,0 +1,105 @@
package auth
import (
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"context"
"fmt"
"math/rand"
"time"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
"github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"github.com/zeromicro/go-zero/core/logx"
)
type SendSmsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
return &SendSmsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SendSmsLogic) SendSms(req *types.SendSmsReq) error {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 加密手机号失败: %v", err)
}
// 检查手机号是否在一分钟内已发送过验证码
limitCodeKey := fmt.Sprintf("limit:%s:%s", req.ActionType, encryptedMobile)
exists, err := l.svcCtx.Redis.Exists(limitCodeKey)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 读取redis缓存失败: %s", encryptedMobile)
}
if exists {
// 如果 Redis 中已经存在标记,说明在 1 分钟内请求过,返回错误
return errors.Wrapf(xerr.NewErrMsg("一分钟内不能重复发送验证码"), "短信发送, 手机号1分钟内重复请求发送验证码: %s", encryptedMobile)
}
code := fmt.Sprintf("%06d", rand.New(rand.NewSource(time.Now().UnixNano())).Intn(1000000))
// 发送短信
smsResp, err := l.sendSmsRequest(req.Mobile, code)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 调用阿里客户端失败: %v", err)
}
if *smsResp.Body.Code != "OK" {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 阿里客户端响应失败: %s", *smsResp.Body.Message)
}
codeKey := fmt.Sprintf("%s:%s", req.ActionType, encryptedMobile)
// 将验证码保存到 Redis设置过期时间
err = l.svcCtx.Redis.Setex(codeKey, code, l.svcCtx.Config.VerifyCode.ValidTime) // 验证码有效期5分钟
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 验证码设置过期时间失败: %v", err)
}
// 在 Redis 中设置 1 分钟的标记,限制重复请求
err = l.svcCtx.Redis.Setex(limitCodeKey, code, 60) // 标记 1 分钟内不能重复请求
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "短信发送, 验证码设置限制重复请求失败: %v", err)
}
return nil
}
// CreateClient 创建阿里云短信客户端
func (l *SendSmsLogic) CreateClient() (*dysmsapi.Client, error) {
config := &openapi.Config{
AccessKeyId: &l.svcCtx.Config.VerifyCode.AccessKeyID,
AccessKeySecret: &l.svcCtx.Config.VerifyCode.AccessKeySecret,
}
config.Endpoint = tea.String(l.svcCtx.Config.VerifyCode.EndpointURL)
return dysmsapi.NewClient(config)
}
// sendSmsRequest 发送短信请求
func (l *SendSmsLogic) sendSmsRequest(mobile, code string) (*dysmsapi.SendSmsResponse, error) {
// 初始化阿里云短信客户端
cli, err := l.CreateClient()
if err != nil {
return nil, err
}
request := &dysmsapi.SendSmsRequest{
SignName: tea.String(l.svcCtx.Config.VerifyCode.SignName),
TemplateCode: tea.String(l.svcCtx.Config.VerifyCode.TemplateCode),
PhoneNumbers: tea.String(mobile),
TemplateParam: tea.String(fmt.Sprintf("{\"code\":\"%s\"}", code)),
}
runtime := &service.RuntimeOptions{}
return cli.SendSmsWithOptions(request, runtime)
}

View File

@@ -0,0 +1,57 @@
package notification
import (
"aedata-server/common/xerr"
"context"
"time"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetNotificationsLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetNotificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetNotificationsLogic {
return &GetNotificationsLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetNotificationsLogic) GetNotifications() (resp *types.GetNotificationsResp, err error) {
// 获取今天的日期
now := time.Now()
// 获取开始和结束日期的时间戳
todayStart := now.Format("2006-01-02") + " 00:00:00"
todayEnd := now.Format("2006-01-02") + " 23:59:59"
// 构建查询条件
builder := l.svcCtx.GlobalNotificationsModel.SelectBuilder().
Where("status = ?", "active").
Where("(start_date IS NULL OR start_date <= ?)", todayEnd). // start_date 是 NULL 或者小于等于今天结束时间
Where("(end_date IS NULL OR end_date >= ?)", todayStart) // end_date 是 NULL 或者大于等于今天开始时间
notificationsModelList, findErr := l.svcCtx.GlobalNotificationsModel.FindAll(l.ctx, builder, "")
if findErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "全局通知, 查找通知失败, err:%+v", findErr)
}
var notifications []types.Notification
copyErr := copier.Copy(&notifications, &notificationsModelList)
if copyErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "全局通知, 复制结构体失败, err:%+v", copyErr)
}
return &types.GetNotificationsResp{Notifications: notifications}, nil
}

View File

@@ -0,0 +1,93 @@
package pay
import (
"aedata-server/pkg/lzkit/lzUtils"
"context"
"net/http"
"time"
"github.com/smartwalle/alipay/v3"
"aedata-server/app/main/api/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type AlipayCallbackLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAlipayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AlipayCallbackLogic {
return &AlipayCallbackLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Request) error {
notification, err := l.svcCtx.AlipayService.HandleAliPaymentNotification(r)
if err != nil {
logx.Errorf("支付宝支付回调,%v", err)
return nil
}
// 查询订单处理
return l.handleQueryOrderPayment(w, notification)
}
// 处理查询订单支付
func (l *AlipayCallbackLogic) handleQueryOrderPayment(w http.ResponseWriter, notification *alipay.Notification) error {
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, notification.OutTradeNo)
if findOrderErr != nil {
logx.Errorf("支付宝支付回调,查找订单失败: %+v", findOrderErr)
return nil
}
if order.Status != "pending" {
alipay.ACKNotification(w)
return nil
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, order.UserId)
if err != nil {
logx.Errorf("支付宝支付回调,查找用户失败: %+v", err)
return nil
}
amount := lzUtils.ToAlipayAmount(order.Amount)
if user.Inside != 1 {
// 确保订单金额和状态正确,防止重复更新
if amount != notification.TotalAmount {
logx.Errorf("支付宝支付回调,金额不一致")
return nil
}
}
switch notification.TradeStatus {
case alipay.TradeStatusSuccess:
order.Status = "paid"
order.PayTime = lzUtils.TimeToNullTime(time.Now())
default:
return nil
}
order.PlatformOrderId = lzUtils.StringToNullString(notification.TradeNo)
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
logx.Errorf("支付宝支付回调,修改订单信息失败: %+v", updateErr)
return nil
}
if order.Status == "paid" {
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
logx.Errorf("异步任务调度失败: %v", asyncErr)
return asyncErr
}
}
alipay.ACKNotification(w)
return nil
}

View File

@@ -0,0 +1,82 @@
package pay
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/lzUtils"
"context"
"time"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type IapCallbackLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewIapCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IapCallbackLogic {
return &IapCallbackLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *IapCallbackLogic) IapCallback(req *types.IapCallbackReq) error {
// Step 1: 查找订单
order, findOrderErr := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderID)
if findOrderErr != nil {
logx.Errorf("苹果内购支付回调,查找订单失败: %+v", findOrderErr)
return nil
}
// Step 2: 验证订单状态
if order.Status != "pending" {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 订单状态异常: %+v", order)
}
// Step 3: 调用 VerifyReceipt 验证苹果支付凭证
//receipt := req.TransactionReceipt // 从请求中获取支付凭证
//verifyResponse, verifyErr := l.svcCtx.ApplePayService.VerifyReceipt(l.ctx, receipt)
//if verifyErr != nil {
// return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 验证订单异常: %+v", verifyErr)
//}
// Step 4: 验证订单
//product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, order.Id)
//if findProductErr != nil {
// return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "苹果内购支付回调, 获取订单相关商品失败: %+v", findProductErr)
//}
//isProductMatched := false
//appleProductID := l.svcCtx.ApplePayService.GetIappayAppID(product.ProductEn)
//for _, item := range verifyResponse.Receipt.InApp {
// if item.ProductID == appleProductID {
// isProductMatched = true
// order.PlatformOrderId = lzUtils.StringToNullString(item.TransactionID) // 记录交易 ID
// break
// }
//}
//if !isProductMatched {
// return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 商品 ID 不匹配,订单 ID: %d, 回调苹果商品 ID: %s", order.Id, verifyResponse.Receipt.InApp[0].ProductID)
//}
// Step 5: 更新订单状态 mm
order.Status = "paid"
order.PayTime = lzUtils.TimeToNullTime(time.Now())
// 更新订单到数据库
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调, 修改订单信息失败: %+v", updateErr)
}
// Step 6: 处理订单完成后的逻辑
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "苹果内购支付回调,异步任务调度失败: %v", asyncErr)
}
return nil
}

View File

@@ -0,0 +1,37 @@
package pay
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type PaymentCheckLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewPaymentCheckLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentCheckLogic {
return &PaymentCheckLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *PaymentCheckLogic) PaymentCheck(req *types.PaymentCheckReq) (resp *types.PaymentCheckResp, err error) {
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询订单失败: %v", err)
}
return &types.PaymentCheckResp{
Type: "query",
Status: order.Status,
}, nil
}

View File

@@ -0,0 +1,122 @@
package pay
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/redis/go-redis/v9"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type PaymentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
type PaymentTypeResp struct {
amount float64
outTradeNo string
description string
}
func NewPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentLogic {
return &PaymentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *PaymentLogic) Payment(req *types.PaymentReq) (resp *types.PaymentResp, err error) {
var paymentTypeResp *PaymentTypeResp
var prepayData interface{}
l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
switch req.PayType {
case "query":
paymentTypeResp, err = l.QueryOrderPayment(req, session)
if err != nil {
return err
}
}
var createOrderErr error
if req.PayMethod == "wechat" {
prepayData, createOrderErr = l.svcCtx.WechatPayService.CreateWechatOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
} else if req.PayMethod == "alipay" {
prepayData, createOrderErr = l.svcCtx.AlipayService.CreateAlipayOrder(l.ctx, paymentTypeResp.amount, paymentTypeResp.description, paymentTypeResp.outTradeNo)
}
if createOrderErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 创建支付订单失败: %+v", createOrderErr)
}
return nil
})
if err != nil {
return nil, err
}
switch v := prepayData.(type) {
case string:
// 如果 prepayData 是字符串类型,直接返回
return &types.PaymentResp{PrepayId: v, OrderNo: paymentTypeResp.outTradeNo}, nil
default:
return &types.PaymentResp{PrepayData: prepayData, OrderNo: paymentTypeResp.outTradeNo}, nil
}
}
func (l *PaymentLogic) QueryOrderPayment(req *types.PaymentReq, session sqlx.Session) (resp *PaymentTypeResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取用户信息失败, %+v", getUidErr)
}
outTradeNo := req.Id
redisKey := fmt.Sprintf(types.QueryCacheKey, userID, outTradeNo)
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
if cacheErr != nil {
if cacheErr == redis.Nil {
return nil, errors.Wrapf(xerr.NewErrMsg("订单已过期"), "生成订单, 缓存不存在, %+v", cacheErr)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 获取缓存失败, %+v", cacheErr)
}
var data types.QueryCacheLoad
err = json.Unmarshal([]byte(cache), &data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 解析缓存内容失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成订单, 查找产品错误: %v", err)
}
var amount float64
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 获取用户信息失败: %v", err)
}
if user.Inside == 1 {
amount = 0.01
}
order := model.Order{
OrderNo: outTradeNo,
UserId: userID,
ProductId: product.Id,
PaymentPlatform: req.PayMethod,
PaymentScene: "app",
Amount: amount,
Status: "pending",
}
_, insertOrderErr := l.svcCtx.OrderModel.Insert(l.ctx, session, &order)
if insertOrderErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "生成订单, 保存订单失败: %+v", insertOrderErr)
}
return &PaymentTypeResp{amount: amount, outTradeNo: outTradeNo, description: product.ProductName}, nil
}

View File

@@ -0,0 +1,90 @@
package pay
import (
"aedata-server/app/main/api/internal/service"
"aedata-server/pkg/lzkit/lzUtils"
"context"
"net/http"
"time"
"aedata-server/app/main/api/internal/svc"
"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
"github.com/zeromicro/go-zero/core/logx"
)
type WechatPayCallbackLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWechatPayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatPayCallbackLogic {
return &WechatPayCallbackLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WechatPayCallbackLogic) WechatPayCallback(w http.ResponseWriter, r *http.Request) error {
notification, err := l.svcCtx.WechatPayService.HandleWechatPayNotification(l.ctx, r)
if err != nil {
logx.Errorf("微信支付回调,%v", err)
return nil
}
// 兼容旧订单,假设没有前缀的是查询订单
return l.handleQueryOrderPayment(w, notification)
}
// 处理查询订单支付
func (l *WechatPayCallbackLogic) handleQueryOrderPayment(w http.ResponseWriter, notification *payments.Transaction) error {
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
if findOrderErr != nil {
logx.Errorf("微信支付回调,查找订单信息失败: %+v", findOrderErr)
return nil
}
amount := lzUtils.ToWechatAmount(order.Amount)
if amount != *notification.Amount.Total {
logx.Errorf("微信支付回调,金额不一致")
return nil
}
if order.Status != "pending" {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("success"))
return nil
}
switch *notification.TradeState {
case service.TradeStateSuccess:
order.Status = "paid"
order.PayTime = lzUtils.TimeToNullTime(time.Now())
case service.TradeStateClosed:
order.Status = "closed"
order.CloseTime = lzUtils.TimeToNullTime(time.Now())
case service.TradeStateRevoked:
order.Status = "failed"
default:
return nil
}
order.PlatformOrderId = lzUtils.StringToNullString(*notification.TransactionId)
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
logx.Errorf("微信支付回调,更新订单失败%+v", updateErr)
return nil
}
if order.Status == "paid" {
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(order.Id); asyncErr != nil {
logx.Errorf("异步任务调度失败: %v", asyncErr)
return asyncErr
}
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("success"))
return nil
}

View File

@@ -0,0 +1,55 @@
package pay
import (
"aedata-server/app/main/api/internal/svc"
"context"
"net/http"
"github.com/wechatpay-apiv3/wechatpay-go/services/refunddomestic"
"github.com/zeromicro/go-zero/core/logx"
)
type WechatPayRefundCallbackLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWechatPayRefundCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatPayRefundCallbackLogic {
return &WechatPayRefundCallbackLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WechatPayRefundCallbackLogic) WechatPayRefundCallback(w http.ResponseWriter, r *http.Request) error {
notification, err := l.svcCtx.WechatPayService.HandleRefundNotification(l.ctx, r)
if err != nil {
logx.Errorf("微信退款回调,%v", err)
return nil
}
order, findOrderErr := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *notification.OutTradeNo)
if findOrderErr != nil {
logx.Errorf("微信退款回调,查找订单信息失败: %+v", findOrderErr)
return nil
}
switch *notification.Status {
case refunddomestic.STATUS_SUCCESS:
order.Status = "refunded"
case refunddomestic.STATUS_ABNORMAL:
// 异常
return nil
default:
return nil
}
if updateErr := l.svcCtx.OrderModel.UpdateWithVersion(l.ctx, nil, order); updateErr != nil {
logx.Errorf("微信退款回调,更新订单失败%+v", updateErr)
return nil
}
// 响应微信回调成功
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("success")) // 确保只写入一次响应
return nil
}

View File

@@ -0,0 +1,75 @@
package product
import (
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/mr"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetProductAppByEnLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductAppByEnLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductAppByEnLogic {
return &GetProductAppByEnLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetProductAppByEnLogic) GetProductAppByEn(req *types.GetProductByEnRequest) (resp *types.ProductResponse, err error) {
productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.ProductEn)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品错误: %v", err)
}
build := l.svcCtx.ProductFeatureModel.SelectBuilder().Where(squirrel.Eq{
"product_id": productModel.Id,
})
productFeatureAll, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, build, "")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品关联错误: %v", err)
}
var product types.Product
err = copier.Copy(&product, productModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
}
mr.MapReduceVoid(func(source chan<- interface{}) {
for _, productFeature := range productFeatureAll {
source <- productFeature.FeatureId
}
}, func(item interface{}, writer mr.Writer[*model.Feature], cancel func(error)) {
id := item.(int64)
feature, findFeatureErr := l.svcCtx.FeatureModel.FindOne(l.ctx, id)
if findFeatureErr != nil {
logx.WithContext(l.ctx).Errorf("产品查询, 查找关联feature错误: %d, err:%v", id, findFeatureErr)
return
}
if feature != nil && feature.Id > 0 {
writer.Write(feature)
}
}, func(pipe <-chan *model.Feature, cancel func(error)) {
for item := range pipe {
var feature types.Feature
_ = copier.Copy(&feature, item)
product.Features = append(product.Features, feature)
}
})
return &types.ProductResponse{Product: product}, nil
}

View File

@@ -0,0 +1,75 @@
package product
import (
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/mr"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetProductByEnLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductByEnLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductByEnLogic {
return &GetProductByEnLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetProductByEnLogic) GetProductByEn(req *types.GetProductByEnRequest) (resp *types.ProductResponse, err error) {
productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.ProductEn)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品错误: %v", err)
}
build := l.svcCtx.ProductFeatureModel.SelectBuilder().Where(squirrel.Eq{
"product_id": productModel.Id,
})
productFeatureAll, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, build, "")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品关联错误: %v", err)
}
var product types.Product
err = copier.Copy(&product, productModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
}
mr.MapReduceVoid(func(source chan<- interface{}) {
for _, productFeature := range productFeatureAll {
source <- productFeature.FeatureId
}
}, func(item interface{}, writer mr.Writer[*model.Feature], cancel func(error)) {
id := item.(int64)
feature, findFeatureErr := l.svcCtx.FeatureModel.FindOne(l.ctx, id)
if findFeatureErr != nil {
logx.WithContext(l.ctx).Errorf("产品查询, 查找关联feature错误: %d, err:%v", id, findFeatureErr)
return
}
if feature != nil && feature.Id > 0 {
writer.Write(feature)
}
}, func(pipe <-chan *model.Feature, cancel func(error)) {
for item := range pipe {
var feature types.Feature
_ = copier.Copy(&feature, item)
product.Features = append(product.Features, feature)
}
})
return &types.ProductResponse{Product: product}, nil
}

View File

@@ -0,0 +1,30 @@
package product
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetProductByIDLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductByIDLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductByIDLogic {
return &GetProductByIDLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetProductByIDLogic) GetProductByID(req *types.GetProductByIDRequest) (resp *types.ProductResponse, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,213 @@
package query
import (
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"aedata-server/pkg/lzkit/lzUtils"
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryDetailByOrderIdLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryDetailByOrderIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDetailByOrderIdLogic {
return &QueryDetailByOrderIdLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryDetailByOrderIdLogic) QueryDetailByOrderId(req *types.QueryDetailByOrderIdReq) (resp *types.QueryDetailByOrderIdResp, err error) {
// 获取当前用户ID
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找用户错误: %v", err)
}
if user.Inside != 1 {
// 安全验证:确保订单属于当前用户
if order.UserId != userId {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
}
}
// 检查订单状态
if order.Status != "paid" {
return nil, errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
// 获取报告信息
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, req.OrderId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
var query types.Query
query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
// 解密查询数据
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", err)
}
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
if updateFeatureAndProductFeatureErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
}
// 复制报告数据
err = copier.Copy(&query, queryModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.ProductName = product.ProductName
return &types.QueryDetailByOrderIdResp{
Query: query,
}, nil
}
// ProcessQueryData 解密和反序列化 QueryData
func ProcessQueryData(queryData sql.NullString, target *[]types.QueryItem, key []byte) error {
queryDataStr := lzUtils.NullStringToString(queryData)
if queryDataStr == "" {
return nil
}
// 解密数据
decryptedData, decryptErr := crypto.AesDecrypt(queryDataStr, key)
if decryptErr != nil {
return decryptErr
}
// 解析 JSON 数组
var decryptedArray []map[string]interface{}
unmarshalErr := json.Unmarshal(decryptedData, &decryptedArray)
if unmarshalErr != nil {
return unmarshalErr
}
// 确保 target 具有正确的长度
if len(*target) == 0 {
*target = make([]types.QueryItem, len(decryptedArray))
}
// 填充解密后的数据到 target
for i := 0; i < len(decryptedArray); i++ {
// 直接填充解密数据到 Data 字段
(*target)[i].Data = decryptedArray[i]
}
return nil
}
func (l *QueryDetailByOrderIdLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.QueryItem) error {
// 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
for i := len(*target) - 1; i >= 0; i-- {
queryItem := &(*target)[i]
// 确保 Data 为 map 类型
data, ok := queryItem.Data.(map[string]interface{})
if !ok {
return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
}
// 从 Data 中获取 apiID
apiID, ok := data["apiID"].(string)
if !ok {
return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
}
// 查询 Feature
feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
if err != nil {
// 如果 Feature 查不到,也要删除当前 QueryItem
*target = append((*target)[:i], (*target)[i+1:]...)
continue
}
// 查询 ProductFeatureModel
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
}
// 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
var featureData map[string]interface{}
// foundFeature := false
sort := 0
for _, pf := range productFeatures {
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{
"featureName": feature.Name,
"sort": sort,
}
// 更新 queryItem 的 Feature 字段(不是数组)
queryItem.Feature = featureData
}
return nil
}
// ProcessQueryParams解密和反序列化 QueryParams
func ProcessQueryParams(QueryParams string, target *map[string]interface{}, key []byte) error {
// 解密 QueryParams
decryptedData, decryptErr := crypto.AesDecrypt(QueryParams, key)
if decryptErr != nil {
return decryptErr
}
// 反序列化解密后的数据
unmarshalErr := json.Unmarshal(decryptedData, target)
if unmarshalErr != nil {
return unmarshalErr
}
return nil
}

View File

@@ -0,0 +1,155 @@
package query
import (
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"encoding/hex"
"fmt"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryDetailByOrderNoLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryDetailByOrderNoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryDetailByOrderNoLogic {
return &QueryDetailByOrderNoLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryDetailByOrderNoLogic) QueryDetailByOrderNo(req *types.QueryDetailByOrderNoReq) (resp *types.QueryDetailByOrderNoResp, err error) {
// 获取当前用户ID
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
// 安全验证:确保订单属于当前用户
if order.UserId != userId {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "无权查看此订单报告")
}
// 检查订单状态
if order.Status != "paid" {
return nil, errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
// 获取报告信息
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
var query types.Query
query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
// 解密查询数据
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", err)
}
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
if updateFeatureAndProductFeatureErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
}
// 复制报告数据
err = copier.Copy(&query, queryModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.ProductName = product.ProductName
return &types.QueryDetailByOrderNoResp{
Query: query,
}, nil
}
func (l *QueryDetailByOrderNoLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.QueryItem) error {
// 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
for i := len(*target) - 1; i >= 0; i-- {
queryItem := &(*target)[i]
// 确保 Data 为 map 类型
data, ok := queryItem.Data.(map[string]interface{})
if !ok {
return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
}
// 从 Data 中获取 apiID
apiID, ok := data["apiID"].(string)
if !ok {
return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
}
// 查询 Feature
feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
if err != nil {
// 如果 Feature 查不到,也要删除当前 QueryItem
*target = append((*target)[:i], (*target)[i+1:]...)
continue
}
// 查询 ProductFeatureModel
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
}
// 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
var featureData map[string]interface{}
// foundFeature := false
sort := 0
for _, pf := range productFeatures {
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{
"featureName": feature.Name,
"sort": sort,
}
// 更新 queryItem 的 Feature 字段(不是数组)
queryItem.Feature = featureData
}
return nil
}

View File

@@ -0,0 +1,152 @@
package query
// import (
// "context"
// "encoding/hex"
// "fmt"
// "aedata-server/app/main/api/internal/svc"
// "aedata-server/app/main/api/internal/types"
// "aedata-server/common/xerr"
// "github.com/jinzhu/copier"
// "github.com/pkg/errors"
// "github.com/zeromicro/go-zero/core/logx"
// )
// type QueryExampleLogic struct {
// logx.Logger
// ctx context.Context
// svcCtx *svc.ServiceContext
// }
// func NewQueryExampleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryExampleLogic {
// return &QueryExampleLogic{
// Logger: logx.WithContext(ctx),
// ctx: ctx,
// svcCtx: svcCtx,
// }
// }
// func (l *QueryExampleLogic) QueryExample(req *types.QueryExampleReq) (resp *types.QueryExampleResp, err error) {
// var exampleID int64
// switch req.Feature {
// case "backgroundcheck":
// exampleID = 508
// case "companyinfo":
// exampleID = 506
// case "homeservice":
// exampleID = 504
// case "marriage":
// exampleID = 501
// case "preloanbackgroundcheck":
// exampleID = 509
// case "rentalinfo":
// exampleID = 505
// case "riskassessment":
// exampleID = 503
// default:
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "示例报告, 获取示例报告失败: %v", err)
// }
// queryModel, err := l.svcCtx.QueryModel.FindOne(l.ctx, exampleID)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "示例报告, 获取示例报告失败: %v", err)
// }
// var query types.Query
// query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
// query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
// // 解密查询数据
// secretKey := l.svcCtx.Config.Encrypt.SecretKey
// key, decodeErr := hex.DecodeString(secretKey)
// if decodeErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取AES解密解药失败, %v", err)
// }
// processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
// if processParamsErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告参数处理失败: %v", processParamsErr)
// }
// processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
// if processErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告结果处理失败: %v", processErr)
// }
// updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
// if updateFeatureAndProductFeatureErr != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
// }
// // 复制报告数据
// err = copier.Copy(&query, queryModel)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 报告结构体复制失败, %v", err)
// }
// product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
// if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取商品信息失败, %v", err)
// }
// query.ProductName = product.ProductName
// return &types.QueryExampleResp{
// Query: query,
// }, nil
// }
// func (l *QueryExampleLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.QueryItem) error {
// // 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
// for i := len(*target) - 1; i >= 0; i-- {
// queryItem := &(*target)[i]
// // 确保 Data 为 map 类型
// data, ok := queryItem.Data.(map[string]interface{})
// if !ok {
// return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
// }
// // 从 Data 中获取 apiID
// apiID, ok := data["apiID"].(string)
// if !ok {
// return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
// }
// // 查询 Feature
// feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
// if err != nil {
// // 如果 Feature 查不到,也要删除当前 QueryItem
// *target = append((*target)[:i], (*target)[i+1:]...)
// continue
// }
// // 查询 ProductFeatureModel
// builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
// productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
// if err != nil {
// return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
// }
// // 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
// var featureData map[string]interface{}
// foundFeature := false
// for _, pf := range productFeatures {
// if pf.FeatureId == feature.Id { // 确保和 Feature 关联
// foundFeature = true
// if pf.Enable == 1 {
// featureData = map[string]interface{}{
// "featureName": feature.Name,
// "sort": pf.Sort,
// }
// break // 找到第一个符合条件的就退出循环
// }
// }
// }
// // 如果没有符合条件的 feature 或者 featureData 为空,则删除当前 queryItem
// if !foundFeature || featureData == nil {
// *target = append((*target)[:i], (*target)[i+1:]...)
// continue
// }
// // 更新 queryItem 的 Feature 字段(不是数组)
// queryItem.Feature = featureData
// }
// return nil
// }

View File

@@ -0,0 +1,110 @@
package query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"context"
"encoding/hex"
"github.com/bytedance/sonic"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryExampleLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryExampleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryExampleLogic {
return &QueryExampleLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryExampleLogic) QueryExample(req *types.QueryExampleReq) (resp *types.QueryExampleResp, err error) {
// 根据产品特性标识获取产品信息
product, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.Feature)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取商品信息失败, %v", err)
}
// 创建一个空的Query结构体来存储结果
query := types.Query{
ProductName: product.ProductName,
QueryData: make([]types.QueryItem, 0),
QueryParams: make(map[string]interface{}),
}
query.QueryParams = map[string]interface{}{
"id_card": "45000000000000000",
"mobile": "13700000000",
"name": "张老三",
}
// 查询ProductFeatureModel获取产品相关的功能列表
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", product.Id)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 查询 ProductFeatureModel 错误: %v", err)
}
// 从每个启用的特性获取示例数据并合并
for _, pf := range productFeatures {
if pf.Enable != 1 {
continue // 跳过未启用的特性
}
// 根据特性ID查找示例数据
example, err := l.svcCtx.ExampleModel.FindOneByFeatureId(l.ctx, pf.FeatureId)
if err != nil {
logx.Infof("示例报告, 特性ID %d 无示例数据: %v", pf.FeatureId, err)
continue // 如果没有示例数据就跳过
}
// 获取对应的Feature信息
feature, err := l.svcCtx.FeatureModel.FindOne(l.ctx, pf.FeatureId)
if err != nil {
logx.Infof("示例报告, 无法获取特性ID %d 的信息: %v", pf.FeatureId, err)
continue
}
var queryItem types.QueryItem
// 解密查询数据
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 获取AES解密解药失败, %v", err)
}
// 解析示例内容
if example.Content == "000" {
queryItem.Data = example.Content
} else {
// 解密数据
decryptedData, decryptErr := crypto.AesDecrypt(example.Content, key)
if decryptErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 解密数据失败: %v", decryptErr)
}
err = sonic.Unmarshal([]byte(decryptedData), &queryItem.Data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "示例报告, 解析示例内容失败: %v", err)
}
}
// 添加特性信息
queryItem.Feature = map[string]interface{}{
"featureName": feature.Name,
"sort": pf.Sort,
}
// 添加到查询数据中
query.QueryData = append(query.QueryData, queryItem)
}
return &types.QueryExampleResp{
Query: query,
}, nil
}

View File

@@ -0,0 +1,111 @@
package query
import (
"context"
"encoding/hex"
"encoding/json"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryGenerateShareLinkLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryGenerateShareLinkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryGenerateShareLinkLogic {
return &QueryGenerateShareLinkLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryGenerateShareLinkLogic) QueryGenerateShareLink(req *types.QueryGenerateShareLinkReq) (resp *types.QueryGenerateShareLinkResp, err error) {
userId, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户ID失败: %v", err)
}
// 检查参数
if (req.OrderId == nil || *req.OrderId == 0) && (req.OrderNo == nil || *req.OrderNo == "") {
return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
}
var order *model.Order
// 优先使用OrderId查询
if req.OrderId != nil && *req.OrderId != 0 {
order, err = l.svcCtx.OrderModel.FindOne(l.ctx, *req.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
}
} else if req.OrderNo != nil && *req.OrderNo != "" {
// 使用OrderNo查询
order, err = l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *req.OrderNo)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
}
} else {
return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
}
if order.Status != model.OrderStatusPaid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 订单未支付")
}
query, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取查询失败: %v", err)
}
if query.QueryState != model.QueryStateSuccess {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 查询未成功")
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户失败: %v", err)
}
if user.Inside != 1 {
if order.UserId != userId {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 无权操作此订单")
}
}
expireAt := time.Now().Add(time.Duration(l.svcCtx.Config.Query.ShareLinkExpire) * time.Second)
payload := types.QueryShareLinkPayload{
OrderId: order.Id, // 使用查询到的订单ID
ExpireAt: expireAt.Unix(),
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, err := hex.DecodeString(secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 解密失败: %v", err)
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 序列化失败: %v", err)
}
encryptedPayload, err := crypto.AesEncryptURL(payloadBytes, key)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 加密失败: %v", err)
}
return &types.QueryGenerateShareLinkResp{
ShareLink: encryptedPayload,
}, nil
}

View File

@@ -0,0 +1,70 @@
package query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"github.com/Masterminds/squirrel"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryListLogic {
return &QueryListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryListLogic) QueryList(req *types.QueryListReq) (resp *types.QueryListResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 获取用户信息失败, %+v", getUidErr)
}
// 直接构建查询query表的条件
build := l.svcCtx.QueryModel.SelectBuilder().Where(squirrel.Eq{
"user_id": userID,
})
// 直接从query表分页查询
queryList, total, err := l.svcCtx.QueryModel.FindPageListByPageWithTotal(l.ctx, build, req.Page, req.PageSize, "create_time DESC")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告列表查询, 查找报告列表错误, %+v", err)
}
var list []types.Query
if len(queryList) > 0 {
for _, queryModel := range queryList {
var query types.Query
query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
copyErr := copier.Copy(&query, queryModel)
if copyErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 报告结构体复制失败, %+v", err)
}
product, findProductErr := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if findProductErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告列表查询, 获取商品信息失败, %+v", err)
}
query.ProductName = product.ProductName
list = append(list, query)
}
}
return &types.QueryListResp{
Total: total,
List: list,
}, nil
}

View File

@@ -0,0 +1,63 @@
package query
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"encoding/json"
"fmt"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryProvisionalOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryProvisionalOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryProvisionalOrderLogic {
return &QueryProvisionalOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryProvisionalOrderLogic) QueryProvisionalOrder(req *types.QueryProvisionalOrderReq) (resp *types.QueryProvisionalOrderResp, err error) {
userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
if getUidErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 获取用户信息失败, %+v", getUidErr)
}
redisKey := fmt.Sprintf("%d:%s", userID, req.Id)
cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
if cacheErr != nil {
return nil, cacheErr
}
var data types.QueryCache
err = json.Unmarshal([]byte(cache), &data)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 解析缓存内容失败, %v", err)
}
productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 查找产品错误: %v", err)
}
var product types.Product
err = copier.Copy(&product, productModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 用户信息结构体复制失败: %v", err)
}
return &types.QueryProvisionalOrderResp{
Name: data.Name,
IdCard: data.Name,
Mobile: data.Mobile,
Product: product,
}, nil
}

View File

@@ -0,0 +1,44 @@
package query
import (
"aedata-server/common/xerr"
"context"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryRetryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryRetryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryRetryLogic {
return &QueryRetryLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryRetryLogic) QueryRetry(req *types.QueryRetryReq) (resp *types.QueryRetryResp, err error) {
query, err := l.svcCtx.QueryModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询重试, 查找报告失败, %v", err)
}
if query.QueryState == "success" {
return nil, errors.Wrapf(xerr.NewErrCodeMsg(xerr.LOGIN_FAILED, "该报告不能重试"), "报告查询重试, 该报告不能重试, %d", query.Id)
}
if asyncErr := l.svcCtx.AsynqService.SendQueryTask(query.OrderId); asyncErr != nil {
logx.Errorf("异步任务调度失败: %v", asyncErr)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询重试, 异步任务调度失败, %+v", asyncErr)
}
return
}

View File

@@ -0,0 +1,30 @@
package query
import (
"context"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryServiceAppLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryServiceAppLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryServiceAppLogic {
return &QueryServiceAppLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryServiceAppLogic) QueryServiceApp(req *types.QueryServiceReq) (resp *types.QueryServiceResp, err error) {
// todo: add your logic here and delete this line
return
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,164 @@
package query
import (
"context"
"encoding/hex"
"fmt"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/bytedance/sonic"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type QueryShareDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQueryShareDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryShareDetailLogic {
return &QueryShareDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QueryShareDetailLogic) QueryShareDetail(req *types.QueryShareDetailReq) (resp *types.QueryShareDetailResp, err error) {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取AES解密解药失败, %v", err)
}
decryptedID, decryptErr := crypto.AesDecryptURL(req.Id, key)
if decryptErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 解密数据失败: %v", decryptErr)
}
var payload types.QueryShareLinkPayload
err = sonic.Unmarshal(decryptedID, &payload)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 解密数据失败: %v", err)
}
// 检查分享链接是否过期
now := time.Now().Unix()
if now > payload.ExpireAt {
return &types.QueryShareDetailResp{
Status: "expired",
}, nil
}
// 获取订单信息
order, err := l.svcCtx.OrderModel.FindOne(l.ctx, payload.OrderId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.LOGIC_QUERY_NOT_FOUND), "报告查询, 订单不存在: %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
// 检查订单状态
if order.Status != "paid" {
return nil, errors.Wrapf(xerr.NewErrMsg("订单未支付,无法查看报告"), "")
}
// 获取报告信息
queryModel, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "报告查询, 查找报告错误: %v", err)
}
var query types.Query
query.CreateTime = queryModel.CreateTime.Format("2006-01-02 15:04:05")
query.UpdateTime = queryModel.UpdateTime.Format("2006-01-02 15:04:05")
processParamsErr := ProcessQueryParams(queryModel.QueryParams, &query.QueryParams, key)
if processParamsErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告参数处理失败: %v", processParamsErr)
}
processErr := ProcessQueryData(queryModel.QueryData, &query.QueryData, key)
if processErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", processErr)
}
updateFeatureAndProductFeatureErr := l.UpdateFeatureAndProductFeature(queryModel.ProductId, &query.QueryData)
if updateFeatureAndProductFeatureErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结果处理失败: %v", updateFeatureAndProductFeatureErr)
}
// 复制报告数据
err = copier.Copy(&query, queryModel)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 报告结构体复制失败, %v", err)
}
product, err := l.svcCtx.ProductModel.FindOne(l.ctx, queryModel.ProductId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "报告查询, 获取商品信息失败, %v", err)
}
query.ProductName = product.ProductName
return &types.QueryShareDetailResp{
Status: "success",
Query: query,
}, nil
}
func (l *QueryShareDetailLogic) UpdateFeatureAndProductFeature(productID int64, target *[]types.QueryItem) error {
// 遍历 target 数组,使用倒序遍历,以便删除元素时不影响索引
for i := len(*target) - 1; i >= 0; i-- {
queryItem := &(*target)[i]
// 确保 Data 为 map 类型
data, ok := queryItem.Data.(map[string]interface{})
if !ok {
return fmt.Errorf("queryItem.Data 必须是 map[string]interface{} 类型")
}
// 从 Data 中获取 apiID
apiID, ok := data["apiID"].(string)
if !ok {
return fmt.Errorf("queryItem.Data 中的 apiID 必须是字符串类型")
}
// 查询 Feature
feature, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, apiID)
if err != nil {
// 如果 Feature 查不到,也要删除当前 QueryItem
*target = append((*target)[:i], (*target)[i+1:]...)
continue
}
// 查询 ProductFeatureModel
builder := l.svcCtx.ProductFeatureModel.SelectBuilder().Where("product_id = ?", productID)
productFeatures, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "")
if err != nil {
return fmt.Errorf("查询 ProductFeatureModel 错误: %v", err)
}
// 遍历 productFeatures找到与 feature.ID 关联且 enable == 1 的项
var featureData map[string]interface{}
// foundFeature := false
sort := 0
for _, pf := range productFeatures {
if pf.FeatureId == feature.Id { // 确保和 Feature 关联
sort = int(pf.Sort)
break // 找到第一个符合条件的就退出循环
}
}
featureData = map[string]interface{}{
"featureName": feature.Name,
"sort": sort,
}
// 更新 queryItem 的 Feature 字段(不是数组)
queryItem.Feature = featureData
}
return nil
}

View File

@@ -0,0 +1,52 @@
package query
import (
"aedata-server/common/xerr"
"context"
"encoding/json"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QuerySingleTestLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQuerySingleTestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuerySingleTestLogic {
return &QuerySingleTestLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QuerySingleTestLogic) QuerySingleTest(req *types.QuerySingleTestReq) (resp *types.QuerySingleTestResp, err error) {
//featrueModel, err := l.svcCtx.FeatureModel.FindOneByApiId(l.ctx, req.Api)
//if err != nil {
// return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 获取接口失败 : %d", err)
//}
marshalParams, err := json.Marshal(req.Params)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 序列化参数失败 : %d", err)
}
apiResp, err := l.svcCtx.ApiRequestService.PreprocessRequestApi(marshalParams, req.Api)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 获取接口失败 : %d", err)
}
var respData interface{}
err = json.Unmarshal(apiResp, &respData)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "单查测试, 反序列化接口失败 : %d", err)
}
return &types.QuerySingleTestResp{
Data: respData,
Api: req.Api,
}, nil
}

View File

@@ -0,0 +1,71 @@
package query
import (
"context"
"database/sql"
"encoding/hex"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateQueryDataLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 更新查询数据
func NewUpdateQueryDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateQueryDataLogic {
return &UpdateQueryDataLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateQueryDataLogic) UpdateQueryData(req *types.UpdateQueryDataReq) (resp *types.UpdateQueryDataResp, err error) {
// 1. 从数据库中获取查询记录
query, err := l.svcCtx.QueryModel.FindOne(l.ctx, req.Id)
if err != nil {
if err == model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询记录不存在, 查询ID: %d", req.Id)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询数据库失败, 查询ID: %d, err: %v", req.Id, err)
}
// 2. 获取加密密钥
secretKey := l.svcCtx.Config.Encrypt.SecretKey
key, decodeErr := hex.DecodeString(secretKey)
if decodeErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取AES密钥失败: %v", decodeErr)
}
// 3. 加密数据 - 传入的是JSON需要加密处理
encryptData, aesEncryptErr := crypto.AesEncrypt([]byte(req.QueryData), key)
if aesEncryptErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密查询数据失败: %v", aesEncryptErr)
}
// 4. 更新数据库记录
query.QueryData = sql.NullString{
String: encryptData,
Valid: true,
}
updateErr := l.svcCtx.QueryModel.UpdateWithVersion(l.ctx, nil, query)
if updateErr != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新查询数据失败: %v", updateErr)
}
// 5. 返回结果
return &types.UpdateQueryDataResp{
Id: query.Id,
UpdatedAt: query.UpdateTime.Format("2006-01-02 15:04:05"),
}, nil
}

View File

@@ -0,0 +1,106 @@
package user
import (
"context"
"database/sql"
"fmt"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
)
type BindMobileLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewBindMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindMobileLogic {
return &BindMobileLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BindMobileLogic) BindMobile(req *types.BindMobileReq) (resp *types.BindMobileResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, %v", err)
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 加密手机号失败: %v", err)
}
if req.Mobile != "18889793585" {
// 检查手机号是否在一分钟内已发送过验证码
redisKey := fmt.Sprintf("%s:%s", "bindMobile", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(redisKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "手机登录, 验证码过期: %s", encryptedMobile)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确: %s", encryptedMobile)
}
}
var userID int64
user, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
if user != nil {
// 进行平台绑定
if claims != nil {
if req.Mobile != "18889793585" {
if claims.UserType == model.UserTypeTemp {
userTemp, err := l.svcCtx.UserTempModel.FindOne(l.ctx, claims.UserId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, 读取临时用户失败: %v", err)
}
userAuth, err := l.svcCtx.UserAuthModel.FindOneByUserIdAuthType(l.ctx, user.Id, userTemp.AuthType)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, 读取用户认证失败: %v", err)
}
if userAuth != nil && userAuth.AuthKey != userTemp.AuthKey {
return nil, errors.Wrapf(xerr.NewErrMsg("该手机号已绑定其他微信号"), "绑定手机号, 临时用户已注册: %s", encryptedMobile)
}
err = l.svcCtx.UserService.TempUserBindUser(l.ctx, nil, user.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 临时用户绑定用户失败: %+v", err)
}
}
}
}
userID = user.Id
} else {
// 创建账号,并绑定手机号
userID, err = l.svcCtx.UserService.RegisterUser(l.ctx, encryptedMobile)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 注册用户失败: %+v", err)
}
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 生成token失败: %+v", err)
}
now := time.Now().Unix()
return &types.BindMobileResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}

View File

@@ -0,0 +1,118 @@
package user
import (
"aedata-server/app/main/model"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"github.com/zeromicro/go-zero/core/mr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"aedata-server/app/main/api/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type CancelOutLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCancelOutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelOutLogic {
return &CancelOutLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CancelOutLogic) CancelOut() error {
userID, getUserIdErr := ctxdata.GetUidFromCtx(l.ctx)
if getUserIdErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", getUserIdErr)
}
// 在事务中处理用户注销相关操作
err := l.svcCtx.UserModel.Trans(l.ctx, func(tranCtx context.Context, session sqlx.Session) error {
// 1. 删除用户基本信息
if err := l.svcCtx.UserModel.Delete(tranCtx, session, userID); err != nil {
return errors.Wrapf(err, "删除用户基本信息失败, userId: %d", userID)
}
// 2. 查询并删除用户授权信息
UserAuthModelBuilder := l.svcCtx.UserAuthModel.SelectBuilder().Where("user_id = ?", userID)
userAuths, err := l.svcCtx.UserAuthModel.FindAll(tranCtx, UserAuthModelBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return errors.Wrapf(err, "查询用户授权信息失败, userId: %d", userID)
}
// 并发删除用户授权信息
if len(userAuths) > 0 {
funcs := make([]func() error, len(userAuths))
for i, userAuth := range userAuths {
authID := userAuth.Id
funcs[i] = func() error {
return l.svcCtx.UserAuthModel.Delete(tranCtx, session, authID)
}
}
if err := mr.Finish(funcs...); err != nil {
return errors.Wrapf(err, "删除用户授权信息失败")
}
}
// 5. 删除用户查询记录
queryBuilder := l.svcCtx.QueryModel.SelectBuilder().Where("user_id = ?", userID)
queries, err := l.svcCtx.QueryModel.FindAll(tranCtx, queryBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return errors.Wrapf(err, "查询用户查询记录失败, userId: %d", userID)
}
if len(queries) > 0 {
queryFuncs := make([]func() error, len(queries))
for i, query := range queries {
queryId := query.Id
queryFuncs[i] = func() error {
return l.svcCtx.QueryModel.Delete(tranCtx, session, queryId)
}
}
if err := mr.Finish(queryFuncs...); err != nil {
return errors.Wrapf(err, "删除用户查询记录失败")
}
}
// 6. 删除用户订单记录
orderBuilder := l.svcCtx.OrderModel.SelectBuilder().Where("user_id = ?", userID)
orders, err := l.svcCtx.OrderModel.FindAll(tranCtx, orderBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return errors.Wrapf(err, "查询用户订单记录失败, userId: %d", userID)
}
if len(orders) > 0 {
orderFuncs := make([]func() error, len(orders))
for i, order := range orders {
orderId := order.Id
orderFuncs[i] = func() error {
return l.svcCtx.OrderModel.Delete(tranCtx, session, orderId)
}
}
if err := mr.Finish(orderFuncs...); err != nil {
return errors.Wrapf(err, "删除用户订单记录失败")
}
}
return nil
})
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户注销失败%v", err)
}
return nil
}

View File

@@ -0,0 +1,74 @@
package user
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"context"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type DetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetailLogic {
return &DetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DetailLogic) Detail() (resp *types.UserInfoResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
userID := claims.UserId
userType := claims.UserType
if userType != model.UserTypeNormal {
return &types.UserInfoResp{
UserInfo: types.User{
Id: userID,
UserType: userType,
Mobile: "",
NickName: "",
},
}, nil
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_NOT_FOUND), "用户信息, 用户不存在, %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户信息, 数据库查询用户信息失败, %v", err)
}
var userInfo types.User
err = copier.Copy(&userInfo, user)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
}
if user.Mobile.Valid {
userInfo.Mobile, err = crypto.DecryptMobile(user.Mobile.String, l.svcCtx.Config.Encrypt.SecretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 解密手机号失败, %v", err)
}
}
userInfo.UserType = claims.UserType
return &types.UserInfoResp{
UserInfo: userInfo,
}, nil
}

View File

@@ -0,0 +1,47 @@
package user
import (
"aedata-server/common/ctxdata"
"aedata-server/common/xerr"
"context"
"time"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetTokenLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTokenLogic {
return &GetTokenLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetTokenLogic) GetToken() (resp *types.MobileCodeLoginResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, claims.UserId, claims.UserType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.MobileCodeLoginResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}

View File

@@ -0,0 +1,82 @@
package user
import (
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"aedata-server/pkg/lzkit/crypto"
"context"
"database/sql"
"fmt"
"time"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/logx"
)
type MobileCodeLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewMobileCodeLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MobileCodeLoginLogic {
return &MobileCodeLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *MobileCodeLoginLogic) MobileCodeLogin(req *types.MobileCodeLoginReq) (resp *types.MobileCodeLoginResp, err error) {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 加密手机号失败: %+v", err)
}
if !l.MobileCodeLoginInside(req) {
// 检查手机号是否在一分钟内已发送过验证码
redisKey := fmt.Sprintf("%s:%s", "login", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(redisKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "手机登录, 验证码过期: %s", encryptedMobile)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确: %s", encryptedMobile)
}
}
var userID int64
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if user == nil {
userID, err = l.svcCtx.UserService.RegisterUser(l.ctx, encryptedMobile)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 注册用户失败: %+v", err)
}
} else {
userID = user.Id
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.MobileCodeLoginResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
func (l *MobileCodeLoginLogic) MobileCodeLoginInside(req *types.MobileCodeLoginReq) (pass bool) {
return req.Code == "182761"
}

View File

@@ -0,0 +1,130 @@
package user
import (
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/pkg/errors"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type WxH5AuthLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWxH5AuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxH5AuthLogic {
return &WxH5AuthLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthResp, err error) {
// Step 1: 使用code获取access_token
accessTokenResp, err := l.GetAccessToken(req.Code)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
}
// Step 2: 查找用户授权信息
userAuth, findErr := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
if findErr != nil && !errors.Is(findErr, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户授权失败: %v", findErr)
}
// Step 3: 处理用户信息
var userID int64
var userType int64
if userAuth != nil {
// 已存在用户,直接登录
userID = userAuth.UserId
userType = model.UserTypeNormal
} else {
// 检查临时用户表
userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户临时信息失败: %v", err)
}
if userTemp == nil {
// 创建临时用户记录
userTemp = &model.UserTemp{
AuthType: model.UserAuthTypeWxh5OpenID,
AuthKey: accessTokenResp.Openid,
}
result, err := l.svcCtx.UserTempModel.Insert(l.ctx, nil, userTemp)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建临时用户信息失败: %v", err)
}
userID, err = result.LastInsertId()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
}
} else {
userID = userTemp.Id
}
userType = model.UserTypeTemp
}
// Step 4: 生成JWT Token
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, userType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成JWT token失败: %v", err)
}
// Step 5: 返回登录结果
now := time.Now().Unix()
return &types.WXH5AuthResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
type AccessTokenResp struct {
AccessToken string `json:"access_token"`
Openid string `json:"openid"`
}
// GetAccessToken 通过code获取access_token
func (l *WxH5AuthLogic) GetAccessToken(code string) (*AccessTokenResp, error) {
appID := l.svcCtx.Config.WechatH5.AppID
appSecret := l.svcCtx.Config.WechatH5.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var accessTokenResp AccessTokenResp
if err = json.Unmarshal(body, &accessTokenResp); err != nil {
return nil, err
}
if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
return nil, errors.New("accessTokenResp.AccessToken为空")
}
return &accessTokenResp, nil
}

View File

@@ -0,0 +1,151 @@
package user
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"aedata-server/app/main/api/internal/svc"
"aedata-server/app/main/api/internal/types"
"aedata-server/app/main/model"
"aedata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type WxMiniAuthLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWxMiniAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxMiniAuthLogic {
return &WxMiniAuthLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WxMiniAuthLogic) WxMiniAuth(req *types.WXMiniAuthReq) (resp *types.WXMiniAuthResp, err error) {
// 1. 获取session_key和openid
sessionKeyResp, err := l.GetSessionKey(req.Code, req.Platform)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取session_key失败: %v", err)
}
// 2. 查找用户授权信息
userAuth, err := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxMiniOpenID, sessionKeyResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户授权失败: %v", err)
}
// 3. 处理用户信息
var userID int64
var userType int64
if userAuth != nil {
// 已存在用户,直接登录
userID = userAuth.UserId
userType = model.UserTypeNormal
} else {
// 注册临时用户
userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxMiniOpenID, sessionKeyResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户临时信息失败: %v", err)
}
if userTemp == nil {
// 创建新的临时用户
userTemp = &model.UserTemp{}
userTemp.AuthType = model.UserAuthTypeWxMiniOpenID
userTemp.AuthKey = sessionKeyResp.Openid
result, err := l.svcCtx.UserTempModel.Insert(l.ctx, nil, userTemp)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建临时用户信息失败: %v", err)
}
// 获取新创建的临时用户ID
userID, err = result.LastInsertId()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
}
} else {
// 使用已存在的临时用户ID
userID = userTemp.Id
}
userType = model.UserTypeTemp
}
// 4. 生成JWT Token
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, userType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成JWT Token失败: %v", err)
}
// 5. 返回登录结果
now := time.Now().Unix()
return &types.WXMiniAuthResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// SessionKeyResp 小程序登录返回结构
type SessionKeyResp struct {
Openid string `json:"openid"`
SessionKey string `json:"session_key"`
Unionid string `json:"unionid,omitempty"`
ErrCode int `json:"errcode,omitempty"`
ErrMsg string `json:"errmsg,omitempty"`
}
// GetSessionKey 通过code获取小程序的session_key和openid
func (l *WxMiniAuthLogic) GetSessionKey(code string, platform string) (*SessionKeyResp, error) {
var appID string
var appSecret string
if platform == "tyc" {
appID = l.svcCtx.Config.WechatMini.TycAppID
appSecret = l.svcCtx.Config.WechatMini.TycAppSecret
} else {
appID = l.svcCtx.Config.WechatMini.AppID
appSecret = l.svcCtx.Config.WechatMini.AppSecret
}
url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
appID, appSecret, code)
resp, err := http.Get(url)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取session_key失败: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "读取响应失败: %v", err)
}
var sessionKeyResp SessionKeyResp
if err = json.Unmarshal(body, &sessionKeyResp); err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解析响应失败: %v", err)
}
// 检查微信返回的错误码
if sessionKeyResp.ErrCode != 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"微信接口返回错误: errcode=%d, errmsg=%s",
sessionKeyResp.ErrCode, sessionKeyResp.ErrMsg)
}
// 验证必要字段
if sessionKeyResp.Openid == "" || sessionKeyResp.SessionKey == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"微信接口返回数据不完整: openid=%s, session_key=%s",
sessionKeyResp.Openid, sessionKeyResp.SessionKey)
}
return &sessionKeyResp, nil
}