作者 yangfu

feat-1.0 chat doc

正在显示 45 个修改的文件 包含 2335 行增加44 行删除
package dataset
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/logic/dataset"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
)
func ChatDatasetAddFilesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ChatDatasetAddFilesRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := dataset.NewChatDatasetAddFilesLogic(r.Context(), svcCtx)
resp, err := l.ChatDatasetAddFiles(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
package dataset
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/logic/dataset"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
)
func ChatDatasetRemvoeFilesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ChatDatasetAddFilesRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := dataset.NewChatDatasetRemvoeFilesLogic(r.Context(), svcCtx)
resp, err := l.ChatDatasetRemvoeFiles(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
package document
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/logic/document"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
)
func ChatDocumentBatchSaveHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ChatDocumentBatchSaveRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := document.NewChatDocumentBatchSaveLogic(r.Context(), svcCtx)
resp, err := l.ChatDocumentBatchSave(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
... ... @@ -93,6 +93,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Handler: document.ChatDocumentSaveHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/chat/document/batch_save",
Handler: document.ChatDocumentBatchSaveHandler(serverCtx),
},
{
Method: http.MethodDelete,
Path: "/chat/document/:id",
Handler: document.ChatDocumentDeleteHandler(serverCtx),
... ... @@ -147,6 +152,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/chat/dataset/search",
Handler: dataset.ChatDatasetSearchHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/chat/dataset/add_files",
Handler: dataset.ChatDatasetAddFilesHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/chat/dataset/remove_files",
Handler: dataset.ChatDatasetRemvoeFilesHandler(serverCtx),
},
}...,
),
rest.WithJwt(serverCtx.Config.SystemAuth.AccessSecret),
... ...
... ... @@ -6,6 +6,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/open"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/contextdata"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
... ... @@ -31,29 +32,51 @@ func NewChatSessionGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ch
func (l *ChatSessionGetLogic) ChatSessionGet(req *types.ChatSessionGetRequest) (resp *types.ChatSessionGetResponse, err error) {
var (
conn = l.svcCtx.DefaultDBConn()
dm *domain.ChatSession
session *domain.ChatSession
records []*domain.ChatSessionRecord
token = contextdata.GetUserTokenFromCtx(l.ctx)
user open.User
)
// 货号唯一
if dm, err = l.svcCtx.ChatSessionRepository.FindOne(l.ctx, conn, req.Id); err != nil {
if session, err = l.svcCtx.ChatSessionRepository.FindOne(l.ctx, conn, req.Id); err != nil {
return nil, xerr.NewErrMsgErr("不存在", err)
}
if user, err = l.svcCtx.SystemOpen.User(l.ctx, conn, dm.UserId); err != nil {
if user, err = l.svcCtx.SystemOpen.User(l.ctx, conn, session.UserId); err != nil {
return nil, xerr.NewErrMsgErr("用户不存在", err)
}
if _, records, err = l.svcCtx.ChatSessionRecordRepository.FindByCompanyUser(l.ctx, conn, token.CompanyId, token.UserId, domain.NewQueryOptions().MustWithKV("sessionId", dm.Id)); err != nil {
if _, records, err = l.svcCtx.ChatSessionRecordRepository.FindByCompanyUser(l.ctx, conn, token.CompanyId, token.UserId, domain.NewQueryOptions().MustWithKV("sessionId", session.Id)); err != nil {
return nil, xerr.NewErr(err)
}
var typesRecords []types.Record
lo.ForEach(records, func(item *domain.ChatSessionRecord, index int) {
typesRecords = append(typesRecords, NewTypesChatRecord(item, user))
})
var documents []types.ChatDocumentItem
var dataset types.ChatDatasetItem
if session.Type == domain.TypeSparkDocumentsChat && len(session.Metadata.DocumentIds) > 0 {
for _, id := range session.Metadata.DocumentIds {
if item, _ := l.svcCtx.ChatDocumentRepository.FindOne(l.ctx, conn, id); item != nil {
documents = append(documents, types.NewTypesChatDocument(item))
}
}
} else if session.Type == domain.TypeSparkDatasetChat && session.Metadata.DatasetId > 0 {
_, documentMapping, _ := l.svcCtx.ChatDatasetDocumentMappingRepository.FindByDataset(l.ctx, conn, session.Metadata.DatasetId)
lazyDocument := tool.NewLazyLoadService(l.svcCtx.ChatDocumentRepository.FindOne)
lo.ForEach(documentMapping, func(item *domain.ChatDatasetDocumentMapping, index int) {
if document, _ := lazyDocument.Load(l.ctx, conn, item.DocumentId); document != nil {
documents = append(documents, types.NewTypesChatDocument(document))
}
})
if item, _ := l.svcCtx.ChatDatasetRepository.FindOne(l.ctx, conn, session.Metadata.DatasetId); item != nil {
dataset = types.NewTypesChatDataset(item, lo.ToPtr(len(documents)))
}
}
resp = &types.ChatSessionGetResponse{
ChatSession: NewTypesChatSession(dm),
ChatSession: NewTypesChatSession(session),
Records: typesRecords,
Documents: documents,
Dataset: &dataset,
}
return
}
... ...
... ... @@ -67,10 +67,20 @@ func NewDomainChatSession(token contextdata.UserToken, item types.ChatSessionIte
}
func NewTypesChatSession(item *domain.ChatSession) types.ChatSessionItem {
var documentIds []int64
var datasetId int64
if item.Metadata != nil {
datasetId = item.Metadata.DatasetId
documentIds = item.Metadata.DocumentIds
}
return types.ChatSessionItem{
Id: item.Id,
Title: item.Title,
Abstract: item.Abstract,
CreatedAt: item.CreatedAt,
Module: item.Module,
Type: item.Type,
DatasetId: datasetId,
DocumentIds: documentIds,
}
}
... ...
package dataset
import (
"context"
"github.com/samber/lo"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ChatDatasetAddFilesLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewChatDatasetAddFilesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatDatasetAddFilesLogic {
return &ChatDatasetAddFilesLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ChatDatasetAddFilesLogic) ChatDatasetAddFiles(req *types.ChatDatasetAddFilesRequest) (resp *types.ChatDatasetAddFilesResponse, err error) {
var (
conn = l.svcCtx.DefaultDBConn()
dm *domain.ChatDataset
documentMapping []*domain.ChatDatasetDocumentMapping
)
// 货号唯一
if dm, err = l.svcCtx.ChatDatasetRepository.FindOne(l.ctx, conn, req.Id); err != nil {
return nil, xerr.NewErrMsgErr("不存在", err)
}
_, documentMapping, _ = l.svcCtx.ChatDatasetDocumentMappingRepository.FindByDataset(l.ctx, conn, dm.Id)
if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
for _, id := range req.DocumentIds {
if lo.ContainsBy(documentMapping, func(item *domain.ChatDatasetDocumentMapping) bool {
return item.DocumentId == id
}) {
continue
}
if _, err = l.svcCtx.ChatDatasetDocumentMappingRepository.Insert(l.ctx, conn, &domain.ChatDatasetDocumentMapping{
DatasetId: dm.Id,
DocumentId: id,
}); err != nil {
return err
}
}
return err
}, true); err != nil {
return nil, xerr.NewErrMsg("添加文档失败")
}
resp = &types.ChatDatasetAddFilesResponse{}
return
}
... ...
package dataset
import (
"context"
"github.com/samber/lo"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ChatDatasetRemvoeFilesLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewChatDatasetRemvoeFilesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatDatasetRemvoeFilesLogic {
return &ChatDatasetRemvoeFilesLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ChatDatasetRemvoeFilesLogic) ChatDatasetRemvoeFiles(req *types.ChatDatasetAddFilesRequest) (resp *types.ChatDatasetAddFilesResponse, err error) {
var (
conn = l.svcCtx.DefaultDBConn()
dm *domain.ChatDataset
documentMapping []*domain.ChatDatasetDocumentMapping
)
// 货号唯一
if dm, err = l.svcCtx.ChatDatasetRepository.FindOne(l.ctx, conn, req.Id); err != nil {
return nil, xerr.NewErrMsgErr("不存在", err)
}
_, documentMapping, _ = l.svcCtx.ChatDatasetDocumentMappingRepository.FindByDataset(l.ctx, conn, dm.Id)
if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
for _, id := range req.DocumentIds {
var found *domain.ChatDatasetDocumentMapping
if !lo.ContainsBy(documentMapping, func(item *domain.ChatDatasetDocumentMapping) bool {
if item.DocumentId == id {
found = item
}
return item.DocumentId == id
}) {
continue
}
if _, err = l.svcCtx.ChatDatasetDocumentMappingRepository.Delete(l.ctx, conn, found); err != nil {
return err
}
}
return err
}, true); err != nil {
return nil, xerr.NewErrMsg("添加文档失败")
}
resp = &types.ChatDatasetAddFilesResponse{}
return
}
... ...
package document
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/ai"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ChatDocumentBatchSaveLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewChatDocumentBatchSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatDocumentBatchSaveLogic {
return &ChatDocumentBatchSaveLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ChatDocumentBatchSaveLogic) ChatDocumentBatchSave(req *types.ChatDocumentBatchSaveRequest) (resp *types.ChatDocumentBatchSaveResponse, err error) {
var (
model *domain.ChatModel
fileId string
documents = make([]types.ChatDocumentItem, 0)
fileMap = make(map[string]string)
)
model, _ = domain.DefaultChatModels.Match(4)
for _, file := range req.Files {
// 文件上传星火文档
// 设置回调
if fileId, err = ai.SparkUploadFile(model.Config.AppId, model.Config.AppKey, model.Config.AppSecret, ai.SparkFileRequest{
Url: file.Url,
FileName: file.FileName,
CallbackUrl: "",
}); err != nil {
return nil, xerr.NewErrMsgErr("上传文件到星火文档失败", err)
}
fileMap[file.Url] = fileId
}
if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
for _, file := range req.Files {
var ok bool
if fileId, ok = fileMap[file.Url]; !ok {
continue
}
var dm *domain.ChatDocument
// 唯一判断
dm = types.NewDomainChatDocument(file.FileName, file.Url, file.Size, fileId)
if dm, err = l.svcCtx.ChatDocumentRepository.Insert(l.ctx, conn, dm); err != nil {
return err
}
documents = append(documents, types.NewTypesChatDocument(dm))
}
return err
}, true); err != nil {
return nil, xerr.NewErrMsgErr("保存失败", err)
}
resp = &types.ChatDocumentBatchSaveResponse{
ChatDocument: documents,
}
return
}
... ...
package types
import (
"github.com/samber/lo"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/chat/internal/pkg/domain"
)
func NewTypesChatDataset(item *domain.ChatDataset, fileNum *int) ChatDatasetItem {
return ChatDatasetItem{
Id: item.Id,
Name: lo.ToPtr(item.Name),
Desc: lo.ToPtr(item.Desc),
Status: lo.ToPtr(item.Status),
CreatedAt: item.CreatedAt,
UpdatedAt: item.UpdatedAt,
FileNumber: fileNum,
}
}
... ...
... ... @@ -8,6 +8,8 @@ type ChatSessionGetRequest struct {
type ChatSessionGetResponse struct {
ChatSession ChatSessionItem `json:"session"`
Records []Record `json:"records"`
Documents []ChatDocumentItem `json:"documents"`
Dataset *ChatDatasetItem `json:"dataset"`
}
type ChatSessionSaveRequest struct {
... ... @@ -99,7 +101,7 @@ type ChatSessionConversationRequestWs struct {
SessionId int64 `form:"sessionId"` // 会话ID
ModelId int64 `form:"modelId"` // 模型ID
ContentType string `form:"contentType"` // 内容类型 文本:text (图片:image 文档:document)
Text string `form:"text"` // 内容文本
Text string `form:"text,optional"` // 内容文本
}
type Record struct {
... ... @@ -197,6 +199,20 @@ type ChatDocumentRenameResponse struct {
ChatDocument ChatDocumentItem `json:"document"`
}
type ChatDocumentBatchSaveRequest struct {
Files []DocumentFile `json:"files"`
}
type ChatDocumentBatchSaveResponse struct {
ChatDocument []ChatDocumentItem `json:"documents"`
}
type DocumentFile struct {
FileName string `json:"fileName"`
Url string `json:"url"`
Size float64 `json:"size"` // 文件大小(KB)
}
type ChatDatasetGetRequest struct {
Id int64 `path:"id"`
}
... ... @@ -260,3 +276,11 @@ type ChatDatasetRenameRequest struct {
type ChatDatasetRenameResponse struct {
ChatDataset ChatDatasetItem `json:"dataset"`
}
type ChatDatasetAddFilesRequest struct {
Id int64 `json:"id"` // 文档ID
DocumentIds []int64 `json:"documentIds"` // 文档ID列表
}
type ChatDatasetAddFilesResponse struct {
}
... ...
... ... @@ -26,6 +26,12 @@ service Core {
@doc "知识库-搜索"
@handler chatDatasetSearch
post /chat/dataset/search (ChatDatasetSearchRequest) returns (ChatDatasetSearchResponse)
@doc "知识库-添加文件"
@handler chatDatasetAddFiles
post /chat/dataset/add_files (ChatDatasetAddFilesRequest) returns (ChatDatasetAddFilesResponse)
@doc "知识库-移除文件"
@handler chatDatasetRemvoeFiles
post /chat/dataset/remove_files (ChatDatasetAddFilesRequest) returns (ChatDatasetAddFilesResponse)
}
type (
... ... @@ -77,6 +83,7 @@ type (
}
)
// 知识库重命名
type(
ChatDatasetRenameRequest{
Id int64 `json:"id"` // 文档ID
... ... @@ -86,3 +93,14 @@ type(
ChatDataset ChatDatasetItem `json:"dataset"`
}
)
// 知识库添加新文档
type(
ChatDatasetAddFilesRequest{
Id int64 `json:"id"` // 文档ID
DocumentIds []int64 `json:"documentIds"` // 文档ID列表
}
ChatDatasetAddFilesResponse{
}
)
\ No newline at end of file
... ...
... ... @@ -14,6 +14,9 @@ service Core {
@doc "文档-保存"
@handler chatDocumentSave
post /chat/document (ChatDocumentSaveRequest) returns (ChatDocumentSaveResponse)
@doc "文档-批量保存"
@handler chatDocumentBatchSave
post /chat/document/batch_save (ChatDocumentBatchSaveRequest) returns (ChatDocumentBatchSaveResponse)
@doc "文档-删除"
@handler chatDocumentDelete
delete /chat/document/:id (ChatDocumentDeleteRequest) returns (ChatDocumentDeleteResponse)
... ... @@ -82,6 +85,7 @@ type (
}
)
// 文档重命名
type(
ChatDocumentRenameRequest{
Id int64 `json:"id"` // 文档ID
... ... @@ -91,3 +95,18 @@ type(
ChatDocument ChatDocumentItem `json:"document"`
}
)
//文档批量添加
type(
ChatDocumentBatchSaveRequest {
Files []DocumentFile `json:"files"`
}
ChatDocumentBatchSaveResponse {
ChatDocument []ChatDocumentItem `json:"documents"`
}
DocumentFile{
FileName string `json:"fileName"`
Url string `json:"url"`
Size float64 `json:"size"` // 文件大小(KB)
}
)
\ No newline at end of file
... ...
... ... @@ -53,6 +53,8 @@ type (
ChatSessionGetResponse {
ChatSession ChatSessionItem `json:"session"`
Records []Record `json:"records"`
Documents []ChatDocumentItem `json:"documents"`
Dataset *ChatDatasetItem `json:"dataset"`
}
ChatSessionSaveRequest {
... ... @@ -143,7 +145,7 @@ type(
SessionId int64 `form:"sessionId"` // 会话ID
ModelId int64 `form:"modelId"` // 模型ID
ContentType string `form:"contentType"` // 内容类型 文本:text (图片:image 文档:document)
Text string `form:"text"` // 内容文本
Text string `form:"text,optional"` // 内容文本
}
Record{
Id int64 `json:"id"` // 记录ID
... ...
Name: sumicro-system
Host: 0.0.0.0
Port: 8080
Port: 8081
Verbose: false
Migrate: true
... ...
package app
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/logic/app"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
)
func SystemAppGetHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.SystemAppGetRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := app.NewSystemAppGetLogic(r.Context(), svcCtx)
resp, err := l.SystemAppGet(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
package app
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/logic/app"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
)
func SystemAppSearchHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.SystemAppSearchRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := app.NewSystemAppSearchLogic(r.Context(), svcCtx)
resp, err := l.SystemAppSearch(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
package app
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/logic/app"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
)
func SystemAppSetConfigHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.SystemAppSetConfigRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := app.NewSystemAppSetConfigLogic(r.Context(), svcCtx)
resp, err := l.SystemAppSetConfig(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
package employee
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/logic/employee"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
)
func SystemDepartmentEmployeesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.DepartmentEmployeesRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := employee.NewSystemDepartmentEmployeesLogic(r.Context(), svcCtx)
resp, err := l.SystemDepartmentEmployees(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
... ...
... ... @@ -4,6 +4,7 @@ package handler
import (
"net/http"
app "gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler/app"
auth "gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler/auth"
company "gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler/company"
department "gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler/department"
... ... @@ -129,6 +130,31 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
[]rest.Route{
{
Method: http.MethodGet,
Path: "/system/app/:id",
Handler: app.SystemAppGetHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/system/app/search",
Handler: app.SystemAppSearchHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/system/app/set_config",
Handler: app.SystemAppSetConfigHandler(serverCtx),
},
}...,
),
rest.WithJwt(serverCtx.Config.SystemAuth.AccessSecret),
rest.WithPrefix("/v1"),
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.LogRequest},
[]rest.Route{
{
Method: http.MethodGet,
Path: "/system/employee/:id",
Handler: employee.SystemEmployeeGetHandler(serverCtx),
},
... ... @@ -172,6 +198,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/system/employee/export",
Handler: employee.SystemEmployeeExportHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/system/department-employees",
Handler: employee.SystemDepartmentEmployeesHandler(serverCtx),
},
}...,
),
rest.WithJwt(serverCtx.Config.SystemAuth.AccessSecret),
... ...
package app
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SystemAppGetLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSystemAppGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemAppGetLogic {
return &SystemAppGetLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SystemAppGetLogic) SystemAppGet(req *types.SystemAppGetRequest) (resp *types.SystemAppGetResponse, err error) {
var (
conn = l.svcCtx.DefaultDBConn()
companyApp *domain.SysCompanyApp
app *domain.SysApp
)
if companyApp, err = l.svcCtx.CompanyAppRepository.FindOne(l.ctx, conn, req.Id); err != nil {
return nil, xerr.NewErrMsgErr("不存在", err)
}
if app, err = l.svcCtx.AppRepository.FindOne(l.ctx, conn, companyApp.AppId); err != nil {
return nil, xerr.NewErrMsgErr("不存在", err)
}
resp = &types.SystemAppGetResponse{
SystemApp: NewTypesSystemAppItem(app, companyApp),
}
return
}
... ...
package app
import (
"context"
"github.com/samber/lo"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/contextdata"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SystemAppSearchLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSystemAppSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemAppSearchLogic {
return &SystemAppSearchLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SystemAppSearchLogic) SystemAppSearch(req *types.SystemAppSearchRequest) (resp *types.SystemAppSearchResponse, err error) {
var (
conn = l.svcCtx.DefaultDBConn()
apps []*domain.SysApp
companyApps []*domain.SysCompanyApp
token = contextdata.GetUserTokenFromCtx(l.ctx)
)
queryOptions := domain.NewQueryOptions().
LikeKV("name", req.Name)
if _, apps, err = l.svcCtx.AppRepository.Find(l.ctx, conn, queryOptions); err != nil {
return nil, xerr.NewErr(err)
}
appsMap := lo.SliceToMap(apps, func(item *domain.SysApp) (int64, *domain.SysApp) {
return item.Id, item
})
if _, companyApps, err = l.svcCtx.CompanyAppRepository.Find(l.ctx, conn, domain.NewQueryOptions().MustWithKV("companyId", token.CompanyId)); err != nil {
return nil, xerr.NewErr(err)
}
list := make([]types.SystemAppItem, 0)
for _, cp := range companyApps {
var (
app *domain.SysApp
ok bool
)
if app, ok = appsMap[cp.AppId]; !ok {
continue
}
list = append(list, NewTypesSystemAppItem(app, cp))
}
// 公司配置APP
for _, app := range apps {
if !lo.ContainsBy(companyApps, func(item *domain.SysCompanyApp) bool {
return item.AppId == app.Id
}) {
l.svcCtx.CompanyAppRepository.Insert(l.ctx, conn, &domain.SysCompanyApp{
CompanyId: token.CompanyId,
AppId: app.Id,
Status: domain.Enable,
VisibleFlag: domain.VisibleAll,
VisibleUsers: make([]int64, 0),
VisibleGroups: make([]int64, 0),
AppConfig: domain.AppConfig{},
Sort: 1,
})
}
}
resp = &types.SystemAppSearchResponse{
List: list,
Total: int64(len(list)),
}
return
}
//func NewDomainSysApp(item types.SysAppItem) *domain.SysApp {
// return &domain.SysApp{
// }
// }
func NewTypesSystemAppItem(item *domain.SysApp, cp *domain.SysCompanyApp) types.SystemAppItem {
return types.SystemAppItem{
Id: cp.Id,
Code: item.Code,
Name: item.Name,
Logo: item.Logo,
Description: item.Description,
Type: item.Type,
VersionNumber: item.VersionNumber,
Status: cp.Status,
VisibleFlag: cp.VisibleFlag,
VisibleUsers: cp.VisibleUsers,
Sort: cp.Sort,
}
}
... ...
package app
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SystemAppSetConfigLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSystemAppSetConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemAppSetConfigLogic {
return &SystemAppSetConfigLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SystemAppSetConfigLogic) SystemAppSetConfig(req *types.SystemAppSetConfigRequest) (resp *types.SystemAppSetConfigResponse, err error) {
return
}
... ...
package employee
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SystemDepartmentEmployeesLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSystemDepartmentEmployeesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemDepartmentEmployeesLogic {
return &SystemDepartmentEmployeesLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SystemDepartmentEmployeesLogic) SystemDepartmentEmployees(req *types.DepartmentEmployeesRequest) (resp *types.DepartmentEmployeesResponse, err error) {
// todo: add your logic here and delete this line
return
}
... ...
... ... @@ -34,6 +34,7 @@ type ServiceContext struct {
RoleRepository domain.SysRoleRepository
GroupRepository domain.SysGroupRepository
AppRepository domain.SysAppRepository
CompanyAppRepository domain.SysCompanyAppRepository
UserDepartmentRepository domain.SysUserDepartmentRepository
}
... ... @@ -62,6 +63,7 @@ func NewServiceContext(c config.Config) *ServiceContext {
GroupRepository: repository.NewSysGroupRepository(cache.NewCachedRepository(mlCache)),
AppRepository: repository.NewSysAppRepository(cache.NewCachedRepository(mlCache)),
UserDepartmentRepository: repository.NewSysUserDepartmentRepository(cache.NewCachedRepository(mlCache)),
CompanyAppRepository: repository.NewSysCompanyAppRepository(cache.NewCachedRepository(mlCache)),
}
}
... ...
... ... @@ -147,6 +147,52 @@ type Group struct {
Name string `json:"name"` // 分组名称
}
type SystemAppGetRequest struct {
Id int64 `path:"id"`
}
type SystemAppGetResponse struct {
SystemApp SystemAppItem `json:"app"`
}
type SystemAppUpdateResponse struct {
}
type SystemAppSearchRequest struct {
Page int `json:"page,optional"`
Size int `json:"size,optional"`
Name string `json:"name,optional"`
VisibleFlag int `json:"visibleFlag,optional"` //0:所有 1:全员可见 2:部分可见 3:已停用
}
type SystemAppSearchResponse struct {
List []SystemAppItem `json:"list"`
Total int64 `json:"total"`
}
type SystemAppItem struct {
Id int64 `json:"id,omitempty"` // 唯一标识
Code string `json:"code,omitempty"` // 应用编码
Name string `json:"name,omitempty"` // 应用名称
Logo string `json:"logo,omitempty"` // 图标
Description string `json:"description,omitempty"` // 描述
Type string `json:"type,omitempty"` // 分类 default
VersionNumber string `json:"versionNumber,omitempty"` // 应用版本号
Status int `json:"status,omitempty"` // 1:启用、2:停用
VisibleFlag int `json:"visibleFlag,omitempty"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:"visibleUsers,omitempty"` // 可见的用户 所有用户:空 部分用户:用户ID列表
Sort int `json:"sort,omitempty"` // 排序
}
type SystemAppSetConfigRequest struct {
VisibleFlag int `json:"visibleFlag"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:"visibleUsers"` // 可见的用户 所有用户:空 部分用户:用户ID列表
}
type SystemAppSetConfigResponse struct {
SystemApp SystemAppItem `json:"app"`
}
type EmployeeGetRequest struct {
Id int64 `path:"id"`
}
... ... @@ -226,3 +272,18 @@ type EmployeeImportRequest struct {
type EmployeeImportResponse struct {
}
type DepartmentEmployeesRequest struct {
CompanyId int64 `json:"companyId,optional"`
}
type DepartmentEmployeesResponse struct {
Departments []DepartmentEmployeeItem `json:"departments"`
}
type DepartmentEmployeeItem struct {
Id int64 `json:"id"` // 部门ID
Name string `json:"name"` // 部门名称
Parent int64 `json:"parent"` // 父级
Employees []Employee `json:"employees"` // 职员列表
}
... ...
... ... @@ -58,3 +58,15 @@ CREATE TABLE `sys_user_role`
`id` int(0) NOT NULL COMMENT '唯一标识',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `sys_app`
(
`id` int(0) NOT NULL COMMENT '唯一标识',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `sys_company_app`
(
`id` int(0) NOT NULL COMMENT '唯一标识',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
... ...
-- 数据初始化
INSERT INTO "sys"."app"("id", "code", "name", "logo", "description", "type", "version_number", "status", "created_at", "updated_at", "deleted_at", "version", "is_del")
VALUES (1, 'AI0001', 'AI大模型应用', NULL, '高校检索文档信息,准确回答专业问题。', 'default', '1.0.0', 1, 1717050119, 1717050119, 0, 0, 0);
-- 公司应用 唯一索引
CREATE UNIQUE INDEX unique_company_app ON sys.company_app(company_id,app_id );
\ No newline at end of file
... ...
syntax = "v1"
// 后台接口
@server(
prefix: v1
group: app
middleware: LogRequest
jwt: SystemAuth
)
service Core {
@doc "应用-详情"
@handler systemAppGet
get /system/app/:id (SystemAppGetRequest) returns (SystemAppGetResponse)
@doc "应用-搜索"
@handler systemAppSearch
post /system/app/search (SystemAppSearchRequest) returns (SystemAppSearchResponse)
@doc "应用-设置配置"
@handler systemAppSetConfig
get /system/app/set_config (SystemAppSetConfigRequest) returns (SystemAppSetConfigResponse)
}
type (
SystemAppGetRequest {
Id int64 `path:"id"`
}
SystemAppGetResponse {
SystemApp SystemAppItem `json:"app"`
}
SystemAppUpdateResponse {}
SystemAppSearchRequest {
Page int `json:"page,optional"`
Size int `json:"size,optional"`
Name string `json:"name,optional"`
VisibleFlag int `json:"visibleFlag,optional"` //0:所有 1:全员可见 2:部分可见 3:已停用
}
SystemAppSearchResponse{
List []SystemAppItem `json:"list"`
Total int64 `json:"total"`
}
SystemAppItem {
Id int64 `json:"id,omitempty"` // 唯一标识
Code string `json:"code,omitempty"` // 应用编码
Name string `json:"name,omitempty"` // 应用名称
Logo string `json:"logo,omitempty"` // 图标
Description string `json:"description,omitempty"` // 描述
Type string `json:"type,omitempty"` // 分类 default
VersionNumber string `json:"versionNumber,omitempty"` // 应用版本号
Status int `json:"status,omitempty"` // 1:启用、2:停用
VisibleFlag int `json:"visibleFlag,omitempty"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:"visibleUsers,omitempty"` // 可见的用户 所有用户:空 部分用户:用户ID列表
Sort int `json:"sort,omitempty"` // 排序
}
)
// 应用-设置配置
type(
SystemAppSetConfigRequest{
VisibleFlag int `json:"visibleFlag"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:"visibleUsers"` // 可见的用户 所有用户:空 部分用户:用户ID列表
}
SystemAppSetConfigResponse{
SystemApp SystemAppItem `json:"app"`
}
)
\ No newline at end of file
... ...
... ... @@ -35,6 +35,9 @@ service Core {
@doc "职员-导出"
@handler systemEmployeeExport
post /system/employee/export (EmployeeSearchRequest) returns (EmployeeSearchResponse)
@doc "职员-部门职员"
@handler systemDepartmentEmployees
post /system/department-employees (DepartmentEmployeesRequest) returns (DepartmentEmployeesResponse)
}
type(
... ... @@ -108,6 +111,21 @@ type(
EmployeeImportResponse{}
)
type (
DepartmentEmployeesRequest{
CompanyId int64 `json:"companyId,optional"`
}
DepartmentEmployeesResponse{
Departments []DepartmentEmployeeItem `json:"departments"`
}
DepartmentEmployeeItem{
Id int64 `json:"id"` // 部门ID
Name string `json:"name"` // 部门名称
Parent int64 `json:"parent"` // 父级
Employees []Employee `json:"employees"` // 职员列表
}
)
//type(
// Department {
// Id int64 `json:"id,optional,omitempty"` // 唯一标识
... ...
... ... @@ -99,6 +99,96 @@
]
}
},
"v1/system/app/search": {
"post": {
"summary": "应用-搜索",
"operationId": "systemAppSearch",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/SystemAppSearchResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/SystemAppSearchRequest"
}
}
],
"requestBody": {},
"tags": [
"app"
]
}
},
"v1/system/app/set_config": {
"get": {
"summary": "应用-设置配置",
"operationId": "systemAppSetConfig",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/SystemAppSetConfigResponse"
}
}
},
"parameters": [
{
"name": "visibleFlag",
"description": " 1:全员可见 2:部分可见",
"in": "query",
"required": true,
"type": "integer",
"format": "int32"
},
{
"name": "visibleUsers",
"description": " 可见的用户 所有用户:空 部分用户:用户ID列表",
"in": "query",
"required": true,
"type": "integer",
"format": "int64"
}
],
"requestBody": {},
"tags": [
"app"
]
}
},
"v1/system/app/{id}": {
"get": {
"summary": "应用-详情",
"operationId": "systemAppGet",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/SystemAppGetResponse"
}
}
},
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"type": "string"
}
],
"requestBody": {},
"tags": [
"app"
]
}
},
"v1/system/company-departments": {
"post": {
"summary": "公司部门",
... ... @@ -199,6 +289,34 @@
]
}
},
"v1/system/department-employees": {
"post": {
"summary": "职员-部门职员",
"operationId": "systemDepartmentEmployees",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/DepartmentEmployeesResponse"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/DepartmentEmployeesRequest"
}
}
],
"requestBody": {},
"tags": [
"employee"
]
}
},
"v1/system/department/batch-del": {
"delete": {
"summary": "部门-批量删除",
... ... @@ -878,6 +996,64 @@
"type": "object",
"title": "DepartmentDeleteResponse"
},
"DepartmentEmployeeItem": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"description": " 部门ID"
},
"name": {
"type": "string",
"description": " 部门名称"
},
"parent": {
"type": "integer",
"format": "int64",
"description": " 父级"
},
"employees": {
"type": "array",
"items": {
"$ref": "#/definitions/Employee"
},
"description": " 职员列表"
}
},
"title": "DepartmentEmployeeItem",
"required": [
"id",
"name",
"parent",
"employees"
]
},
"DepartmentEmployeesRequest": {
"type": "object",
"properties": {
"companyId": {
"type": "integer",
"format": "int64"
}
},
"title": "DepartmentEmployeesRequest"
},
"DepartmentEmployeesResponse": {
"type": "object",
"properties": {
"departments": {
"type": "array",
"items": {
"$ref": "#/definitions/DepartmentEmployeeItem"
}
}
},
"title": "DepartmentEmployeesResponse",
"required": [
"departments"
]
},
"DepartmentGetRequest": {
"type": "object",
"properties": {
... ... @@ -1306,6 +1482,183 @@
"name"
]
},
"SystemAppGetRequest": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
}
},
"title": "SystemAppGetRequest",
"required": [
"id"
]
},
"SystemAppGetResponse": {
"type": "object",
"properties": {
"app": {
"$ref": "#/definitions/SystemAppItem"
}
},
"title": "SystemAppGetResponse",
"required": [
"app"
]
},
"SystemAppItem": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"description": " 唯一标识"
},
"code": {
"type": "string",
"description": " 应用编码"
},
"name": {
"type": "string",
"description": " 应用名称"
},
"logo": {
"type": "string",
"description": " 图标"
},
"description": {
"type": "string",
"description": " 描述"
},
"type": {
"type": "string",
"description": " 分类 default"
},
"versionNumber": {
"type": "string",
"description": " 应用版本号"
},
"status": {
"type": "integer",
"format": "int32",
"description": " 1:启用、2:停用"
},
"visibleFlag": {
"type": "integer",
"format": "int32",
"description": " 1:全员可见 2:部分可见"
},
"visibleUsers": {
"type": "array",
"items": {
"type": "integer",
"format": "int64"
},
"description": " 可见的用户 所有用户:空 部分用户:用户ID列表"
},
"sort": {
"type": "integer",
"format": "int32",
"description": " 排序"
}
},
"title": "SystemAppItem",
"required": [
"id",
"code",
"name",
"logo",
"description",
"type",
"versionNumber",
"status",
"visibleFlag",
"visibleUsers",
"sort"
]
},
"SystemAppSearchRequest": {
"type": "object",
"properties": {
"page": {
"type": "integer",
"format": "int32"
},
"size": {
"type": "integer",
"format": "int32"
},
"name": {
"type": "string"
},
"visibleFlag": {
"type": "integer",
"format": "int32",
"description": "0:所有 1:全员可见 2:部分可见 3:已停用"
}
},
"title": "SystemAppSearchRequest"
},
"SystemAppSearchResponse": {
"type": "object",
"properties": {
"list": {
"type": "array",
"items": {
"$ref": "#/definitions/SystemAppItem"
}
},
"total": {
"type": "integer",
"format": "int64"
}
},
"title": "SystemAppSearchResponse",
"required": [
"list",
"total"
]
},
"SystemAppSetConfigRequest": {
"type": "object",
"properties": {
"visibleFlag": {
"type": "integer",
"format": "int32",
"description": " 1:全员可见 2:部分可见"
},
"visibleUsers": {
"type": "array",
"items": {
"type": "integer",
"format": "int64"
},
"description": " 可见的用户 所有用户:空 部分用户:用户ID列表"
}
},
"title": "SystemAppSetConfigRequest",
"required": [
"visibleFlag",
"visibleUsers"
]
},
"SystemAppSetConfigResponse": {
"type": "object",
"properties": {
"app": {
"$ref": "#/definitions/SystemAppItem"
}
},
"title": "SystemAppSetConfigResponse",
"required": [
"app"
]
},
"SystemAppUpdateResponse": {
"type": "object",
"title": "SystemAppUpdateResponse"
},
"SystemCompanyInfoRequest": {
"type": "object",
"title": "SystemCompanyInfoRequest"
... ...
syntax = "v1"
info(
title: "xx实例"
desc: "xx实例"
author: "author"
email: "email"
version: "v1"
)
@server(
prefix: v1
group: sys_company_app
jwt: JwtAuth
)
service Core {
@doc "详情"
@handler sys_company_appGet
get /sys_company_app/:id (SysCompanyAppGetRequest) returns (SysCompanyAppGetResponse)
@doc "保存"
@handler sys_company_appSave
post /sys_company_app (SysCompanyAppSaveRequest) returns (SysCompanyAppSaveResponse)
@doc "删除"
@handler sys_company_appDelete
delete /sys_company_app/:id (SysCompanyAppDeleteRequest) returns (SysCompanyAppDeleteResponse)
@doc "更新"
@handler sys_company_appUpdate
put /sys_company_app/:id (SysCompanyAppUpdateRequest) returns (SysCompanyAppUpdateResponse)
@doc "搜索"
@handler sys_company_appSearch
post /sys_company_app/search (SysCompanyAppSearchRequest) returns (SysCompanyAppSearchResponse)
}
type (
SysCompanyAppGetRequest {
Id int64 `path:"id"`
}
SysCompanyAppGetResponse {
SysCompanyApp SysCompanyAppItem `json:"sys_company_app"`
}
SysCompanyAppSaveRequest {
SysCompanyApp SysCompanyAppItem `json:"sys_company_app"`
}
SysCompanyAppSaveResponse {}
SysCompanyAppDeleteRequest {
Id int64 `path:"id"`
}
SysCompanyAppDeleteResponse {}
SysCompanyAppUpdateRequest {
Id int64 `path:"id"`
SysCompanyApp SysCompanyAppItem `json:"sys_company_app"`
}
SysCompanyAppUpdateResponse {}
SysCompanyAppSearchRequest {
Page int `json:"page"`
Size int `json:"size"`
}
SysCompanyAppSearchResponse{
List []SysCompanyAppItem `json:"list"`
Total int64 `json:"total"`
}
SysCompanyAppItem {
}
)
// logic CRUD
// Save
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysCompanyApp
//)
//// 唯一判断
//dm = NewDomainSysCompanyApp(req.SysCompanyApp)
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysCompanyAppRepository.Insert(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("保存失败")
//}
////resp = &types.SysCompanyAppSaveResponse{}
//return
//func NewDomainSysCompanyApp(item types.SysCompanyAppItem) *domain.SysCompanyApp {
// return &domain.SysCompanyApp{
// }
//}
//
//func NewTypesSysCompanyApp(item *domain.SysCompanyApp) types.SysCompanyAppItem {
// return types.SysCompanyAppItem{
// Id: item.Id,
// }
//}
// Get
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysCompanyApp
//)
//// 货号唯一
//if dm, err = l.svcCtx.SysCompanyAppRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//resp = &types.SysCompanyAppGetResponse{
// SysCompanyApp: NewTypesSysCompanyApp(dm),
//}
//return
// Delete
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysCompanyApp
//)
//if dm, err = l.svcCtx.SysCompanyAppRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// if dm, err = l.svcCtx.SysCompanyAppRepository.Delete(l.ctx, conn, dm); err != nil {
// return err
// }
// return nil
//}, true); err != nil {
// return nil, xerr.NewErrMsgErr("移除失败", err)
//}
//return
// Search
//var (
// conn = l.svcCtx.DefaultDBConn()
// dms []*domain.SysCompanyApp
// total int64
//)
//
//queryOptions := domain.NewQueryOptions().WithOffsetLimit(req.Page, req.Size).
// WithKV("", "")
//total, dms, err = l.svcCtx.SysCompanyAppRepository.Find(l.ctx, conn, queryOptions)
//list := make([]types.SysCompanyAppItem, 0)
//for i := range dms {
// list = append(list, NewTypesSysCompanyApp(dms[i]))
//}
//resp = &types.SysCompanyAppSearchResponse{
// List: list,
// Total: total,
//}
//return
// Update
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysCompanyApp
//)
//if dm, err = l.svcCtx.SysCompanyAppRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//// 不可编辑判断
//// 赋值
//// 更新
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysCompanyAppRepository.UpdateWithVersion(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("更新失败")
//}
//resp = &types.SysCompanyAppUpdateResponse{}
//return
... ...
syntax = "v1"
info(
title: "xx实例"
desc: "xx实例"
author: "author"
email: "email"
version: "v1"
)
@server(
prefix: v1
group: sys_user_department
jwt: JwtAuth
)
service Core {
@doc "详情"
@handler sys_user_departmentGet
get /sys_user_department/:id (SysUserDepartmentGetRequest) returns (SysUserDepartmentGetResponse)
@doc "保存"
@handler sys_user_departmentSave
post /sys_user_department (SysUserDepartmentSaveRequest) returns (SysUserDepartmentSaveResponse)
@doc "删除"
@handler sys_user_departmentDelete
delete /sys_user_department/:id (SysUserDepartmentDeleteRequest) returns (SysUserDepartmentDeleteResponse)
@doc "更新"
@handler sys_user_departmentUpdate
put /sys_user_department/:id (SysUserDepartmentUpdateRequest) returns (SysUserDepartmentUpdateResponse)
@doc "搜索"
@handler sys_user_departmentSearch
post /sys_user_department/search (SysUserDepartmentSearchRequest) returns (SysUserDepartmentSearchResponse)
}
type (
SysUserDepartmentGetRequest {
Id int64 `path:"id"`
}
SysUserDepartmentGetResponse {
SysUserDepartment SysUserDepartmentItem `json:"sys_user_department"`
}
SysUserDepartmentSaveRequest {
SysUserDepartment SysUserDepartmentItem `json:"sys_user_department"`
}
SysUserDepartmentSaveResponse {}
SysUserDepartmentDeleteRequest {
Id int64 `path:"id"`
}
SysUserDepartmentDeleteResponse {}
SysUserDepartmentUpdateRequest {
Id int64 `path:"id"`
SysUserDepartment SysUserDepartmentItem `json:"sys_user_department"`
}
SysUserDepartmentUpdateResponse {}
SysUserDepartmentSearchRequest {
Page int `json:"page"`
Size int `json:"size"`
}
SysUserDepartmentSearchResponse{
List []SysUserDepartmentItem `json:"list"`
Total int64 `json:"total"`
}
SysUserDepartmentItem {
}
)
// logic CRUD
// Save
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserDepartment
//)
//// 唯一判断
//dm = NewDomainSysUserDepartment(req.SysUserDepartment)
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysUserDepartmentRepository.Insert(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("保存失败")
//}
////resp = &types.SysUserDepartmentSaveResponse{}
//return
//func NewDomainSysUserDepartment(item types.SysUserDepartmentItem) *domain.SysUserDepartment {
// return &domain.SysUserDepartment{
// }
//}
//
//func NewTypesSysUserDepartment(item *domain.SysUserDepartment) types.SysUserDepartmentItem {
// return types.SysUserDepartmentItem{
// Id: item.Id,
// }
//}
// Get
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserDepartment
//)
//// 货号唯一
//if dm, err = l.svcCtx.SysUserDepartmentRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//resp = &types.SysUserDepartmentGetResponse{
// SysUserDepartment: NewTypesSysUserDepartment(dm),
//}
//return
// Delete
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserDepartment
//)
//if dm, err = l.svcCtx.SysUserDepartmentRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// if dm, err = l.svcCtx.SysUserDepartmentRepository.Delete(l.ctx, conn, dm); err != nil {
// return err
// }
// return nil
//}, true); err != nil {
// return nil, xerr.NewErrMsgErr("移除失败", err)
//}
//return
// Search
//var (
// conn = l.svcCtx.DefaultDBConn()
// dms []*domain.SysUserDepartment
// total int64
//)
//
//queryOptions := domain.NewQueryOptions().WithOffsetLimit(req.Page, req.Size).
// WithKV("", "")
//total, dms, err = l.svcCtx.SysUserDepartmentRepository.Find(l.ctx, conn, queryOptions)
//list := make([]types.SysUserDepartmentItem, 0)
//for i := range dms {
// list = append(list, NewTypesSysUserDepartment(dms[i]))
//}
//resp = &types.SysUserDepartmentSearchResponse{
// List: list,
// Total: total,
//}
//return
// Update
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserDepartment
//)
//if dm, err = l.svcCtx.SysUserDepartmentRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//// 不可编辑判断
//// 赋值
//// 更新
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysUserDepartmentRepository.UpdateWithVersion(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("更新失败")
//}
//resp = &types.SysUserDepartmentUpdateResponse{}
//return
... ...
syntax = "v1"
info(
title: "xx实例"
desc: "xx实例"
author: "author"
email: "email"
version: "v1"
)
@server(
prefix: v1
group: sys_user_role
jwt: JwtAuth
)
service Core {
@doc "详情"
@handler sys_user_roleGet
get /sys_user_role/:id (SysUserRoleGetRequest) returns (SysUserRoleGetResponse)
@doc "保存"
@handler sys_user_roleSave
post /sys_user_role (SysUserRoleSaveRequest) returns (SysUserRoleSaveResponse)
@doc "删除"
@handler sys_user_roleDelete
delete /sys_user_role/:id (SysUserRoleDeleteRequest) returns (SysUserRoleDeleteResponse)
@doc "更新"
@handler sys_user_roleUpdate
put /sys_user_role/:id (SysUserRoleUpdateRequest) returns (SysUserRoleUpdateResponse)
@doc "搜索"
@handler sys_user_roleSearch
post /sys_user_role/search (SysUserRoleSearchRequest) returns (SysUserRoleSearchResponse)
}
type (
SysUserRoleGetRequest {
Id int64 `path:"id"`
}
SysUserRoleGetResponse {
SysUserRole SysUserRoleItem `json:"sys_user_role"`
}
SysUserRoleSaveRequest {
SysUserRole SysUserRoleItem `json:"sys_user_role"`
}
SysUserRoleSaveResponse {}
SysUserRoleDeleteRequest {
Id int64 `path:"id"`
}
SysUserRoleDeleteResponse {}
SysUserRoleUpdateRequest {
Id int64 `path:"id"`
SysUserRole SysUserRoleItem `json:"sys_user_role"`
}
SysUserRoleUpdateResponse {}
SysUserRoleSearchRequest {
Page int `json:"page"`
Size int `json:"size"`
}
SysUserRoleSearchResponse{
List []SysUserRoleItem `json:"list"`
Total int64 `json:"total"`
}
SysUserRoleItem {
}
)
// logic CRUD
// Save
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserRole
//)
//// 唯一判断
//dm = NewDomainSysUserRole(req.SysUserRole)
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysUserRoleRepository.Insert(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("保存失败")
//}
////resp = &types.SysUserRoleSaveResponse{}
//return
//func NewDomainSysUserRole(item types.SysUserRoleItem) *domain.SysUserRole {
// return &domain.SysUserRole{
// }
//}
//
//func NewTypesSysUserRole(item *domain.SysUserRole) types.SysUserRoleItem {
// return types.SysUserRoleItem{
// Id: item.Id,
// }
//}
// Get
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserRole
//)
//// 货号唯一
//if dm, err = l.svcCtx.SysUserRoleRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//resp = &types.SysUserRoleGetResponse{
// SysUserRole: NewTypesSysUserRole(dm),
//}
//return
// Delete
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserRole
//)
//if dm, err = l.svcCtx.SysUserRoleRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// if dm, err = l.svcCtx.SysUserRoleRepository.Delete(l.ctx, conn, dm); err != nil {
// return err
// }
// return nil
//}, true); err != nil {
// return nil, xerr.NewErrMsgErr("移除失败", err)
//}
//return
// Search
//var (
// conn = l.svcCtx.DefaultDBConn()
// dms []*domain.SysUserRole
// total int64
//)
//
//queryOptions := domain.NewQueryOptions().WithOffsetLimit(req.Page, req.Size).
// WithKV("", "")
//total, dms, err = l.svcCtx.SysUserRoleRepository.Find(l.ctx, conn, queryOptions)
//list := make([]types.SysUserRoleItem, 0)
//for i := range dms {
// list = append(list, NewTypesSysUserRole(dms[i]))
//}
//resp = &types.SysUserRoleSearchResponse{
// List: list,
// Total: total,
//}
//return
// Update
//var (
// conn = l.svcCtx.DefaultDBConn()
// dm *domain.SysUserRole
//)
//if dm, err = l.svcCtx.SysUserRoleRepository.FindOne(l.ctx, conn, req.Id); err != nil {
// return nil, xerr.NewErrMsgErr("不存在", err)
//}
//// 不可编辑判断
//// 赋值
//// 更新
//if err = transaction.UseTrans(l.ctx, l.svcCtx.DB, func(ctx context.Context, conn transaction.Conn) error {
// dm, err = l.svcCtx.SysUserRoleRepository.UpdateWithVersion(l.ctx, conn, dm)
// return err
//}, true); err != nil {
// return nil, xerr.NewErrMsg("更新失败")
//}
//resp = &types.SysUserRoleUpdateResponse{}
//return
... ...
syntax = "proto3";
option go_package ="./pb";
package pb;
message SysCompanyAppGetReq {
int64 Id = 1;
}
message SysCompanyAppGetResp{
SysCompanyAppItem SysCompanyApp = 1;
}
message SysCompanyAppSaveReq {
}
message SysCompanyAppSaveResp{
}
message SysCompanyAppDeleteReq {
int64 Id = 1;
}
message SysCompanyAppDeleteResp{
}
message SysCompanyAppUpdateReq {
int64 Id = 1;
}
message SysCompanyAppUpdateResp{
}
message SysCompanyAppSearchReq {
int64 PageNumber = 1;
int64 PageSize = 2;
}
message SysCompanyAppSearchResp{
repeated SysCompanyAppItem List =1;
int64 Total =2;
}
message SysCompanyAppItem {
}
service SysCompanyAppService {
rpc SysCompanyAppGet(SysCompanyAppGetReq) returns(SysCompanyAppGetResp);
rpc SysCompanyAppSave(SysCompanyAppSaveReq) returns(SysCompanyAppSaveResp);
rpc SysCompanyAppDelete(SysCompanyAppDeleteReq) returns(SysCompanyAppDeleteResp);
rpc SysCompanyAppUpdate(SysCompanyAppUpdateReq) returns(SysCompanyAppUpdateResp);
rpc SysCompanyAppSearch(SysCompanyAppSearchReq) returns(SysCompanyAppSearchResp);
}
... ...
syntax = "proto3";
option go_package ="./pb";
package pb;
message SysUserDepartmentGetReq {
int64 Id = 1;
}
message SysUserDepartmentGetResp{
SysUserDepartmentItem SysUserDepartment = 1;
}
message SysUserDepartmentSaveReq {
}
message SysUserDepartmentSaveResp{
}
message SysUserDepartmentDeleteReq {
int64 Id = 1;
}
message SysUserDepartmentDeleteResp{
}
message SysUserDepartmentUpdateReq {
int64 Id = 1;
}
message SysUserDepartmentUpdateResp{
}
message SysUserDepartmentSearchReq {
int64 PageNumber = 1;
int64 PageSize = 2;
}
message SysUserDepartmentSearchResp{
repeated SysUserDepartmentItem List =1;
int64 Total =2;
}
message SysUserDepartmentItem {
}
service SysUserDepartmentService {
rpc SysUserDepartmentGet(SysUserDepartmentGetReq) returns(SysUserDepartmentGetResp);
rpc SysUserDepartmentSave(SysUserDepartmentSaveReq) returns(SysUserDepartmentSaveResp);
rpc SysUserDepartmentDelete(SysUserDepartmentDeleteReq) returns(SysUserDepartmentDeleteResp);
rpc SysUserDepartmentUpdate(SysUserDepartmentUpdateReq) returns(SysUserDepartmentUpdateResp);
rpc SysUserDepartmentSearch(SysUserDepartmentSearchReq) returns(SysUserDepartmentSearchResp);
}
... ...
syntax = "proto3";
option go_package ="./pb";
package pb;
message SysUserRoleGetReq {
int64 Id = 1;
}
message SysUserRoleGetResp{
SysUserRoleItem SysUserRole = 1;
}
message SysUserRoleSaveReq {
}
message SysUserRoleSaveResp{
}
message SysUserRoleDeleteReq {
int64 Id = 1;
}
message SysUserRoleDeleteResp{
}
message SysUserRoleUpdateReq {
int64 Id = 1;
}
message SysUserRoleUpdateResp{
}
message SysUserRoleSearchReq {
int64 PageNumber = 1;
int64 PageSize = 2;
}
message SysUserRoleSearchResp{
repeated SysUserRoleItem List =1;
int64 Total =2;
}
message SysUserRoleItem {
}
service SysUserRoleService {
rpc SysUserRoleGet(SysUserRoleGetReq) returns(SysUserRoleGetResp);
rpc SysUserRoleSave(SysUserRoleSaveReq) returns(SysUserRoleSaveResp);
rpc SysUserRoleDelete(SysUserRoleDeleteReq) returns(SysUserRoleDeleteResp);
rpc SysUserRoleUpdate(SysUserRoleUpdateReq) returns(SysUserRoleUpdateResp);
rpc SysUserRoleSearch(SysUserRoleSearchReq) returns(SysUserRoleSearchResp);
}
... ...
... ... @@ -12,5 +12,7 @@ func Migrate(db *gorm.DB) {
models.SysEmployee{},
models.SysUser{},
models.SysUserDepartment{},
models.SysApp{},
models.SysCompanyApp{},
)
}
... ...
... ... @@ -10,6 +10,13 @@ import (
type SysApp struct {
Id int64 // 唯一标识
Code string // 应用编码
Name string // 应用名称
Logo string // 图标
Description string // 描述
Type string // 分类 default
VersionNumber string // 应用版本号
Status int // 1:启用、2:停用
CreatedAt int64
UpdatedAt int64
DeletedAt int64
... ...
package models
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
"gorm.io/gorm"
"gorm.io/plugin/soft_delete"
)
type SysCompanyApp struct {
Id int64 // 唯一标识
CompanyId int64 // 公司表ID
AppId int64 // 应用ID
Status int // 1:启用、2:停用
VisibleFlag int // 1:全员可见 2:部分可见
VisibleUsers []int64 `gorm:"type:jsonb;serializer:json"` // 可见的用户 所有用户:空 部分用户:用户ID列表
VisibleGroups []int64 `gorm:"type:jsonb;serializer:json"` // 可见的用户组 所有用户:空 部分用户:用户ID列表
AppConfig domain.AppConfig `gorm:"type:jsonb;serializer:json"` // 应用配置
Sort int // 排序
CreatedAt int64
UpdatedAt int64
DeletedAt int64
Version int
IsDel soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt"`
}
func (m *SysCompanyApp) TableName() string {
return "sys.company_app"
}
func (m *SysCompanyApp) BeforeCreate(tx *gorm.DB) (err error) {
// m.CreatedAt = time.Now().Unix()
// m.UpdatedAt = time.Now().Unix()
return
}
func (m *SysCompanyApp) BeforeUpdate(tx *gorm.DB) (err error) {
// m.UpdatedAt = time.Now().Unix()
return
}
func (m *SysCompanyApp) CacheKeyFunc() string {
if m.Id == 0 {
return ""
}
return fmt.Sprintf("%v:cache:%v:id:%v", domain.ProjectName, m.TableName(), m.Id)
}
func (m *SysCompanyApp) CacheKeyFuncByObject(obj interface{}) string {
if v, ok := obj.(*SysCompanyApp); ok {
return v.CacheKeyFunc()
}
return ""
}
func (m *SysCompanyApp) CachePrimaryKeyFunc() string {
if len("") == 0 {
return ""
}
return fmt.Sprintf("%v:cache:%v:primarykey:%v", domain.ProjectName, m.TableName(), "key")
}
... ...
package repository
import (
"context"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/tiptok/gocomm/pkg/cache"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/db/models"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
"gorm.io/gorm"
)
type SysCompanyAppRepository struct {
*cache.CachedRepository
}
func (repository *SysCompanyAppRepository) Insert(ctx context.Context, conn transaction.Conn, dm *domain.SysCompanyApp) (*domain.SysCompanyApp, error) {
var (
err error
m = &models.SysCompanyApp{}
tx = conn.DB()
)
if m, err = repository.DomainModelToModel(dm); err != nil {
return nil, err
}
if tx = tx.Model(m).Save(m); tx.Error != nil {
return nil, tx.Error
}
dm.Id = m.Id
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) Update(ctx context.Context, conn transaction.Conn, dm *domain.SysCompanyApp) (*domain.SysCompanyApp, error) {
var (
err error
m *models.SysCompanyApp
tx = conn.DB()
)
if m, err = repository.DomainModelToModel(dm); err != nil {
return nil, err
}
queryFunc := func() (interface{}, error) {
tx = tx.Model(m).Updates(m)
return nil, tx.Error
}
if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
return nil, err
}
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) UpdateWithVersion(ctx context.Context, transaction transaction.Conn, dm *domain.SysCompanyApp) (*domain.SysCompanyApp, error) {
var (
err error
m *models.SysCompanyApp
tx = transaction.DB()
)
if m, err = repository.DomainModelToModel(dm); err != nil {
return nil, err
}
oldVersion := dm.Version
m.Version += 1
queryFunc := func() (interface{}, error) {
tx = tx.Model(m).Select("*").Where("id = ?", m.Id).Where("version = ?", oldVersion).Updates(m)
if tx.RowsAffected == 0 {
return nil, domain.ErrUpdateFail
}
return nil, tx.Error
}
if _, err = repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
return nil, err
}
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) Delete(ctx context.Context, conn transaction.Conn, dm *domain.SysCompanyApp) (*domain.SysCompanyApp, error) {
var (
tx = conn.DB()
m = &models.SysCompanyApp{Id: dm.Id}
)
queryFunc := func() (interface{}, error) {
tx = tx.Where("id = ?", m.Id).Delete(m)
return m, tx.Error
}
if _, err := repository.Query(queryFunc, m.CacheKeyFunc()); err != nil {
return dm, err
}
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) FindOne(ctx context.Context, conn transaction.Conn, id int64) (*domain.SysCompanyApp, error) {
var (
err error
tx = conn.DB()
m = new(models.SysCompanyApp)
)
queryFunc := func() (interface{}, error) {
tx = tx.Model(m).Where("id = ?", id).First(m)
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
return nil, domain.ErrNotFound
}
return m, tx.Error
}
cacheModel := new(models.SysCompanyApp)
cacheModel.Id = id
if err = repository.QueryCache(cacheModel.CacheKeyFunc, m, queryFunc); err != nil {
return nil, err
}
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) FindOneUnscoped(ctx context.Context, conn transaction.Conn, id int64) (*domain.SysCompanyApp, error) {
var (
err error
tx = conn.DB()
m = new(models.SysCompanyApp)
)
queryFunc := func() (interface{}, error) {
tx = tx.Model(m).Unscoped().Where("id = ?", id).First(m)
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
return nil, domain.ErrNotFound
}
return m, tx.Error
}
cacheModel := new(models.SysCompanyApp)
cacheModel.Id = id
if err = repository.QueryCache(cacheModel.CacheKeyFunc, m, queryFunc); err != nil {
return nil, err
}
return repository.ModelToDomainModel(m)
}
func (repository *SysCompanyAppRepository) Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*domain.SysCompanyApp, error) {
var (
tx = conn.DB()
ms []*models.SysCompanyApp
dms = make([]*domain.SysCompanyApp, 0)
total int64
)
queryFunc := func() (interface{}, error) {
tx = tx.Model(&ms).Order("id desc")
if total, tx = transaction.PaginationAndCount(ctx, tx, queryOptions, &ms); tx.Error != nil {
return dms, tx.Error
}
return dms, nil
}
if _, err := repository.Query(queryFunc); err != nil {
return 0, nil, err
}
for _, item := range ms {
if dm, err := repository.ModelToDomainModel(item); err != nil {
return 0, dms, err
} else {
dms = append(dms, dm)
}
}
return total, dms, nil
}
func (repository *SysCompanyAppRepository) ModelToDomainModel(from *models.SysCompanyApp) (*domain.SysCompanyApp, error) {
to := &domain.SysCompanyApp{}
err := copier.Copy(to, from)
return to, err
}
func (repository *SysCompanyAppRepository) DomainModelToModel(from *domain.SysCompanyApp) (*models.SysCompanyApp, error) {
to := &models.SysCompanyApp{}
err := copier.Copy(to, from)
return to, err
}
func NewSysCompanyAppRepository(cache *cache.CachedRepository) domain.SysCompanyAppRepository {
return &SysCompanyAppRepository{CachedRepository: cache}
}
... ...
... ... @@ -42,6 +42,14 @@ func (options QueryOptions) WithKV(key string, value interface{}) QueryOptions {
return options
}
func (options QueryOptions) LikeKV(key string, value interface{}) QueryOptions {
if isEmptyOrZeroValue(value) {
return options
}
options[key] = fmt.Sprintf("%%%v%%", value)
return options
}
func isEmptyOrZeroValue(i interface{}) bool {
if i == nil {
return true // 如果接口为空,返回true
... ...
... ... @@ -8,16 +8,17 @@ import (
type SysApp struct {
Id int64 `json:",omitempty"` // 唯一标识
Code string `json:",omitempty"` // 应用编码
CompanyId int64 `json:",omitempty"` // 公司表ID
Name string `json:",omitempty"` // 应用名称
Logo string `json:",omitempty"` // 图标
Description string `json:",omitempty"` // 描述
Type string `json:",omitempty"` // 分类 default
VersionNumber string `json:",omitempty"` // 应用版本号
Status int `json:",omitempty"` // 1:启用、2:停用
VisibleFlag int `json:",omitempty"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:",omitempty"` // 可见的用户 所有用户:空 部分用户:用户ID列表
VisibleGroups []int64 `json:",omitempty"` // 可见的用户组 所有用户:空 部分用户:用户ID列表
AppConfig AppConfig `json:",omitempty"` // 应用配置
Sort int `json:",omitempty"` // 排序
//VisibleFlag int `json:",omitempty"` // 1:全员可见 2:部分可见
//VisibleUsers []int64 `json:",omitempty"` // 可见的用户 所有用户:空 部分用户:用户ID列表
//VisibleGroups []int64 `json:",omitempty"` // 可见的用户组 所有用户:空 部分用户:用户ID列表
//AppConfig AppConfig `json:",omitempty"` // 应用配置
//Sort int `json:",omitempty"` // 排序
CreatedAt int64 `json:",omitempty"`
UpdatedAt int64 `json:",omitempty"`
DeletedAt int64 `json:",omitempty"`
... ... @@ -64,18 +65,22 @@ var DefaultApps = []SysApp{
{
Code: "AI0001",
Name: "AI大模型应用",
Description: "素天下AI大模型应用",
AppConfig: AppConfig{
AIConfig: &AIConfig{
XFSpark: XFSpark{
APPID: "4fd8694e",
APISecret: "NTVkM2FjNzk2NzQ5MzBkNWMwYTUwNjAz",
APIKey: "4a4081a20e9ba0fb1b9686ed93221989",
},
ChatGPT: ChatGPT{
APIKey: "4a4081a20e9ba0fb1b9686ed93221989",
},
},
},
Logo: "",
Type: "default",
Description: "高校检索文档信息,准确回答专业问题。",
VersionNumber: "1.0.0",
Status: 1,
//AppConfig: AppConfig{
// AIConfig: &AIConfig{
// XFSpark: XFSpark{
// APPID: "4fd8694e",
// APISecret: "NTVkM2FjNzk2NzQ5MzBkNWMwYTUwNjAz",
// APIKey: "4a4081a20e9ba0fb1b9686ed93221989",
// },
// ChatGPT: ChatGPT{
// APIKey: "4a4081a20e9ba0fb1b9686ed93221989",
// },
// },
//},
},
}
... ...
package domain
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/transaction"
)
type SysCompanyApp struct {
Id int64 // 唯一标识
CompanyId int64 `json:",omitempty"` // 公司表ID
AppId int64 `json:",omitempty"` // 应用ID
Status int `json:",omitempty"` // 1:启用、2:停用
VisibleFlag int `json:",omitempty"` // 1:全员可见 2:部分可见
VisibleUsers []int64 `json:",omitempty"` // 可见的用户 所有用户:空 部分用户:用户ID列表
VisibleGroups []int64 `json:",omitempty"` // 可见的用户组 所有用户:空 部分用户:用户ID列表
AppConfig AppConfig `json:",omitempty"` // 应用配置
Sort int `json:",omitempty"` // 排序
CreatedAt int64 `json:",omitempty"`
UpdatedAt int64 `json:",omitempty"`
DeletedAt int64 `json:",omitempty"`
Version int `json:",omitempty"`
}
type SysCompanyAppRepository interface {
Insert(ctx context.Context, conn transaction.Conn, dm *SysCompanyApp) (*SysCompanyApp, error)
Update(ctx context.Context, conn transaction.Conn, dm *SysCompanyApp) (*SysCompanyApp, error)
UpdateWithVersion(ctx context.Context, conn transaction.Conn, dm *SysCompanyApp) (*SysCompanyApp, error)
Delete(ctx context.Context, conn transaction.Conn, dm *SysCompanyApp) (*SysCompanyApp, error)
FindOne(ctx context.Context, conn transaction.Conn, id int64) (*SysCompanyApp, error)
FindOneUnscoped(ctx context.Context, conn transaction.Conn, id int64) (*SysCompanyApp, error)
Find(ctx context.Context, conn transaction.Conn, queryOptions map[string]interface{}) (int64, []*SysCompanyApp, error)
}
const (
VisibleAll = 1 // 全员可见
VisibleParts = 2 // 部分可见
Invisible = 3 // 都不可见
)
... ...
... ... @@ -35,7 +35,7 @@ func ChatSpark(appid string, apiKey string, apiSecret string, question string, c
d := websocket.Dialer{
HandshakeTimeout: 5 * time.Second,
}
conn, resp, err := d.Dial(assembleAuthUrl(hostChatDocumentUrl, apiKey, apiSecret), nil)
conn, resp, err := d.Dial(assembleAuthUrl(hostChatUrl, apiKey, apiSecret), nil)
if err != nil {
logx.Error(readResp(resp) + err.Error())
return
... ... @@ -59,35 +59,29 @@ func ChatSpark(appid string, apiKey string, apiSecret string, question string, c
break
}
var data map[string]interface{}
var data SparkChatMessage
err = json.Unmarshal(msg, &data)
if err != nil {
logx.Error("Error parsing JSON:", err)
return
}
logx.Info(string(msg))
//解析数据
payload := data["payload"].(map[string]interface{})
choices := payload["choices"].(map[string]interface{})
header := data["header"].(map[string]interface{})
code := header["code"].(float64)
if code != 0 {
logx.Error(data["payload"])
if data.Header.Code != 0 {
logx.Error("ws error code ", data.Header.Code)
return
}
status := choices["status"].(float64)
//logx.Info("status:",status)
text := choices["text"].([]interface{})
content := text[0].(map[string]interface{})["content"].(string)
status := data.Payload.Choices.Status
text := data.Payload.Choices.Text
var content string
if len(text) > 0 {
content = text[0].Content
channel <- content
}
if status != 2 {
answer += content
} else {
answer += content
usage := payload["usage"].(map[string]interface{})
temp := usage["text"].(map[string]interface{})
totalTokens := temp["total_tokens"].(float64)
totalTokens := data.Payload.Usage.Text.TotalTokens
logx.Infof("收到最终结果 total_tokens: %v answer:%v", totalTokens, answer)
conn.Close()
break
... ... @@ -96,6 +90,34 @@ func ChatSpark(appid string, apiKey string, apiSecret string, question string, c
return answer, nil
}
type SparkChatMessage struct {
Header struct {
Code int `json:"code"`
Message string `json:"message"`
Sid string `json:"sid"`
Status int `json:"status"`
} `json:"header"`
Payload struct {
Choices struct {
Status int `json:"status"`
Seq int `json:"seq"`
Text []struct {
Content string `json:"content"`
Role string `json:"role"`
Index int `json:"index"`
} `json:"text"`
} `json:"choices"`
Usage struct {
Text struct {
QuestionTokens int `json:"question_tokens"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"text"`
} `json:"usage"`
} `json:"payload"`
}
// 生成参数
func genParams1(appid, question string) map[string]interface{} { // 根据实际情况修改返回的数据结构和字段名
... ...