From 04bdbe73bca4764ea1548a81ad2dabe434a930e7 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Wed, 24 Jul 2024 10:34:11 +0800 Subject: [PATCH 01/19] =?UTF-8?q?1.=20=E5=88=A0=E9=99=A4=E7=BB=84=E7=BB=87?= =?UTF-8?q?=E6=A6=82=E5=BF=B5=202.=20=E7=8E=AF=E5=A2=83=EF=BC=88=E5=88=86?= =?UTF-8?q?=E5=8C=BA=EF=BC=89=E5=8F=96=E6=B6=88=E7=BB=91=E5=AE=9A=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E3=80=81=E5=9B=A2=E9=98=9F=E3=80=81=E8=AE=A2=E9=98=85?= =?UTF-8?q?=E5=85=B3=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/api/iml.go | 2 +- controller/organization/iml.go | 44 ---- controller/organization/organization.go | 24 --- controller/project/iml.go | 2 +- controller/subscribe/iml.go | 7 +- controller/subscribe/subscribe.go | 5 +- controller/upstream/iml.go | 21 +- controller/upstream/upstream.go | 3 +- module/api/api.go | 2 +- module/api/iml.go | 40 +--- module/catalogue/dto/output.go | 20 +- module/catalogue/iml.go | 186 ++++++----------- module/my-team/iml.go | 64 +++--- module/organization/dto/input.go | 18 -- module/organization/dto/output.go | 58 ------ module/organization/iml.go | 125 ------------ module/organization/organization.go | 24 --- module/partition/impl.go | 78 ++++---- module/project-authorization/iml.go | 41 ++-- module/project/dto/input.go | 7 +- module/project/dto/output.go | 87 ++++---- module/project/iml.go | 256 ++++++++---------------- module/project/project.go | 2 +- module/project_diff/iml.go | 27 +-- module/publish/iml.go | 28 +-- module/release/iml.go | 24 ++- module/service/iml.go | 56 +++--- module/subscribe/dto/input.go | 16 +- module/subscribe/dto/output.go | 26 +-- module/subscribe/iml.go | 244 +++++++++++----------- module/subscribe/subscribe.go | 2 +- module/team/dto/input.go | 9 +- module/team/iml.go | 9 +- module/upstream/iml.go | 18 +- plugins/core/core.go | 32 ++- plugins/core/organization.go | 22 -- plugins/core/subscribe.go | 2 +- plugins/core/upstream.go | 2 +- service/organization/iml.go | 250 ----------------------- service/organization/model.go | 35 ---- service/organization/service.go | 27 --- service/project/iml.go | 115 +---------- service/project/model.go | 59 +++--- service/project/service.go | 11 - service/service/iml.go | 25 ++- service/service/model.go | 67 +++---- service/subscribe/iml.go | 42 ++-- service/subscribe/model.go | 105 ++++------ service/subscribe/service.go | 2 +- service/team/iml.go | 19 +- service/team/model.go | 34 ++-- stores/dynamic-module/model.go | 7 +- stores/organization/model.go | 43 ---- stores/organization/store.go | 30 --- stores/project/model.go | 40 ++-- stores/project/store.go | 11 - stores/service/model.go | 33 ++- stores/subscribe/model.go | 33 ++- stores/team/model.go | 22 +- 59 files changed, 778 insertions(+), 1865 deletions(-) delete mode 100644 controller/organization/iml.go delete mode 100644 controller/organization/organization.go delete mode 100644 module/organization/dto/input.go delete mode 100644 module/organization/dto/output.go delete mode 100644 module/organization/iml.go delete mode 100644 module/organization/organization.go delete mode 100644 plugins/core/organization.go delete mode 100644 service/organization/iml.go delete mode 100644 service/organization/model.go delete mode 100644 service/organization/service.go delete mode 100644 stores/organization/model.go delete mode 100644 stores/organization/store.go diff --git a/controller/api/iml.go b/controller/api/iml.go index e6ae143..403e3f4 100644 --- a/controller/api/iml.go +++ b/controller/api/iml.go @@ -13,7 +13,7 @@ type imlAPIController struct { } func (i *imlAPIController) SimpleList(ctx *gin.Context, partitionId string, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) { - return i.module.SimpleList(ctx, partitionId, input) + return i.module.SimpleList(ctx, input) } func (i *imlAPIController) Detail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiDetail, error) { diff --git a/controller/organization/iml.go b/controller/organization/iml.go deleted file mode 100644 index e63d274..0000000 --- a/controller/organization/iml.go +++ /dev/null @@ -1,44 +0,0 @@ -package organization - -import ( - "github.com/eolinker/apipark/module/organization" - organization_dto "github.com/eolinker/apipark/module/organization/dto" - "github.com/gin-gonic/gin" -) - -var ( - _ IOrganizationController = (*imlOrganizationController)(nil) -) - -type imlOrganizationController struct { - module organization.IOrganizationModule `autowired:""` -} - -func (c *imlOrganizationController) Simple(ctx *gin.Context) ([]*organization_dto.Simple, error) { - return c.module.Simple(ctx) - -} - -func (c *imlOrganizationController) Create(ctx *gin.Context, input *organization_dto.CreateOrganization) (*organization_dto.Detail, error) { - return c.module.Create(ctx, input) -} - -func (c *imlOrganizationController) Edit(ctx *gin.Context, id string, input *organization_dto.EditOrganization) (*organization_dto.Detail, error) { - return c.module.Edit(ctx, id, input) -} - -func (c *imlOrganizationController) Get(ctx *gin.Context, id string) (*organization_dto.Detail, error) { - return c.module.Get(ctx, id) -} - -func (c *imlOrganizationController) Search(ctx *gin.Context, keyword string) ([]*organization_dto.Item, error) { - return c.module.Search(ctx, keyword) -} - -func (c *imlOrganizationController) Delete(ctx *gin.Context, id string) (string, error) { - return c.module.Delete(ctx, id) -} - -func (c *imlOrganizationController) Partitions(ctx *gin.Context, id string) ([]*organization_dto.Partition, error) { - return c.module.Partitions(ctx, id) -} diff --git a/controller/organization/organization.go b/controller/organization/organization.go deleted file mode 100644 index 4af2a81..0000000 --- a/controller/organization/organization.go +++ /dev/null @@ -1,24 +0,0 @@ -package organization - -import ( - organization_dto "github.com/eolinker/apipark/module/organization/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -type IOrganizationController interface { - Create(ctx *gin.Context, input *organization_dto.CreateOrganization) (*organization_dto.Detail, error) - Edit(ctx *gin.Context, id string, input *organization_dto.EditOrganization) (*organization_dto.Detail, error) - Get(ctx *gin.Context, id string) (*organization_dto.Detail, error) - Search(ctx *gin.Context, keyword string) ([]*organization_dto.Item, error) - Delete(ctx *gin.Context, id string) (string, error) - Partitions(ctx *gin.Context, id string) ([]*organization_dto.Partition, error) - Simple(ctx *gin.Context) ([]*organization_dto.Simple, error) -} - -func init() { - autowire.Auto[IOrganizationController](func() reflect.Value { - return reflect.ValueOf(new(imlOrganizationController)) - }) -} diff --git a/controller/project/iml.go b/controller/project/iml.go index 9c56152..a617a77 100644 --- a/controller/project/iml.go +++ b/controller/project/iml.go @@ -21,7 +21,7 @@ func (i *imlProjectController) SearchMyProjects(ctx *gin.Context, teamId string, } func (i *imlProjectController) SimpleProjects(ctx *gin.Context, keyword string, partition string) ([]*project_dto.SimpleProjectItem, error) { - return i.module.SimpleProjects(ctx, keyword, partition) + return i.module.SimpleProjects(ctx, keyword) } func (i *imlProjectController) MySimpleProjects(ctx *gin.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { diff --git a/controller/subscribe/iml.go b/controller/subscribe/iml.go index 2d3324b..ff9da18 100644 --- a/controller/subscribe/iml.go +++ b/controller/subscribe/iml.go @@ -2,6 +2,7 @@ package subscribe import ( "fmt" + "github.com/gin-gonic/gin" "github.com/eolinker/apipark/module/subscribe" @@ -16,9 +17,9 @@ type imlSubscribeController struct { module subscribe.ISubscribeModule `autowired:""` } -func (i *imlSubscribeController) PartitionServices(ctx *gin.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) { - return i.module.PartitionServices(ctx, app) -} +//func (i *imlSubscribeController) PartitionServices(ctx *gin.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) { +// return i.module.PartitionServices(ctx, app) +//} func (i *imlSubscribeController) SearchSubscriptions(ctx *gin.Context, partitionId string, projectId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { return i.module.SearchSubscriptions(ctx, partitionId, projectId, keyword) diff --git a/controller/subscribe/subscribe.go b/controller/subscribe/subscribe.go index 1b159ef..fab292f 100644 --- a/controller/subscribe/subscribe.go +++ b/controller/subscribe/subscribe.go @@ -1,9 +1,10 @@ package subscribe import ( - "github.com/gin-gonic/gin" "reflect" + "github.com/gin-gonic/gin" + subscribe_dto "github.com/eolinker/apipark/module/subscribe/dto" "github.com/eolinker/go-common/autowire" @@ -24,7 +25,7 @@ type ISubscribeController interface { DeleteSubscription(ctx *gin.Context, project string, uuid string) error // RevokeApply 取消申请 RevokeApply(ctx *gin.Context, project string, uuid string) error - PartitionServices(ctx *gin.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) + //PartitionServices(ctx *gin.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) } type ISubscribeApprovalController interface { diff --git a/controller/upstream/iml.go b/controller/upstream/iml.go index 3f960d6..96416aa 100644 --- a/controller/upstream/iml.go +++ b/controller/upstream/iml.go @@ -2,7 +2,6 @@ package upstream import ( "github.com/eolinker/apipark/module/partition" - partition_dto "github.com/eolinker/apipark/module/partition/dto" "github.com/eolinker/apipark/module/project" "github.com/eolinker/apipark/module/upstream" upstream_dto "github.com/eolinker/apipark/module/upstream/dto" @@ -19,24 +18,8 @@ type imlUpstreamController struct { partitionModule partition.IPartitionModule `autowired:""` } -func (i *imlUpstreamController) Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, []*partition_dto.Simple, error) { - info, err := i.upstreamModule.Get(ctx, pid) - if err != nil { - return nil, nil, err - } - projectInfo, err := i.projectModule.GetProject(ctx, pid) - if err != nil { - return nil, nil, err - } - ids := make([]string, 0) - for _, p := range projectInfo.Partition { - ids = append(ids, p.Id) - } - items, err := i.partitionModule.SimpleByIds(ctx, ids) - if err != nil { - return nil, nil, err - } - return info, items, nil +func (i *imlUpstreamController) Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, error) { + return i.upstreamModule.Get(ctx, pid) } func (i *imlUpstreamController) Save(ctx *gin.Context, pid string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { diff --git a/controller/upstream/upstream.go b/controller/upstream/upstream.go index 89e14a9..122582d 100644 --- a/controller/upstream/upstream.go +++ b/controller/upstream/upstream.go @@ -1,7 +1,6 @@ package upstream import ( - partition_dto "github.com/eolinker/apipark/module/partition/dto" "reflect" "github.com/eolinker/go-common/autowire" @@ -11,7 +10,7 @@ import ( ) type IUpstreamController interface { - Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, []*partition_dto.Simple, error) + Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, error) Save(ctx *gin.Context, pid string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) } diff --git a/module/api/api.go b/module/api/api.go index 754c3c9..524d471 100644 --- a/module/api/api.go +++ b/module/api/api.go @@ -18,7 +18,7 @@ type IApiModule interface { Search(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiItem, error) // SimpleSearch 获取API简要列表 SimpleSearch(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiSimpleItem, error) - SimpleList(ctx context.Context, partitionId string, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) + SimpleList(ctx context.Context, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) // Create 创建API Create(ctx context.Context, pid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // Edit 编辑API diff --git a/module/api/iml.go b/module/api/iml.go index bd7eb36..d56df96 100644 --- a/module/api/iml.go +++ b/module/api/iml.go @@ -11,7 +11,6 @@ import ( "gorm.io/gorm" - "github.com/eolinker/apipark/service/organization" "github.com/eolinker/apipark/service/team" "github.com/google/uuid" @@ -36,26 +35,15 @@ var ( ) type imlApiModule struct { - organizationService organization.IOrganizationService `autowired:""` - teamService team.ITeamService `autowired:""` - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - apiService api.IAPIService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - transaction store.ITransaction `autowired:""` + teamService team.ITeamService `autowired:""` + projectService project.IProjectService `autowired:""` + apiService api.IAPIService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + transaction store.ITransaction `autowired:""` } -func (i *imlApiModule) SimpleList(ctx context.Context, partitionId string, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) { +func (i *imlApiModule) SimpleList(ctx context.Context, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) { projectIds := input.Projects - if partitionId != "" { - pp, err := i.projectPartitionService.ListByPartition(ctx, partitionId) - if err != nil { - return nil, err - } - projectIds = utils.SliceToSlice(pp, func(p *project.Partition) string { - return p.Project - }) - } w := make(map[string]interface{}) if len(projectIds) > 0 { w["project"] = projectIds @@ -455,23 +443,11 @@ func (i *imlApiModule) Prefix(ctx context.Context, pid string) (string, error) { if err != nil { return "", err } - tInfo, err := i.teamService.Get(ctx, pInfo.Team) - if err != nil { - return "", err - } - oInfo, err := i.organizationService.Get(ctx, tInfo.Organization) - if err != nil { - return "", err - } - if oInfo.Prefix != "" { - if oInfo.Prefix[0] != '/' { - oInfo.Prefix = fmt.Sprintf("/%s", strings.TrimSuffix(oInfo.Prefix, "/")) - } - } + if pInfo.Prefix != "" { if pInfo.Prefix[0] != '/' { pInfo.Prefix = fmt.Sprintf("/%s", strings.TrimSuffix(pInfo.Prefix, "/")) } } - return strings.TrimSuffix(fmt.Sprintf("%s%s", oInfo.Prefix, pInfo.Prefix), "/"), nil + return strings.TrimSuffix(pInfo.Prefix, "/"), nil } diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index 83fdd87..c2c1767 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -9,15 +9,15 @@ type Item struct { } type ServiceItem struct { - Id string `json:"id"` - Name string `json:"name"` - Tags []auto.Label `json:"tags" aolabel:"tag"` - Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` - Partition []auto.Label `json:"partition" aolabel:"partition"` - Description string `json:"description"` - Logo string `json:"logo"` - ApiNum int64 `json:"api_num"` - SubscriberNum int64 `json:"subscriber_num"` + Id string `json:"id"` + Name string `json:"name"` + Tags []auto.Label `json:"tags" aolabel:"tag"` + Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` + //Partition []auto.Label `json:"partition" aolabel:"partition"` + Description string `json:"description"` + Logo string `json:"logo"` + ApiNum int64 `json:"api_num"` + SubscriberNum int64 `json:"subscriber_num"` } type ServiceDetail struct { @@ -31,7 +31,7 @@ type ServiceDetail struct { } type ServiceBasic struct { - Organization auto.Label `json:"organization" aolabel:"organization"` + //Organization auto.Label `json:"organization" aolabel:"organization"` Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` ApiNum int `json:"api_num"` diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index 8413369..af1933e 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -42,21 +42,20 @@ var ( ) type imlCatalogueModule struct { - catalogueService catalogue.ICatalogueService `autowired:""` - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - apiService api.IAPIService `autowired:""` - serviceService service.IServiceService `autowired:""` - serviceApiService service.IApiService `autowired:""` - serviceTagService service.ITagService `autowired:""` - servicePartitionService service.IPartitionsService `autowired:""` - serviceDocService service.IDocService `autowired:""` - tagService tag.ITagService `autowired:""` - releaseService release.IReleaseService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - transaction store.ITransaction `autowired:""` + catalogueService catalogue.ICatalogueService `autowired:""` + projectService project.IProjectService `autowired:""` + apiService api.IAPIService `autowired:""` + serviceService service.IServiceService `autowired:""` + serviceApiService service.IApiService `autowired:""` + serviceTagService service.ITagService `autowired:""` + servicePartitionService service.IPartitionsService `autowired:""` + serviceDocService service.IDocService `autowired:""` + tagService tag.ITagService `autowired:""` + releaseService release.IReleaseService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + transaction store.ITransaction `autowired:""` root *Root } @@ -70,31 +69,10 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal if err != nil { return fmt.Errorf("get service failed: %w", err) } - // 获取服务可用分区 - servicePartitions, err := i.servicePartitionService.PartitionsByService(ctx, subscribeInfo.Service) - if err != nil { - return fmt.Errorf("get service partitions failed: %w", err) - } - partitions, has := servicePartitions[subscribeInfo.Service] - if !has || len(partitions) == 0 { - // 没有可用分区,不给申请 - return fmt.Errorf("service has no available partitions") - } - partitionMap := utils.SliceToMapO(partitions, func(t string) (string, struct{}) { - return t, struct{}{} - }) userId := utils.UserId(ctx) return i.transaction.Transaction(ctx, func(ctx context.Context) error { - availablePartitions := make([]string, 0, len(subscribeInfo.Partitions)) - for _, p := range subscribeInfo.Partitions { - if _, has := partitionMap[p]; has { - availablePartitions = append(availablePartitions, p) - } - } - if len(availablePartitions) == 0 { - return fmt.Errorf("service has no available partitions") - } + projects := make([]string, 0, len(subscribeInfo.Applications)) for _, pid := range subscribeInfo.Applications { @@ -114,18 +92,15 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal applyID := uuid.New().String() // 创建一条审核申请 err = i.subscribeApplyService.Create(ctx, &subscribe.CreateApply{ - Uuid: applyID, - Service: subscribeInfo.Service, - Project: s.Project, - Team: s.Team, - ApplyPartitions: availablePartitions, - Application: pid, - ApplyTeam: pInfo.Team, - ApplyOrganization: pInfo.Organization, - Reason: subscribeInfo.Reason, - Organization: s.Organization, - Status: subscribe.ApplyStatusReview, - Applier: userId, + Uuid: applyID, + Service: subscribeInfo.Service, + Project: s.Project, + Team: s.Team, + Application: pid, + ApplyTeam: pInfo.Team, + Reason: subscribeInfo.Reason, + Status: subscribe.ApplyStatusReview, + Applier: userId, }) if err != nil { return err @@ -136,12 +111,28 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal if !errors.Is(err, gorm.ErrRecordNotFound) { return err } - for _, p := range availablePartitions { + err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ + Uuid: uuid.New().String(), + Service: subscribeInfo.Service, + Project: s.Project, + Application: pid, + ApplyStatus: subscribe.ApplyStatusReview, + From: subscribe.FromSubscribe, + }) + if err != nil { + return err + } + + } else { + subscriberMap := utils.SliceToMap(subscriber, func(t *subscribe.Subscribe) string { + return t.Application + }) + v, has := subscriberMap[pid] + if !has { err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ Uuid: uuid.New().String(), Service: subscribeInfo.Service, Project: s.Project, - Partition: p, Application: pid, ApplyStatus: subscribe.ApplyStatusReview, From: subscribe.FromSubscribe, @@ -149,37 +140,13 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal if err != nil { return err } + } else if v.ApplyStatus != subscribe.ApplyStatusSubscribe { + status := subscribe.ApplyStatusReview + err = i.subscribeService.Save(ctx, v.Id, &subscribe.UpdateSubscribe{ + ApplyStatus: &status, + }) } - if err != nil { - return err - } - } else { - subscriberMap := utils.SliceToMap(subscriber, func(t *subscribe.Subscribe) string { - return t.Partition - }) - for _, p := range availablePartitions { - v, has := subscriberMap[p] - if !has { - err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ - Uuid: uuid.New().String(), - Service: subscribeInfo.Service, - Project: s.Project, - Partition: p, - Application: pid, - ApplyStatus: subscribe.ApplyStatusReview, - From: subscribe.FromSubscribe, - }) - if err != nil { - return err - } - } else if v.ApplyStatus != subscribe.ApplyStatusSubscribe { - status := subscribe.ApplyStatusReview - err = i.subscribeService.Save(ctx, v.Id, &subscribe.UpdateSubscribe{ - ApplyStatus: &status, - }) - } - } } projects = append(projects, pid) @@ -207,27 +174,8 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca } else { docStr = doc.Doc } - servicePartitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return nil, fmt.Errorf("get service partitions failed: %w", err) - } - servicePartitionIds := utils.SliceToSlice(servicePartitions, func(t *service.Partition) string { - return t.Pid - }) - projectPartitions, err := i.projectPartitionService.ListByProject(ctx, s.Project) - if err != nil { - return nil, err - } - projectPartitionIds := utils.SliceToSlice(projectPartitions, func(t *project.Partition) string { - return t.Partition - }) - - partitionIds := utils.Intersection(servicePartitionIds, projectPartitionIds) - if len(partitionIds) == 0 { - return nil, fmt.Errorf("no partition") - } - globalPartitions, err := i.partitionService.List(ctx, partitionIds...) + globalPartitions, err := i.partitionService.List(ctx) if err != nil { return nil, err } @@ -247,10 +195,9 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Description: s.Description, Document: docStr, Basic: &catalogue_dto.ServiceBasic{ - Organization: auto.UUID(s.Organization), - Project: auto.UUID(s.Project), - Team: auto.UUID(s.Team), - ApiNum: 0, + Project: auto.UUID(s.Project), + Team: auto.UUID(s.Team), + ApiNum: 0, }, Partition: partitions, }, nil @@ -330,7 +277,6 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Description: s.Description, Document: docStr, Basic: &catalogue_dto.ServiceBasic{ - Organization: auto.UUID(s.Organization), Project: auto.UUID(s.Project), Team: auto.UUID(s.Team), ApiNum: len(apis), @@ -342,13 +288,7 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca } func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*catalogue_dto.ServiceItem, error) { - projectPartitions, err := i.projectPartitionService.ListByProject(ctx) - if err != nil { - return nil, err - } - projectPartitionMap := utils.SliceToMapArrayO(projectPartitions, func(t *project.Partition) (string, string) { - return t.Project, t.Partition - }) + serviceTags, err := i.serviceTagService.List(ctx, nil, nil) if err != nil { return nil, err @@ -356,10 +296,6 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c serviceTagMap := utils.SliceToMapArrayO(serviceTags, func(t *service.Tag) (string, string) { return t.Sid, t.Tid }) - servicePartitionMap, err := i.servicePartitionService.PartitionsByService(ctx) - if err != nil { - return nil, err - } items, err := i.serviceService.Search(ctx, keyword, nil) if err != nil { @@ -391,16 +327,16 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c if !ok || apiNum < 1 { continue } - ps := utils.Intersection(servicePartitionMap[v.Id], projectPartitionMap[v.Project]) - if len(ps) < 1 { - continue - } + //ps := utils.Intersection(servicePartitionMap[v.Id], projectPartitionMap[v.Project]) + //if len(ps) < 1 { + // continue + //} result = append(result, &catalogue_dto.ServiceItem{ - Id: v.Id, - Name: v.Name, - Tags: auto.List(serviceTagMap[v.Id]), - Catalogue: auto.UUID(v.Catalogue), - Partition: auto.List(ps), + Id: v.Id, + Name: v.Name, + Tags: auto.List(serviceTagMap[v.Id]), + Catalogue: auto.UUID(v.Catalogue), + //Partition: auto.List(ps), ApiNum: apiNum, SubscriberNum: subscribeCount[v.Id], Description: v.Description, diff --git a/module/my-team/iml.go b/module/my-team/iml.go index 7f3da14..b2fe2aa 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -4,12 +4,11 @@ import ( "context" "errors" "fmt" + "gorm.io/gorm" "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/apipark/service/organization" - "github.com/eolinker/apipark/service/project" department_member "github.com/eolinker/ap-account/service/department-member" @@ -39,7 +38,6 @@ type imlTeamModule struct { userService user.IUserService `autowired:""` departmentMemberService department_member.IMemberService `autowired:""` projectService project.IProjectService `autowired:""` - organizationService organization.IOrganizationService `autowired:""` partitionService partition.IPartitionService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -49,10 +47,10 @@ func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, if err != nil { return nil, err } - availablePartitions, err := m.organizationService.Partitions(ctx, tv.Organization) - if err != nil { - return nil, err - } + //availablePartitions, err := m.organizationService.Partitions(ctx, tv.Organization) + //if err != nil { + // return nil, err + //} globalPartitions, err := m.partitionService.List(ctx) if err != nil { return nil, err @@ -60,20 +58,20 @@ func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, globalPartitionMap := utils.SliceToMapO(globalPartitions, func(p *partition.Partition) (string, struct{}) { return p.UUID, struct{}{} }) - for _, p := range availablePartitions { - delete(globalPartitionMap, p) - } + //for _, p := range availablePartitions { + // delete(globalPartitionMap, p) + //} return &team_dto.Team{ - Id: tv.Id, - Name: tv.Name, - Description: tv.Description, - Master: auto.UUID(tv.Master), - CreateTime: auto.TimeLabel(tv.CreateTime), - UpdateTime: auto.TimeLabel(tv.UpdateTime), - Organization: auto.UUID(tv.Organization), - Creator: auto.UUID(tv.Creator), - Updater: auto.UUID(tv.Updater), - AvailablePartitions: auto.List(availablePartitions), + Id: tv.Id, + Name: tv.Name, + Description: tv.Description, + Master: auto.UUID(tv.Master), + CreateTime: auto.TimeLabel(tv.CreateTime), + UpdateTime: auto.TimeLabel(tv.UpdateTime), + Organization: auto.UUID(tv.Organization), + Creator: auto.UUID(tv.Creator), + Updater: auto.UUID(tv.Updater), + //AvailablePartitions: auto.List(availablePartitions), DisablePartitions: auto.List(utils.MapToSlice(globalPartitionMap, func(k string, v struct{}) string { return k })), @@ -152,10 +150,10 @@ func (m *imlTeamModule) SimpleTeams(ctx context.Context, keyword string) ([]*tea if err != nil { return nil, err } - partitionMap, err := m.organizationService.PartitionsByOrganization(ctx) - if err != nil { - return nil, err - } + //partitionMap, err := m.organizationService.PartitionsByOrganization(ctx) + //if err != nil { + // return nil, err + //} globalPartitions, err := m.partitionService.List(ctx) if err != nil { return nil, err @@ -177,16 +175,16 @@ func (m *imlTeamModule) SimpleTeams(ctx context.Context, keyword string) ([]*tea globalPartitionMap := utils.SliceToMapO(globalPartitions, func(p *partition.Partition) (string, struct{}) { return p.UUID, struct{}{} }) - availablePartitions := partitionMap[s.Organization] - for _, p := range availablePartitions { - delete(globalPartitionMap, p) - } + //availablePartitions := partitionMap[s.Organization] + //for _, p := range availablePartitions { + // delete(globalPartitionMap, p) + //} return &team_dto.SimpleTeam{ - Id: s.Id, - Name: s.Name, - Description: s.Description, - Organization: auto.UUID(s.Organization), - AvailablePartitions: auto.List(availablePartitions), + Id: s.Id, + Name: s.Name, + Description: s.Description, + Organization: auto.UUID(s.Organization), + //AvailablePartitions: auto.List(availablePartitions), DisablePartitions: auto.List(utils.MapToSlice(globalPartitionMap, func(k string, v struct{}) string { return k })), diff --git a/module/organization/dto/input.go b/module/organization/dto/input.go deleted file mode 100644 index c8472fa..0000000 --- a/module/organization/dto/input.go +++ /dev/null @@ -1,18 +0,0 @@ -package organization_dto - -type CreateOrganization struct { - Id string `json:"id,omitempty"` // Id is the UUID of the organization - Name string `json:"name,omitempty"` // Name is the name of the organization - Description string `json:"description,omitempty"` // Description is the description of the organization - Master string `json:"master,omitempty"` // Master is the UUID of the organization's master partition - Partitions []string `json:"partitions,omitempty"` // Partition is the list of the organization's partition UUID - Prefix string `json:"prefix,omitempty"` // Prefix is the prefix of the organization's UUID -} - -type EditOrganization struct { - Name *string `json:"name,omitempty"` // Name is the name of the organization - Description *string `json:"description,omitempty"` // Description is the description of the organization - Master *string `json:"master,omitempty"` // Master is the UUID of the organization's master partition - Partitions *[]string `json:"partitions,omitempty"` // Partition is the - Prefix *string `json:"prefix,omitempty"` // Prefix is the prefix of the organization's UUID -} diff --git a/module/organization/dto/output.go b/module/organization/dto/output.go deleted file mode 100644 index 1185145..0000000 --- a/module/organization/dto/output.go +++ /dev/null @@ -1,58 +0,0 @@ -package organization_dto - -import ( - "github.com/eolinker/apipark/service/organization" - "github.com/eolinker/go-common/auto" -) - -type Item struct { - Id string `json:"id,omitempty"` // Id is the UUID of the organization - Name string `json:"name,omitempty"` // Name is the name of the organization - Description string `json:"description,omitempty"` // Description is the description of the organization - Master auto.Label `json:"master,omitempty" aolabel:"user"` // Master is the UUID of the organization's master partition - Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` // Partition is the list of the organization's partition UUID - Prefix string `json:"prefix,omitempty"` // Prefix is the prefix of the organization's UUID - CreateTime auto.TimeLabel `json:"create_time,omitempty"` // CreateTime is the time when the organization was created - UpdateTime auto.TimeLabel `json:"update_time,omitempty"` // UpdateTime is the time when the organization was updated - Updater auto.Label `json:"updater,omitempty" aolabel:"user"` // - Creator auto.Label `json:"creator,omitempty" aolabel:"user"` - CanDelete bool `json:"can_delete"` -} - -type Detail struct { - Id string `json:"id"` // - Name string `json:"name"` // - Description string `json:"description"` // - Master auto.Label `json:"master" aolabel:"user"` // - Prefix string `json:"prefix"` // - Updater auto.Label `json:"updater" aolabel:"user"` // - Creator auto.Label `json:"creator" aolabel:"user"` // - CreateTime auto.TimeLabel `json:"create_time"` // - UpdateTime auto.TimeLabel `json:"update_time"` // - Partitions []auto.Label `json:"partitions" aolabel:"partition"` // -} - -func NewDetail(m *organization.Organization) *Detail { - return &Detail{ - Id: m.UUID, - Name: m.Name, - Description: m.Description, - Master: auto.UUID(m.Master), - Prefix: m.Prefix, - Updater: auto.UUID(m.Updater), - Creator: auto.UUID(m.Creator), - CreateTime: auto.TimeLabel(m.CreateTime), - UpdateTime: auto.TimeLabel(m.UpdateTime), - Partitions: auto.List(m.Partitions), - } -} - -type Partition struct { - Id string `json:"id,omitempty"` // - Name string `json:"name,omitempty"` // -} - -type Simple struct { - Id string `json:"id,omitempty"` // - Name string `json:"name,omitempty"` // -} diff --git a/module/organization/iml.go b/module/organization/iml.go deleted file mode 100644 index f06b135..0000000 --- a/module/organization/iml.go +++ /dev/null @@ -1,125 +0,0 @@ -package organization - -import ( - "context" - "strings" - - "github.com/eolinker/apipark/service/team" - - organization_dto "github.com/eolinker/apipark/module/organization/dto" - "github.com/eolinker/apipark/service/organization" - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/utils" - "github.com/google/uuid" -) - -var ( - _ IOrganizationModule = (*implOrganizationModule)(nil) -) - -type implOrganizationModule struct { - organizationService organization.IOrganizationService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - teamService team.ITeamService `autowired:""` -} - -func (m *implOrganizationModule) Simple(ctx context.Context) ([]*organization_dto.Simple, error) { - list, err := m.organizationService.All(ctx) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(i *organization.Organization) *organization_dto.Simple { - return &organization_dto.Simple{ - Id: i.UUID, - Name: i.Name, - } - }), nil -} - -func (m *implOrganizationModule) Create(ctx context.Context, input *organization_dto.CreateOrganization) (*organization_dto.Detail, error) { - id := input.Id - if id == "" { - id = uuid.NewString() - } - input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") - o, err := m.organizationService.Create(ctx, id, input.Name, input.Description, input.Prefix, input.Master, input.Partitions) - if err != nil { - return nil, err - } - detail := organization_dto.NewDetail(o) - return detail, nil -} - -func (m *implOrganizationModule) Edit(ctx context.Context, id string, input *organization_dto.EditOrganization) (*organization_dto.Detail, error) { - nv, err := m.organizationService.Edit(ctx, id, input.Name, input.Description, input.Master, input.Partitions) - if err != nil { - return nil, err - } - detail := organization_dto.NewDetail(nv) - - return detail, nil -} - -func (m *implOrganizationModule) Get(ctx context.Context, id string) (*organization_dto.Detail, error) { - v, err := m.organizationService.Get(ctx, id) - if err != nil { - return nil, err - } - detail := organization_dto.NewDetail(v) - - return detail, nil -} - -func (m *implOrganizationModule) Search(ctx context.Context, keyword string) ([]*organization_dto.Item, error) { - list, err := m.organizationService.Search(ctx, keyword) - if err != nil { - return nil, err - } - countMap, err := m.teamService.CountByGroup(ctx, "", nil, "organization") - if err != nil { - return nil, err - } - itemList := utils.SliceToSlice(list, func(o *organization.Organization) *organization_dto.Item { - return &organization_dto.Item{ - Id: o.UUID, - Name: o.Name, - Description: o.Description, - Master: auto.UUID(o.Master), - Partition: auto.List(o.Partitions), - Prefix: o.Prefix, - CreateTime: auto.TimeLabel(o.CreateTime), - UpdateTime: auto.TimeLabel(o.UpdateTime), - Updater: auto.UUID(o.Updater), - Creator: auto.UUID(o.Creator), - CanDelete: countMap[o.UUID] == 0, - } - }) - return itemList, nil -} - -func (m *implOrganizationModule) Delete(ctx context.Context, id string) (string, error) { - err := m.organizationService.Delete(ctx, id) - if err != nil { - return "", err - } - return id, nil -} - -func (m *implOrganizationModule) Partitions(ctx context.Context, id string) ([]*organization_dto.Partition, error) { - partitions, err := m.organizationService.Partitions(ctx, id) - if err != nil { - return nil, err - } - list, err := m.partitionService.List(ctx, partitions...) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(p *partition.Partition) *organization_dto.Partition { - return &organization_dto.Partition{ - Id: p.UUID, - Name: p.Name, - } - }), nil - -} diff --git a/module/organization/organization.go b/module/organization/organization.go deleted file mode 100644 index 3219652..0000000 --- a/module/organization/organization.go +++ /dev/null @@ -1,24 +0,0 @@ -package organization - -import ( - "context" - organization_dto "github.com/eolinker/apipark/module/organization/dto" - "github.com/eolinker/go-common/autowire" - "reflect" -) - -type IOrganizationModule interface { - Create(ctx context.Context, input *organization_dto.CreateOrganization) (*organization_dto.Detail, error) - Edit(ctx context.Context, id string, input *organization_dto.EditOrganization) (*organization_dto.Detail, error) - Get(ctx context.Context, id string) (*organization_dto.Detail, error) - Search(ctx context.Context, keyword string) ([]*organization_dto.Item, error) - Delete(ctx context.Context, id string) (string, error) - Simple(ctx context.Context) ([]*organization_dto.Simple, error) - Partitions(ctx context.Context, id string) ([]*organization_dto.Partition, error) -} - -func init() { - autowire.Auto[IOrganizationModule](func() reflect.Value { - return reflect.ValueOf(new(implOrganizationModule)) - }) -} diff --git a/module/partition/impl.go b/module/partition/impl.go index 725025c..f312695 100644 --- a/module/partition/impl.go +++ b/module/partition/impl.go @@ -4,19 +4,19 @@ import ( "context" "errors" "fmt" + "strings" + "github.com/eolinker/apipark/gateway/admin" - "github.com/eolinker/apipark/service/organization" "github.com/eolinker/eosc/log" - "strings" - + "github.com/eolinker/go-common/store" - + "github.com/eolinker/apipark/gateway" - + "gorm.io/gorm" - + "github.com/google/uuid" - + "github.com/eolinker/ap-account/service/account" paritiondto "github.com/eolinker/apipark/module/partition/dto" "github.com/eolinker/apipark/service/cluster" @@ -30,10 +30,10 @@ var ( ) type imlPartition struct { - partitionService partition.IPartitionService `autowired:""` - organizationService organization.IOrganizationService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - userNameService account.IAccountService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + //organizationService organization.IOrganizationService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + userNameService account.IAccountService `autowired:""` //monitorService monitor.IMonitorService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -53,7 +53,7 @@ func (m *imlPartition) CheckCluster(ctx context.Context, address ...string) ([]* } }) nodeStatus(ctx, nodesOut) - + return nodesOut, nil } @@ -62,7 +62,7 @@ func (m *imlPartition) ResetCluster(ctx context.Context, partitionId string, add if err != nil { return nil, err } - + nodes, err := m.clusterService.UpdateAddress(ctx, info.Cluster, address) if err != nil { return nil, err @@ -80,7 +80,7 @@ func (m *imlPartition) ResetCluster(ctx context.Context, partitionId string, add Gateways: i.Server, } }) - + nodeStatus(ctx, nodesOut) return nodesOut, nil } @@ -116,7 +116,7 @@ func (m *imlPartition) ClusterNodes(ctx context.Context, partitionId string) ([] } }) nodeStatus(ctx, nodesOut) - + return nodesOut, nil } @@ -166,7 +166,7 @@ func (m *imlPartition) Search(ctx context.Context, keyword string) ([]*paritiond return nil, err } items := utils.SliceToSlice(partitions, func(i *partition.Partition) *paritiondto.Item { - + return &paritiondto.Item{ Creator: auto.UUID(i.Creator), Updater: auto.UUID(i.Updater), @@ -187,7 +187,7 @@ func (m *imlPartition) Search(ctx context.Context, keyword string) ([]*paritiond item.ClusterNum = counts[item.Id] } } - + return items, nil } @@ -196,23 +196,23 @@ func (m *imlPartition) Get(ctx context.Context, id string) (*paritiondto.Detail, if err != nil { return nil, err } - oDetails, err := m.organizationService.Search(ctx, "") - if err != nil { - return nil, err - } - canDelete := true - for _, o := range oDetails { - for _, p := range o.Partitions { - if p == id { - canDelete = false - break - } - } - if !canDelete { - break - } - } - + //oDetails, err := m.organizationService.Search(ctx, "") + //if err != nil { + // return nil, err + //} + //canDelete := true + //for _, o := range oDetails { + // for _, p := range o.Partitions { + // if p == id { + // canDelete = false + // break + // } + // } + // if !canDelete { + // break + // } + //} + pd := &paritiondto.Detail{ Creator: auto.UUID(pm.Creator), Updater: auto.UUID(pm.Updater), @@ -222,7 +222,7 @@ func (m *imlPartition) Get(ctx context.Context, id string) (*paritiondto.Detail, Prefix: pm.Prefix, CreateTime: auto.TimeLabel(pm.CreateTime), UpdateTime: auto.TimeLabel(pm.UpdateTime), - CanDelete: canDelete, + //CanDelete: canDelete, } return pd, nil } @@ -255,7 +255,7 @@ func (m *imlPartition) Delete(ctx context.Context, id string) error { } return m.partitionService.Delete(ctx, id) }) - + } func (m *imlPartition) Simple(ctx context.Context) ([]*paritiondto.Simple, error) { @@ -286,19 +286,19 @@ func (m *imlPartition) SimpleByIds(ctx context.Context, ids []string) ([]*pariti } }) return pd, nil - + } func (m *imlPartition) SimpleWithCluster(ctx context.Context) ([]*paritiondto.SimpleWithCluster, error) { pm, err := m.partitionService.Search(ctx, "", nil) if err != nil { return nil, err } - + clusterList, err := m.clusterService.List(ctx) if err != nil { return nil, err } - + clusterMap := utils.SliceToMapArrayO(clusterList, func(i *cluster.Cluster) (string, *paritiondto.Cluster) { return i.Partition, &paritiondto.Cluster{ Id: i.Uuid, diff --git a/module/project-authorization/iml.go b/module/project-authorization/iml.go index 85009ea..155b16a 100644 --- a/module/project-authorization/iml.go +++ b/module/project-authorization/iml.go @@ -5,9 +5,12 @@ import ( "encoding/json" "errors" "fmt" - "github.com/eolinker/eosc/log" "time" + "github.com/eolinker/apipark/service/partition" + + "github.com/eolinker/eosc/log" + authDriver "github.com/eolinker/apipark/module/project-authorization/auth-driver" "github.com/eolinker/go-common/utils" @@ -33,7 +36,7 @@ var _ IProjectAuthorizationModule = (*imlProjectAuthorizationModule)(nil) type imlProjectAuthorizationModule struct { projectService project.IProjectService `autowired:""` projectAuthorizationService projectAuthorization.IProjectAuthorizationService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` + partitionService partition.IPartitionService `autowired:""` clusterService cluster.IClusterService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -80,20 +83,17 @@ func (i *imlProjectAuthorizationModule) getApplications(ctx context.Context, pro } func (i *imlProjectAuthorizationModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projectPartitions, err := i.projectPartitionService.ListByPartition(ctx, partitionId) + projects, err := i.projectService.List(ctx) if err != nil { return err } - projectIds := utils.SliceToSlice(projectPartitions, func(p *project.Partition) string { - return p.Project - }) - projects, err := i.projectService.List(ctx, projectIds...) - if err != nil { - return err + projectIds := make([]string, 0, len(projects)) + projectMap := make(map[string]*project.Project) + for _, p := range projects { + projectIds = append(projectIds, p.Id) + projectMap[p.Id] = p } - projectMap := utils.SliceToMap(projects, func(p *project.Project) string { - return p.Id - }) + applications, err := i.getApplications(ctx, projectIds, projectMap) if err != nil { return err @@ -102,10 +102,14 @@ func (i *imlProjectAuthorizationModule) initGateway(ctx context.Context, partiti } func (i *imlProjectAuthorizationModule) online(ctx context.Context, projectInfo *project.Project) error { - partitionIds, err := i.projectPartitionService.GetByProject(ctx, projectInfo.Id) + + partitions, err := i.partitionService.List(ctx) if err != nil { return err } + partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { + return p.UUID + }) clusters, err := i.clusterService.List(ctx, partitionIds...) if err != nil { return err @@ -259,15 +263,18 @@ func (i *imlProjectAuthorizationModule) DeleteAuthorization(ctx context.Context, if err != nil { return err } + partitions, err := i.partitionService.List(ctx) + if err != nil { + return err + } + partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { + return p.UUID + }) return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.projectAuthorizationService.Delete(ctx, aid) if err != nil { return err } - partitionIds, err := i.projectPartitionService.GetByProject(ctx, pid) - if err != nil { - return err - } clusters, err := i.clusterService.List(ctx, partitionIds...) if err != nil { return err diff --git a/module/project/dto/input.go b/module/project/dto/input.go index 2195016..d4445b9 100644 --- a/module/project/dto/input.go +++ b/module/project/dto/input.go @@ -12,10 +12,9 @@ type CreateProject struct { } type EditProject struct { - Name *string `json:"name"` - Description *string `json:"description"` - Master *string `json:"master" aocheck:"user"` - Partition []string `json:"partition" aocheck:"partition"` + Name *string `json:"name"` + Description *string `json:"description"` + Master *string `json:"master" aocheck:"user"` } type CreateApp struct { diff --git a/module/project/dto/output.go b/module/project/dto/output.go index a55e8c5..6fb22fd 100644 --- a/module/project/dto/output.go +++ b/module/project/dto/output.go @@ -6,19 +6,19 @@ import ( ) type ProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - ApiNum int64 `json:"api_num"` - ServiceNum int64 `json:"service_num"` + Id string `json:"id"` + Name string `json:"name"` + //Organization auto.Label `json:"organization" aolabel:"organization"` + Team auto.Label `json:"team" aolabel:"team"` + ApiNum int64 `json:"api_num"` + ServiceNum int64 `json:"service_num"` //SubscribeNum int64 `json:"subscribe_num"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` - Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - CanDelete bool `json:"can_delete"` + Description string `json:"description"` + Master auto.Label `json:"master" aolabel:"user"` + //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + CanDelete bool `json:"can_delete"` } type AppItem struct { @@ -34,12 +34,12 @@ type AppItem struct { } type SimpleProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - Description string `json:"description"` + Id string `json:"id"` + Name string `json:"name"` + //Organization auto.Label `json:"organization" aolabel:"organization"` + Team auto.Label `json:"team" aolabel:"team"` + //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` + Description string `json:"description"` } type SimpleAppItem struct { @@ -50,19 +50,19 @@ type SimpleAppItem struct { } type Project struct { - Id string `json:"id"` - Name string `json:"name"` - Prefix string `json:"prefix,omitempty"` - Description string `json:"description"` - Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - Master auto.Label `json:"master" aolabel:"user"` - Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - OrganizationPrefix string `json:"organization_prefix,omitempty"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - AsServer bool `json:"as_server"` - AsApp bool `json:"as_app"` + Id string `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix,omitempty"` + Description string `json:"description"` + //Organization auto.Label `json:"organization" aolabel:"organization"` + Team auto.Label `json:"team" aolabel:"team"` + Master auto.Label `json:"master" aolabel:"user"` + //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` + //OrganizationPrefix string `json:"organization_prefix,omitempty"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + AsServer bool `json:"as_server"` + AsApp bool `json:"as_app"` } type App struct { @@ -75,21 +75,18 @@ type App struct { AsApp bool `json:"as_app"` } -func ToProject(model *project.Project, organization string, organizationPrefix string, partitions []string) *Project { +func ToProject(model *project.Project) *Project { return &Project{ - Id: model.Id, - Name: model.Name, - Prefix: model.Prefix, - Description: model.Description, - Organization: auto.UUID(organization), - Team: auto.UUID(model.Team), - Master: auto.UUID(model.Master), - Partition: auto.List(partitions), - OrganizationPrefix: organizationPrefix, - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - AsServer: model.AsServer, - AsApp: model.AsApp, + Id: model.Id, + Name: model.Name, + Prefix: model.Prefix, + Description: model.Description, + Team: auto.UUID(model.Team), + Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + AsServer: model.AsServer, + AsApp: model.AsApp, } } diff --git a/module/project/iml.go b/module/project/iml.go index 965b608..e9903c5 100644 --- a/module/project/iml.go +++ b/module/project/iml.go @@ -4,11 +4,14 @@ import ( "context" "errors" "fmt" - "github.com/eolinker/apipark/service/subscribe" - "gorm.io/gorm" "sort" "strings" + "github.com/eolinker/apipark/service/partition" + + "github.com/eolinker/apipark/service/subscribe" + "gorm.io/gorm" + "github.com/eolinker/ap-account/service/member" "github.com/eolinker/apipark/service/api" @@ -21,8 +24,6 @@ import ( "github.com/eolinker/go-common/auto" - "github.com/eolinker/apipark/service/organization" - team_member "github.com/eolinker/apipark/service/team-member" project_member "github.com/eolinker/apipark/service/project-member" @@ -45,15 +46,14 @@ var ( ) type imlProjectModule struct { - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - projectMemberService project_member.IMemberService `autowired:""` - teamService team.ITeamService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - organizationService organization.IOrganizationService `autowired:""` - serviceService service.IServiceService `autowired:""` - apiService api.IAPIService `autowired:""` - transaction store.ITransaction `autowired:""` + partitionService partition.IPartitionService `autowired:""` + projectService project.IProjectService `autowired:""` + projectMemberService project_member.IMemberService `autowired:""` + teamService team.ITeamService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + serviceService service.IServiceService `autowired:""` + apiService api.IAPIService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlProjectModule) searchMyProjects(ctx context.Context, teamId string, keyword string) ([]*project.Project, error) { @@ -96,13 +96,7 @@ func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, if err != nil { return nil, err } - partitions, err := i.projectPartitionService.ListByProject(ctx, projectIDs...) - if err != nil { - return nil, err - } - partitionMap := utils.SliceToMapArrayO(partitions, func(p *project.Partition) (string, string) { - return p.Project, p.Partition - }) + items := make([]*project_dto.ProjectItem, 0, len(projects)) for _, model := range projects { if teamId != "" && model.Team != teamId { @@ -111,18 +105,16 @@ func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, apiCount := apiCountMap[model.Id] serviceCount := serviceCountMap[model.Id] items = append(items, &project_dto.ProjectItem{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - Partition: auto.List(partitionMap[model.Id]), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + Id: model.Id, + Name: model.Name, + Description: model.Description, + Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + ServiceNum: serviceCount, + CanDelete: apiCount == 0 && serviceCount == 0, }) } return items, nil @@ -141,49 +133,36 @@ func (i *imlProjectModule) SimpleAPPS(ctx context.Context, keyword string) ([]*p Name: p.Name, Description: p.Description, - Organization: auto.UUID(p.Organization), - Team: auto.UUID(p.Team), + Team: auto.UUID(p.Team), } }), nil } -func (i *imlProjectModule) SimpleProjects(ctx context.Context, keyword string, partition string) ([]*project_dto.SimpleProjectItem, error) { +func (i *imlProjectModule) SimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { w := make(map[string]interface{}) w["as_server"] = true - if partition != "" { - pp, err := i.projectPartitionService.ListByPartition(ctx, partition) - if err != nil { - return nil, err - } - w["uuid"] = utils.SliceToSlice(pp, func(p *project.Partition) string { - return p.Project - }) - } + //if partition != "" { + // pp, err := i.projectPartitionService.ListByPartition(ctx, partition) + // if err != nil { + // return nil, err + // } + // w["uuid"] = utils.SliceToSlice(pp, func(p *project.Partition) string { + // return p.Project + // }) + //} projects, err := i.projectService.Search(ctx, keyword, w) if err != nil { return nil, err } - projectIDs := utils.SliceToSlice(projects, func(p *project.Project) string { - return p.Id - }) - partitions, err := i.projectPartitionService.ListByProject(ctx, projectIDs...) - if err != nil { - return nil, err - } - partitionMap := utils.SliceToMapArrayO(partitions, func(p *project.Partition) (string, string) { - return p.Project, p.Partition - }) items := make([]*project_dto.SimpleProjectItem, 0, len(projects)) for _, p := range projects { items = append(items, &project_dto.SimpleProjectItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Organization: auto.UUID(p.Organization), - Team: auto.UUID(p.Team), - Partition: auto.List(partitionMap[p.Id]), + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), }) } return items, nil @@ -195,27 +174,15 @@ func (i *imlProjectModule) MySimpleProjects(ctx context.Context, keyword string) if err != nil { return nil, err } - projectIDs := utils.SliceToSlice(projects, func(p *project.Project) string { - return p.Id - }) - partitions, err := i.projectPartitionService.ListByProject(ctx, projectIDs...) - if err != nil { - return nil, err - } - partitionMap := utils.SliceToMapArrayO(partitions, func(p *project.Partition) (string, string) { - return p.Project, p.Partition - }) items := make([]*project_dto.SimpleProjectItem, 0, len(projects)) for _, p := range projects { items = append(items, &project_dto.SimpleProjectItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Organization: auto.UUID(p.Organization), - Team: auto.UUID(p.Team), - Partition: auto.List(partitionMap[p.Id]), + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), }) } return items, nil @@ -226,19 +193,8 @@ func (i *imlProjectModule) GetProject(ctx context.Context, id string) (*project_ if err != nil { return nil, err } - teamInfo, err := i.teamService.Get(ctx, projectInfo.Team) - if err != nil { - return nil, err - } - organizationInfo, err := i.organizationService.Get(ctx, teamInfo.Organization) - if err != nil { - return nil, err - } - partitions, err := i.projectPartitionService.GetByProject(ctx, id) - if err != nil { - return nil, err - } - return project_dto.ToProject(projectInfo, teamInfo.Organization, organizationInfo.Prefix, partitions), nil + + return project_dto.ToProject(projectInfo), nil } func (i *imlProjectModule) Search(ctx context.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) { @@ -269,51 +225,39 @@ func (i *imlProjectModule) Search(ctx context.Context, teamID string, keyword st if err != nil { return nil, err } - partitions, err := i.projectPartitionService.ListByProject(ctx, projectIds...) - if err != nil { - return nil, err - } - partitionMap := utils.SliceToMapArrayO(partitions, func(p *project.Partition) (string, string) { - return p.Project, p.Partition - }) + items := make([]*project_dto.ProjectItem, 0, len(list)) for _, model := range list { apiCount := apiCountMap[model.Id] serviceCount := serviceCountMap[model.Id] items = append(items, &project_dto.ProjectItem{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - Partition: auto.List(partitionMap[model.Id]), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + Id: model.Id, + Name: model.Name, + Description: model.Description, + Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + ServiceNum: serviceCount, + CanDelete: apiCount == 0 && serviceCount == 0, }) } return items, nil } func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, input *project_dto.CreateProject) (*project_dto.Project, error) { - teamInfo, err := i.teamService.Get(ctx, teamID) - if err != nil { - return nil, err - } + if input.Id == "" { input.Id = uuid.New().String() } mo := &project.CreateProject{ - Id: input.Id, - Name: input.Name, - Description: input.Description, - Master: input.Master, - Team: teamID, - Prefix: input.Prefix, - Organization: teamInfo.Organization, + Id: input.Id, + Name: input.Name, + Description: input.Description, + Master: input.Master, + Team: teamID, + Prefix: input.Prefix, } if input.AsApp == nil { // 默认值为false @@ -328,18 +272,8 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp mo.AsServer = *input.AsServer } input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") - err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - if mo.AsServer { - // 判断是否有不可用的分区 - err = i.validPartitions(ctx, teamInfo.Organization, input.Partition) - if err != nil { - return err - } - err = i.projectPartitionService.Save(ctx, input.Id, input.Partition) - if err != nil { - return err - } - } + err := i.transaction.Transaction(ctx, func(ctx context.Context) error { + // 判断用户是否在团队内 members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{input.Master}) if err != nil { @@ -362,40 +296,13 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp return i.GetProject(ctx, input.Id) } -func (i *imlProjectModule) validPartitions(ctx context.Context, orgID string, partitions []string) error { - orgPartitions, err := i.organizationService.Partitions(ctx, orgID) +func (i *imlProjectModule) EditProject(ctx context.Context, id string, input *project_dto.EditProject) (*project_dto.Project, error) { + _, err := i.projectService.Get(ctx, id) if err != nil { - return err - } - partitionMap := utils.SliceToMapO(orgPartitions, func(s string) (string, struct{}) { - return s, struct{}{} - }) - for _, partition := range partitions { - if _, ok := partitionMap[partition]; !ok { - return fmt.Errorf("partition not found: %s", partition) - } + return nil, err } - return nil -} - -func (i *imlProjectModule) EditProject(ctx context.Context, id string, input *project_dto.EditProject) (*project_dto.Project, error) { + err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - err := i.transaction.Transaction(ctx, func(ctx context.Context) error { - pInfo, err := i.projectService.Get(ctx, id) - if err != nil { - return err - } - if len(input.Partition) > 0 { - // 判断是否有不可用的分区 - err = i.validPartitions(ctx, pInfo.Organization, input.Partition) - if err != nil { - return err - } - err = i.projectPartitionService.Save(ctx, pInfo.Id, input.Partition) - if err != nil { - return err - } - } if input.Master != nil { projectInfo, err := i.projectService.Get(ctx, id) if err != nil { @@ -450,10 +357,6 @@ func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { if err != nil { return err } - err = i.projectPartitionService.Delete(ctx, id) - if err != nil { - return err - } return i.projectService.Delete(ctx, id) }) @@ -643,22 +546,21 @@ type imlAppModule struct { } func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) { - teamInfo, err := i.teamService.Get(ctx, teamID) - if err != nil { - return nil, err - } + //teamInfo, err := i.teamService.Get(ctx, teamID) + //if err != nil { + // return nil, err + //} if input.Id == "" { input.Id = uuid.New().String() } userId := utils.UserId(ctx) mo := &project.CreateProject{ - Id: input.Id, - Name: input.Name, - Description: input.Description, - Master: userId, - Team: teamID, - Organization: teamInfo.Organization, - AsApp: true, + Id: input.Id, + Name: input.Name, + Description: input.Description, + Master: userId, + Team: teamID, + AsApp: true, } // 判断用户是否在团队内 members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{userId}) diff --git a/module/project/project.go b/module/project/project.go index 23712d8..9850848 100644 --- a/module/project/project.go +++ b/module/project/project.go @@ -23,7 +23,7 @@ type IProjectModule interface { // DeleteProject 删除项目 DeleteProject(ctx context.Context, id string) error // SimpleProjects 获取简易项目列表 - SimpleProjects(ctx context.Context, keyword string, partition string) ([]*project_dto.SimpleProjectItem, error) + SimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) // MySimpleProjects 获取我的简易项目列表 MySimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) diff --git a/module/project_diff/iml.go b/module/project_diff/iml.go index 885c43a..816be78 100644 --- a/module/project_diff/iml.go +++ b/module/project_diff/iml.go @@ -10,7 +10,6 @@ import ( "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/cluster" "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/apipark/service/project" "github.com/eolinker/apipark/service/project_diff" "github.com/eolinker/apipark/service/release" "github.com/eolinker/apipark/service/universally/commit" @@ -20,19 +19,18 @@ import ( ) type imlProjectDiff struct { - apiService api.IAPIService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - releaseService release.IReleaseService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` + apiService api.IAPIService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + releaseService release.IReleaseService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + clusterService cluster.IClusterService `autowired:""` } func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease, targetRelease string) (*project_diff.Diff, error) { if targetRelease == "" { return nil, fmt.Errorf("target release is required") } - partitions, err := m.projectPartitionService.GetByProject(ctx, projectId) + partitions, err := m.partitionService.List(ctx) if err != nil { return nil, err } @@ -58,8 +56,10 @@ func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease return nil, err } target.id = projectId - - diff := m.diff(partitions, base, target) + partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { + return i.UUID + }) + diff := m.diff(partitionIds, base, target) return diff, nil } @@ -120,11 +120,14 @@ func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, ba apiDocs: documents, upstreamCommits: upstreamCommits, } - partitions, err := m.projectPartitionService.GetByProject(ctx, projectId) + partitions, err := m.partitionService.List(ctx) if err != nil { return nil, false, err } - return m.diff(partitions, base, target), true, nil + partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { + return i.UUID + }) + return m.diff(partitionIds, base, target), true, nil } func (m *imlProjectDiff) getReleaseInfo(ctx context.Context, releaseId string) (*projectInfo, error) { commits, err := m.releaseService.GetCommits(ctx, releaseId) diff --git a/module/publish/iml.go b/module/publish/iml.go index fa31b32..86a232b 100644 --- a/module/publish/iml.go +++ b/module/publish/iml.go @@ -39,25 +39,24 @@ var ( ) type imlPublishModule struct { - projectDiffModule projectDiff.IProjectDiffModule `autowired:""` - publishService publish.IPublishService `autowired:""` - apiService api.IAPIService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - releaseService release.IReleaseService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - projectService project.IProjectService `autowired:""` + projectDiffModule projectDiff.IProjectDiffModule `autowired:""` + publishService publish.IPublishService `autowired:""` + apiService api.IAPIService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + releaseService release.IReleaseService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + projectService project.IProjectService `autowired:""` } func (m *imlPublishModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projectPartitions, err := m.projectPartitionService.ListByPartition(ctx, partitionId) + projects, err := m.projectService.List(ctx) if err != nil { return err } - projectIds := utils.SliceToSlice(projectPartitions, func(p *project.Partition) string { - return p.Project + projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { + return p.Id }) for _, projectId := range projectIds { releaseInfo, err := m.getProjectRelease(ctx, projectId, partitionId) @@ -530,10 +529,13 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin if flow.Status != publish.StatusAccept { return errors.New("只有通过状态才能发布") } - partitionIds, err := m.projectPartitionService.GetByProject(ctx, project) + partitions, err := m.partitionService.List(ctx) if err != nil { return err } + partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { + return p.UUID + }) projectReleaseMap, err := m.getReleaseInfo(ctx, project, flow.Release, flow.Release, partitionIds) if err != nil { return err diff --git a/module/release/iml.go b/module/release/iml.go index 3555e10..7f56a6a 100644 --- a/module/release/iml.go +++ b/module/release/iml.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" + "github.com/eolinker/apipark/service/partition" + projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/release/dto" "github.com/eolinker/apipark/service/api" @@ -28,14 +30,14 @@ var ( ) type imlReleaseModule struct { - projectDiffModule projectDiff.IProjectDiffModule `autowired:""` - releaseService release.IReleaseService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - apiService api.IAPIService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - publishService publish.IPublishService `autowired:""` - transaction store.ITransaction `autowired:""` - projectService project.IProjectService `autowired:""` + projectDiffModule projectDiff.IProjectDiffModule `autowired:""` + releaseService release.IReleaseService `autowired:""` + apiService api.IAPIService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + publishService publish.IPublishService `autowired:""` + transaction store.ITransaction `autowired:""` + projectService project.IProjectService `autowired:""` + partitionService partition.IPartitionService `autowired:""` } func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input *dto.CreateInput) (string, error) { @@ -47,7 +49,7 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * } return "", err } - partitions, err := m.projectPartitionService.ListByProject(ctx, projectId) + partitions, err := m.partitionService.List(ctx) if err != nil { return "", fmt.Errorf("partitions not set:%w", err) } @@ -107,8 +109,8 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * return c.Key, c.UUID }) }) - if !m.releaseService.Completeness(utils.SliceToSlice(partitions, func(s *project.Partition) string { - return s.Partition + if !m.releaseService.Completeness(utils.SliceToSlice(partitions, func(s *partition.Partition) string { + return s.UUID }), apiUUIDS, apiProxy, apiDocs, upstreams) { return "", errors.New("completeness check failed") } diff --git a/module/service/iml.go b/module/service/iml.go index 773acc0..19f2607 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -4,10 +4,11 @@ import ( "context" "errors" "fmt" + "strings" + "github.com/eolinker/apipark/service/partition" "github.com/eolinker/apipark/service/subscribe" "github.com/eolinker/eosc/log" - "strings" "github.com/eolinker/apipark/gateway" @@ -39,18 +40,17 @@ var ( ) type imlServiceModule struct { - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - serviceService service.IServiceService `autowired:""` - serviceTagService service.ITagService `autowired:""` - servicePartitionService service.IPartitionsService `autowired:""` - serviceDocService service.IDocService `autowired:""` - tagService tag.ITagService `autowired:""` - serviceApiService service.IApiService `autowired:""` - apiService api.IAPIService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` + projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` + serviceTagService service.ITagService `autowired:""` + servicePartitionService service.IPartitionsService `autowired:""` + serviceDocService service.IDocService `autowired:""` + tagService tag.ITagService `autowired:""` + serviceApiService service.IApiService `autowired:""` + apiService api.IAPIService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + clusterService cluster.IClusterService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -82,12 +82,9 @@ func (i *imlServiceModule) getServiceApis(ctx context.Context, projectIds []stri } func (i *imlServiceModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projectPartitions, err := i.projectPartitionService.ListByPartition(ctx, partitionId) - if err != nil { - return err - } - projectIds := utils.SliceToSlice(projectPartitions, func(p *project.Partition) string { - return p.Project + projects, err := i.projectService.List(ctx) + projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { + return p.Id }) releases, err := i.getServiceApis(ctx, projectIds) if err != nil { @@ -413,17 +410,16 @@ func (i *imlServiceModule) Create(ctx context.Context, pid string, input *servic err = i.transaction.Transaction(ctx, func(ctx context.Context) error { t := strings.Join(input.Tags, ",") err = i.serviceService.Create(ctx, &service.CreateService{ - Uuid: input.ID, - Name: input.Name, - Description: input.Description, - Logo: input.Logo, - ServiceType: input.ServiceType, - Project: pid, - Team: pInfo.Team, - Organization: pInfo.Organization, - Catalogue: catalogue, - Status: service.StatusOff, - Tag: t, + Uuid: input.ID, + Name: input.Name, + Description: input.Description, + Logo: input.Logo, + ServiceType: input.ServiceType, + Project: pid, + Team: pInfo.Team, + Catalogue: catalogue, + Status: service.StatusOff, + Tag: t, }) if err != nil { return err diff --git a/module/subscribe/dto/input.go b/module/subscribe/dto/input.go index ba67cab..8f9faa5 100644 --- a/module/subscribe/dto/input.go +++ b/module/subscribe/dto/input.go @@ -1,15 +1,15 @@ package subscribe_dto type AddSubscriber struct { - Uuid string `json:"uuid"` - Service string `json:"service" aocheck:"service"` - Project string `json:"subscriber" aocheck:"project"` - Applier string `json:"applier" aocheck:"user"` - Partition []string `json:"partition" aocheck:"partition"` + Uuid string `json:"uuid"` + Service string `json:"service" aocheck:"service"` + Project string `json:"subscriber" aocheck:"project"` + Applier string `json:"applier" aocheck:"user"` + //Partition []string `json:"partition" aocheck:"partition"` } type Approve struct { - Partition []string `json:"partition" aocheck:"partition"` - Opinion string `json:"opinion"` - Operate string `json:"operate"` + //Partition []string `json:"partition" aocheck:"partition"` + Opinion string `json:"opinion"` + Operate string `json:"operate"` } diff --git a/module/subscribe/dto/output.go b/module/subscribe/dto/output.go index b749d01..70ec6fe 100644 --- a/module/subscribe/dto/output.go +++ b/module/subscribe/dto/output.go @@ -3,10 +3,10 @@ package subscribe_dto import "github.com/eolinker/go-common/auto" type Subscriber struct { - Id string `json:"id"` - Project auto.Label `json:"project" aolabel:"project"` - Service auto.Label `json:"service" aolabel:"service"` - Partition []auto.Label `json:"partition" aolabel:"partition"` + Id string `json:"id"` + Project auto.Label `json:"project" aolabel:"project"` + Service auto.Label `json:"service" aolabel:"service"` + //Partition []auto.Label `json:"partition" aolabel:"partition"` Subscriber auto.Label `json:"subscriber" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` @@ -17,9 +17,9 @@ type Subscriber struct { } type SubscriptionItem struct { - Id string `json:"id"` - Service auto.Label `json:"service" aolabel:"service"` - Partition auto.Label `json:"partition" aolabel:"partition"` + Id string `json:"id"` + Service auto.Label `json:"service" aolabel:"service"` + //Partition auto.Label `json:"partition" aolabel:"partition"` ApplyStatus int `json:"apply_status"` Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` @@ -39,7 +39,6 @@ type Approval struct { Applier auto.Label `json:"applier" aolabel:"user"` Approver auto.Label `json:"approver" aolabel:"user"` ApprovalTime auto.TimeLabel `json:"approval_time"` - Partition []auto.Label `json:"partition" aolabel:"partition"` Reason string `json:"reason"` Opinion string `json:"opinion"` Status int `json:"status"` @@ -59,8 +58,9 @@ type ApprovalItem struct { Status int `json:"status"` } -type PartitionServiceItem struct { - Id string `json:"id"` - Name string `json:"name"` - ServiceNum int64 `json:"service_num"` -} +// +//type PartitionServiceItem struct { +// Id string `json:"id"` +// Name string `json:"name"` +// ServiceNum int64 `json:"service_num"` +//} diff --git a/module/subscribe/iml.go b/module/subscribe/iml.go index 1af02cf..1958f6c 100644 --- a/module/subscribe/iml.go +++ b/module/subscribe/iml.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/eolinker/apipark/service/partition" "github.com/eolinker/eosc/log" "gorm.io/gorm" @@ -34,55 +35,54 @@ var ( ) type imlSubscribeModule struct { - partitionService partition.IPartitionService `autowired:""` - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - serviceService service.IServiceService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - transaction store.ITransaction `autowired:""` + partitionService partition.IPartitionService `autowired:""` + projectService project.IProjectService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` + serviceService service.IServiceService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + transaction store.ITransaction `autowired:""` } -func (i *imlSubscribeModule) PartitionServices(ctx context.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) { - pInfo, err := i.projectService.Get(ctx, app) - if err != nil { - return nil, fmt.Errorf("get application error: %w", err) - } - if !pInfo.AsApp { - return nil, fmt.Errorf("project %s is not an application", app) - } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return nil, err - } - subscriptions, err := i.subscribeService.SubscriptionsByApplication(ctx, app) - if err != nil { - return nil, err - } - subscriptionCount := make(map[string]int64) - for _, s := range subscriptions { - if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { - continue - } - if _, ok := subscriptionCount[s.Partition]; !ok { - subscriptionCount[s.Partition] = 0 - } - subscriptionCount[s.Partition]++ - } - items := make([]*subscribe_dto.PartitionServiceItem, 0) - for _, p := range partitions { - items = append(items, &subscribe_dto.PartitionServiceItem{ - Id: p.UUID, - Name: p.Name, - ServiceNum: subscriptionCount[p.UUID], - }) - } - return items, nil -} - -func (i *imlSubscribeModule) getSubscribers(ctx context.Context, partitionId string, projectIds []string) ([]*gateway.SubscribeRelease, error) { - subscribers, err := i.subscribeService.SubscribersByProject(ctx, partitionId, projectIds...) +//func (i *imlSubscribeModule) PartitionServices(ctx context.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) { +// pInfo, err := i.projectService.Get(ctx, app) +// if err != nil { +// return nil, fmt.Errorf("get application error: %w", err) +// } +// if !pInfo.AsApp { +// return nil, fmt.Errorf("project %s is not an application", app) +// } +// partitions, err := i.partitionService.List(ctx) +// if err != nil { +// return nil, err +// } +// subscriptions, err := i.subscribeService.SubscriptionsByApplication(ctx, app) +// if err != nil { +// return nil, err +// } +// subscriptionCount := make(map[string]int64) +// for _, s := range subscriptions { +// if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { +// continue +// } +// if _, ok := subscriptionCount[s.Partition]; !ok { +// subscriptionCount[s.Partition] = 0 +// } +// subscriptionCount[s.Partition]++ +// } +// items := make([]*subscribe_dto.PartitionServiceItem, 0) +// for _, p := range partitions { +// items = append(items, &subscribe_dto.PartitionServiceItem{ +// Id: p.UUID, +// Name: p.Name, +// ServiceNum: subscriptionCount[p.UUID], +// }) +// } +// return items, nil +//} + +func (i *imlSubscribeModule) getSubscribers(ctx context.Context, projectIds []string) ([]*gateway.SubscribeRelease, error) { + subscribers, err := i.subscribeService.SubscribersByProject(ctx, projectIds...) if err != nil { return nil, err } @@ -95,15 +95,16 @@ func (i *imlSubscribeModule) getSubscribers(ctx context.Context, partitionId str }), nil } -func (i *imlSubscribeModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projectPartitions, err := i.projectPartitionService.ListByPartition(ctx, partitionId) +func (i *imlSubscribeModule) initGateway(ctx context.Context, clientDriver gateway.IClientDriver) error { + + projects, err := i.projectService.List(ctx) if err != nil { return err } - projectIds := utils.SliceToSlice(projectPartitions, func(p *project.Partition) string { - return p.Project + projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { + return p.Id }) - releases, err := i.getSubscribers(ctx, partitionId, projectIds) + releases, err := i.getSubscribers(ctx, projectIds) if err != nil { return err } @@ -140,7 +141,6 @@ func (i *imlSubscribeModule) SearchSubscriptions(ctx context.Context, partitionI return &subscribe_dto.SubscriptionItem{ Id: s.Id, Service: auto.UUID(s.Service), - Partition: auto.UUID(s.Partition), ApplyStatus: s.ApplyStatus, Project: auto.UUID(s.Project), Team: auto.UUID(pInfo.Team), @@ -172,6 +172,13 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, if subscription.ApplyStatus != subscribe.ApplyStatusSubscribe { return fmt.Errorf("subscription can not be revoked") } + partitions, err := i.partitionService.List(ctx) + if err != nil { + return err + } + partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { + return i.UUID + }) applyStatus := subscribe.ApplyStatusUnsubscribe return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.subscribeService.Save(ctx, uuid, &subscribe.UpdateSubscribe{ @@ -180,13 +187,14 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, if err != nil { return err } - - err = i.offlineForCluster(ctx, subscription.Partition, &gateway.SubscribeRelease{ - Service: subscription.Service, - Application: subscription.Application, - }) - if err != nil { - log.Warnf("revoke Subscription for partition:%s %s", subscription.Partition, err) + for _, p := range partitionIds { + err = i.offlineForCluster(ctx, p, &gateway.SubscribeRelease{ + Service: subscription.Service, + Application: subscription.Application, + }) + if err != nil { + return err + } } return nil @@ -232,9 +240,11 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, if err != nil { return err } - if len(input.Partition) == 0 { - return fmt.Errorf("partition is empty") + partitions, err := i.partitionService.List(ctx) + if err != nil { + return err } + if input.Uuid == "" { input.Uuid = uuid.New().String() } @@ -243,25 +253,24 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, Application: input.Project, Expired: "0", } + return i.transaction.Transaction(ctx, func(ctx context.Context) error { - for _, partitionId := range input.Partition { - err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ - Uuid: input.Uuid, - Service: input.Service, - Project: project, - Partition: partitionId, - Application: input.Project, - ApplyStatus: subscribe.ApplyStatusSubscribe, - From: subscribe.FromUser, - }) - if err != nil { - return err - } - err := i.onlineSubscriber(ctx, partitionId, sub) + err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ + Uuid: input.Uuid, + Service: input.Service, + Project: project, + Application: input.Project, + ApplyStatus: subscribe.ApplyStatusSubscribe, + From: subscribe.FromUser, + }) + if err != nil { + return err + } + for _, p := range partitions { + err = i.onlineSubscriber(ctx, p.UUID, sub) if err != nil { - return fmt.Errorf("add subscriber for partition[%s] %v", partitionId, err) + return fmt.Errorf("add subscriber for partition[%s] %v", p.UUID, err) } - } return nil @@ -291,6 +300,19 @@ func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project strin if err != nil { return err } + partitions, err := i.partitionService.List(ctx) + if err != nil { + return err + } + for _, p := range partitions { + err = i.offlineForCluster(ctx, p.UUID, &gateway.SubscribeRelease{ + Service: serviceId, + Application: applicationId, + }) + if err != nil { + return fmt.Errorf("offline subscribe for partition[%s] %s", p.UUID, err) + } + } return i.transaction.Transaction(ctx, func(ctx context.Context) error { list, err := i.subscribeService.ListByApplication(ctx, serviceId, applicationId) @@ -306,9 +328,11 @@ func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project strin if err != nil { return err } - err := i.offlineForCluster(ctx, s.Partition, releaseInfo) + } + for _, p := range partitions { + err := i.offlineForCluster(ctx, p.UUID, releaseInfo) if err != nil { - return fmt.Errorf("offline subscribe for partition[%s] %s", s.Partition, err) + return fmt.Errorf("offline subscribe for partition[%s] %s", p.UUID, err) } } return nil @@ -343,30 +367,19 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st if err != nil { return nil, err } - subscriberMap := utils.SliceToMapArrayO(list, func(s *subscribe.Subscribe) (string, string) { - return fmt.Sprintf("%s-%s", s.Service, s.Application), s.Partition - }) if keyword == "" { items := make([]*subscribe_dto.Subscriber, 0, len(list)) for _, subscriber := range list { - key := fmt.Sprintf("%s-%s", subscriber.Service, subscriber.Application) - partitionIds, ok := subscriberMap[key] - if !ok { - continue - } - items = append(items, &subscribe_dto.Subscriber{ Id: subscriber.Application, Project: auto.UUID(subscriber.Project), Service: auto.UUID(subscriber.Service), - Partition: auto.List(partitionIds), Subscriber: auto.UUID(subscriber.Application), Team: auto.UUID(pInfo.Team), ApplyTime: auto.TimeLabel(subscriber.CreateAt), From: subscriber.From, }) - delete(subscriberMap, key) } return items, nil } @@ -381,23 +394,17 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st }) items := make([]*subscribe_dto.Subscriber, 0, len(list)) for _, subscriber := range list { - key := fmt.Sprintf("%s-%s", subscriber.Service, subscriber.Application) - partitionIds, ok := subscriberMap[key] - if !ok { - continue - } + if _, ok := serviceMap[subscriber.Service]; ok { items = append(items, &subscribe_dto.Subscriber{ Id: subscriber.Id, Project: auto.UUID(subscriber.Project), Service: auto.UUID(subscriber.Service), - Partition: auto.List(partitionIds), Subscriber: auto.UUID(subscriber.Application), Team: auto.UUID(pInfo.Team), ApplyTime: auto.TimeLabel(subscriber.CreateAt), From: subscriber.From, }) - delete(subscriberMap, key) } } return items, nil @@ -406,12 +413,12 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st var _ ISubscribeApprovalModule = (*imlSubscribeApprovalModule)(nil) type imlSubscribeApprovalModule struct { - subscribeService subscribe.ISubscribeService `autowired:""` - subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - transaction store.ITransaction `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` + projectService project.IProjectService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id string, approveInfo *subscribe_dto.Approve) error { @@ -419,27 +426,20 @@ func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id st if err != nil { return err } - partitions, err := i.projectPartitionService.GetByProject(ctx, pid) + partitions, err := i.partitionService.List(ctx) if err != nil { return err } - partitionMap := utils.SliceToMapO(partitions, func(s string) (string, struct{}) { - return s, struct{}{} + partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { + return i.UUID }) - for _, pt := range approveInfo.Partition { - if _, ok := partitionMap[pt]; !ok { - return fmt.Errorf("partition %s not exists", pt) - } - } - return i.transaction.Transaction(ctx, func(ctx context.Context) error { userID := utils.UserId(ctx) status := subscribe.ApplyStatusSubscribe err = i.subscribeApplyService.Save(ctx, id, &subscribe.EditApply{ - ApplyPartitions: approveInfo.Partition, - Opinion: &approveInfo.Opinion, - Status: &status, - Approver: &userID, + Opinion: &approveInfo.Opinion, + Status: &status, + Approver: &userID, }) if err != nil { return err @@ -448,7 +448,7 @@ func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id st if err != nil { return err } - cs, err := i.clusterService.List(ctx, approveInfo.Partition...) + cs, err := i.clusterService.List(ctx, partitionIds...) if err != nil { return err } @@ -488,10 +488,9 @@ func (i *imlSubscribeApprovalModule) Reject(ctx context.Context, pid string, id userID := utils.UserId(ctx) status := subscribe.ApplyStatusRefuse err = i.subscribeApplyService.Save(ctx, id, &subscribe.EditApply{ - ApplyPartitions: approveInfo.Partition, - Opinion: &approveInfo.Opinion, - Status: &status, - Approver: &userID, + Opinion: &approveInfo.Opinion, + Status: &status, + Approver: &userID, }) if err != nil { return err @@ -551,7 +550,6 @@ func (i *imlSubscribeApprovalModule) GetApprovalDetail(ctx context.Context, pid Applier: auto.UUID(item.Applier), Approver: auto.UUID(item.Approver), ApprovalTime: auto.TimeLabel(item.ApproveAt), - Partition: auto.List(item.ApplyPartitions), Reason: item.Reason, Opinion: item.Opinion, Status: item.Status, diff --git a/module/subscribe/subscribe.go b/module/subscribe/subscribe.go index 9fd2722..110e75e 100644 --- a/module/subscribe/subscribe.go +++ b/module/subscribe/subscribe.go @@ -24,7 +24,7 @@ type ISubscribeModule interface { DeleteSubscription(ctx context.Context, pid string, uuid string) error // RevokeApply 取消申请 RevokeApply(ctx context.Context, app string, uuid string) error - PartitionServices(ctx context.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) + //PartitionServices(ctx context.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) } type ISubscribeApprovalModule interface { diff --git a/module/team/dto/input.go b/module/team/dto/input.go index e9149e2..64ae4d7 100644 --- a/module/team/dto/input.go +++ b/module/team/dto/input.go @@ -1,11 +1,10 @@ package team_dto type CreateTeam struct { - Id string `json:"id"` - Name string `json:"name" binding:"required"` - Description string `json:"description"` - OrganizationId string `json:"organization" aocheck:"organization"` - Master string `json:"master" aocheck:"user"` + Id string `json:"id"` + Name string `json:"name" binding:"required"` + Description string `json:"description"` + Master string `json:"master" aocheck:"user"` } type EditTeam struct { Name *string `json:"name"` diff --git a/module/team/iml.go b/module/team/iml.go index d81ce9e..11ec075 100644 --- a/module/team/iml.go +++ b/module/team/iml.go @@ -67,11 +67,10 @@ func (m *imlTeamModule) Create(ctx context.Context, input *team_dto.CreateTeam) err := m.transaction.Transaction(ctx, func(ctx context.Context) error { err := m.service.Create(ctx, &team.CreateTeam{ - Id: input.Id, - Name: input.Name, - Description: input.Description, - Master: input.Master, - Organization: input.OrganizationId, + Id: input.Id, + Name: input.Name, + Description: input.Description, + Master: input.Master, }) if err != nil { return err diff --git a/module/upstream/iml.go b/module/upstream/iml.go index 97b8efb..2e6f573 100644 --- a/module/upstream/iml.go +++ b/module/upstream/iml.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" + "github.com/eolinker/apipark/service/partition" + "github.com/eolinker/go-common/utils" "gorm.io/gorm" @@ -26,10 +28,10 @@ var ( ) type imlUpstreamModule struct { - projectService project.IProjectService `autowired:""` - projectPartitionService project.IProjectPartitionsService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - transaction store.ITransaction `autowired:""` + projectService project.IProjectService `autowired:""` + partitionService partition.IPartitionService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.UpstreamConfig, error) { @@ -64,18 +66,18 @@ func (i *imlUpstreamModule) Save(ctx context.Context, pid string, upstreamConfig if err != nil { return nil, err } - projectPartitions, err := i.projectPartitionService.ListByProject(ctx, pid) + partitions, err := i.partitionService.List(ctx) if err != nil { return nil, err } - projectPartitionMap := utils.SliceToMap(projectPartitions, func(p *project.Partition) string { - return p.Partition + partitionMap := utils.SliceToMapO(partitions, func(p *partition.Partition) (string, struct{}) { + return p.UUID, struct{}{} }) err = i.transaction.Transaction(ctx, func(ctx context.Context) error { partitionIds := make([]string, 0, len(upstreamConfig)) for id, cfg := range upstreamConfig { - if _, ok := projectPartitionMap[id]; !ok { + if _, ok := partitionMap[id]; !ok { continue } err = i.upstreamService.SaveCommit(ctx, pid, id, upstream_dto.ConvertUpstream(cfg)) diff --git a/plugins/core/core.go b/plugins/core/core.go index e73661c..2d4fc8e 100644 --- a/plugins/core/core.go +++ b/plugins/core/core.go @@ -1,34 +1,34 @@ package core import ( + "net/http" + "github.com/eolinker/apipark/controller/common" plugin_partition "github.com/eolinker/apipark/controller/plugin-partition" - "net/http" - + "github.com/eolinker/apipark/controller/topology" - + dynamic_module "github.com/eolinker/apipark/controller/dynamic-module" - + "github.com/eolinker/apipark/controller/release" - + project_authorization "github.com/eolinker/apipark/controller/project-authorization" - + "github.com/eolinker/apipark/controller/subscribe" - + "github.com/eolinker/apipark/controller/api" - + "github.com/eolinker/apipark/controller/upstream" - + "github.com/eolinker/apipark/controller/service" - + "github.com/eolinker/apipark/controller/catalogue" - + "github.com/eolinker/apipark/controller/project" - + "github.com/eolinker/apipark/controller/my_team" - + "github.com/eolinker/apipark/controller/certificate" - organization2 "github.com/eolinker/apipark/controller/organization" "github.com/eolinker/apipark/controller/partition" "github.com/eolinker/apipark/controller/team_manager" "github.com/eolinker/go-common/autowire" @@ -47,7 +47,7 @@ func (d *Driver) Access() map[string][]string { } func (d *Driver) Create() (pm3.IPlugin, error) { - + p := new(plugin) autowire.Autowired(p) return p, nil @@ -56,7 +56,6 @@ func (d *Driver) Create() (pm3.IPlugin, error) { type plugin struct { partitionController partition.IPartitionController `autowired:""` certificateController certificate.ICertificateController `autowired:""` - organizationController organization2.IOrganizationController `autowired:""` teamManagerController team_manager.ITeamManagerController `autowired:""` myTeamController my_team.ITeamController `autowired:""` appController project.IAppController `autowired:""` @@ -81,7 +80,6 @@ func (p *plugin) OnComplete() { p.apis = append(p.apis, p.partitionApi()...) p.apis = append(p.apis, p.certificateApi()...) p.apis = append(p.apis, p.clusterApi()...) - p.apis = append(p.apis, p.organizationApi()...) p.apis = append(p.apis, p.TeamManagerApi()...) p.apis = append(p.apis, p.MyTeamApi()...) p.apis = append(p.apis, p.ProjectApi()...) diff --git a/plugins/core/organization.go b/plugins/core/organization.go deleted file mode 100644 index eb7646f..0000000 --- a/plugins/core/organization.go +++ /dev/null @@ -1,22 +0,0 @@ -package core - -import ( - "net/http" - - "github.com/eolinker/go-common/pm3" -) - -func (p *plugin) organizationApi() []pm3.Api { - return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/manager/organizations", []string{"context", "query:keyword"}, []string{"organizations"}, p.organizationController.Search), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/manager/organization", []string{"context", "query:id"}, []string{"organization"}, p.organizationController.Get), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/manager/organization/:id", []string{"context", "path:id"}, []string{"organization"}, p.organizationController.Get), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/manager/organization", []string{"context", "body"}, []string{"organization"}, p.organizationController.Create), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/manager/organization", []string{"context", "query:id", "body"}, []string{"organization"}, p.organizationController.Edit), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/manager/organization", []string{"context", "query:id"}, []string{"id"}, p.organizationController.Delete), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/manager/organization/:id", []string{"context", "path:id"}, []string{"id"}, p.organizationController.Delete), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/organization/partitions", []string{"context", "query:organization"}, []string{"partitions"}, p.organizationController.Partitions), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/organizations", []string{"context"}, []string{"organizations"}, p.organizationController.Simple), - } - -} diff --git a/plugins/core/subscribe.go b/plugins/core/subscribe.go index 1824313..68868fb 100644 --- a/plugins/core/subscribe.go +++ b/plugins/core/subscribe.go @@ -17,7 +17,7 @@ func (p *plugin) subscribeApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/application/subscription/cancel", []string{"context", "query:application", "query:subscription"}, nil, p.subscribeController.RevokeSubscription), pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/application/subscription/cancel_apply", []string{"context", "query:application", "query:subscription"}, nil, p.subscribeController.RevokeApply), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/application/partitions", []string{"context", "query:application"}, []string{"partitions"}, p.subscribeController.PartitionServices), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/application/partitions", []string{"context", "query:application"}, []string{"partitions"}, p.subscribeController.PartitionServices), // 审批相关 pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/approval/subscribes", []string{"context", "query:project", "query:status"}, []string{"approvals"}, p.subscribeApprovalController.GetApprovalList), diff --git a/plugins/core/upstream.go b/plugins/core/upstream.go index 859bfe0..c72138e 100644 --- a/plugins/core/upstream.go +++ b/plugins/core/upstream.go @@ -8,7 +8,7 @@ import ( func (p *plugin) upstreamApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/upstream", []string{"context", "query:project"}, []string{"upstream", "partitions"}, p.upstreamController.Get), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/upstream", []string{"context", "query:project"}, []string{"upstream"}, p.upstreamController.Get), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/upstream", []string{"context", "query:project", "body"}, []string{"upstream"}, p.upstreamController.Save), } } diff --git a/service/organization/iml.go b/service/organization/iml.go deleted file mode 100644 index 2ce8393..0000000 --- a/service/organization/iml.go +++ /dev/null @@ -1,250 +0,0 @@ -package organization - -import ( - "context" - "errors" - "time" - - "github.com/eolinker/apipark/stores/organization" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/utils" - "github.com/google/uuid" - "gorm.io/gorm" -) - -var ( - _ IOrganizationService = (*imlOrganizationService)(nil) -) - -type imlOrganizationService struct { - organizationStore organization.IOrganizationStore `autowired:""` - partitionStore organization.IOrganizationPartitionStore `autowired:""` -} - -func (s *imlOrganizationService) PartitionsByOrganization(ctx context.Context, orgId ...string) (map[string][]string, error) { - w := make(map[string]interface{}) - if len(orgId) > 0 { - w["oid"] = orgId - } - partitions, err := s.partitionStore.List(ctx, w) - if err != nil { - return nil, err - } - return utils.SliceToMapArrayO(partitions, func(p *organization.Partition) (string, string) { - return p.Oid, p.Pid - }), nil -} - -func (s *imlOrganizationService) All(ctx context.Context) ([]*Organization, error) { - list, err := s.organizationStore.List(ctx, map[string]interface{}{}) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(e *organization.Organization) *Organization { - return fromEntity(e, nil) - }), nil -} - -func (s *imlOrganizationService) OnComplete() { - auto.RegisterService("organization", s) -} - -func (s *imlOrganizationService) GetLabels(ctx context.Context, ids ...string) map[string]string { - if len(ids) == 0 { - return nil - } - list, err := s.organizationStore.ListQuery(ctx, "`uuid` in (?)", []interface{}{ids}, "id") - if err != nil { - return nil - } - return utils.SliceToMapO(list, func(i *organization.Organization) (string, string) { - return i.UUID, i.Name - }) -} - -func (s *imlOrganizationService) Create(ctx context.Context, id, name, description, prefix, master string, partitions []string) (*Organization, error) { - if id == "" { - id = uuid.NewString() - } - oe, err := s.organizationStore.FirstQuery(ctx, "`uuid`=?", []interface{}{id}, "id") - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return nil, err - } - if oe != nil { - return nil, errors.New("organization already exists") - } - now := time.Now() - userId := utils.UserId(ctx) - ne := &organization.Organization{ - Id: 0, - UUID: id, - Name: name, - CreateAt: now, - UpdateAt: now, - Description: description, - Master: master, - Prefix: prefix, - Updater: userId, - Creator: userId, - } - pel := make([]*organization.Partition, 0, len(partitions)) - for _, p := range partitions { - pel = append(pel, &organization.Partition{ - Id: 0, - Oid: id, - Pid: p, - CreateTime: ne.CreateAt, - }) - } - err = s.partitionStore.Transaction(ctx, func(ctx context.Context) error { - err := s.organizationStore.Insert(ctx, ne) - if err != nil { - return err - } - - err = s.organizationStore.SetLabels(ctx, ne.Id, ne.Name, ne.Prefix, ne.Master, ne.Description) - if err != nil { - return err - } - return s.partitionStore.Insert(ctx, pel...) - }) - if err != nil { - return nil, err - } - return fromEntity(ne, utils.SliceToSlice(pel, func(p *organization.Partition) string { return p.Pid })), nil -} - -func (s *imlOrganizationService) Edit(ctx context.Context, id string, name, description, master *string, partitions *[]string) (*Organization, error) { - if id == "" { - return nil, errors.New("id is empty") - } - operator := utils.UserId(ctx) - ve, err := s.organizationStore.FirstQuery(ctx, "`uuid`=?", []interface{}{id}, "id") - if err != nil { - return nil, err - } - if ve == nil { - return nil, errors.New("organization not exists") - } - if name != nil { - ve.Name = *name - } - if description != nil { - ve.Description = *description - } - if master != nil { - ve.Master = *master - } - ve.UpdateAt = time.Now() - ve.Updater = operator - pel := make([]*organization.Partition, 0, len(*partitions)) - err = s.organizationStore.Transaction(ctx, func(ctx context.Context) error { - update, err := s.organizationStore.Update(ctx, ve) - if err != nil { - return err - } - if update == 0 { - return errors.New("organization not exists") - } - err = s.organizationStore.SetLabels(ctx, ve.Id, ve.Name, ve.Prefix, ve.Master, ve.Description) - // todo: update labels 需要增加更多参与查询的内容 - if err != nil { - return err - } - if partitions != nil { - _, err := s.partitionStore.DeleteWhere(ctx, map[string]interface{}{ - "`oid`": id, - }) - if err != nil { - return err - } - for _, p := range *partitions { - pel = append(pel, &organization.Partition{ - Id: 0, - Oid: id, - Pid: p, - CreateTime: ve.UpdateAt, - }) - } - err = s.partitionStore.Insert(ctx, pel...) - } else { - pelO, err := s.partitionStore.List(ctx, map[string]interface{}{ - "`oid`": id, - }) - if err != nil { - return err - } - pel = pelO - } - return nil - }) - if err != nil { - return nil, err - } - return fromEntity(ve, utils.SliceToSlice(pel, func(p *organization.Partition) string { return p.Pid })), nil -} - -func (s *imlOrganizationService) Get(ctx context.Context, id string) (*Organization, error) { - ev, err := s.organizationStore.FirstQuery(ctx, "`uuid`=?", []interface{}{id}, "id") - if err != nil { - return nil, err - } - pel, err := s.partitionStore.List(ctx, map[string]interface{}{"`oid`": id}) - if err != nil { - return nil, err - } - return fromEntity(ev, utils.SliceToSlice(pel, func(p *organization.Partition) string { return p.Pid })), nil - -} - -func (s *imlOrganizationService) Search(ctx context.Context, keyword string) ([]*Organization, error) { - ev, err := s.organizationStore.Search(ctx, keyword, nil) - if err != nil { - return nil, err - } - pelAll, err := s.partitionStore.List(ctx, nil) - if err != nil { - return nil, err - } - pelMap := utils.SliceToMapArray(pelAll, func(i *organization.Partition) string { - return i.Oid - }) - - return utils.SliceToSlice(ev, func(i *organization.Organization) *Organization { - return fromEntity(i, utils.SliceToSlice(pelMap[i.UUID], func(p *organization.Partition) string { return p.Pid })) - }), nil -} - -func (s *imlOrganizationService) Delete(ctx context.Context, id string) error { - _, err := s.organizationStore.FirstQuery(ctx, "`uuid`=?", []interface{}{id}, "id") - if err != nil { - return err - } - return s.organizationStore.Transaction(ctx, func(ctx context.Context) error { - deleteCount, err := s.organizationStore.DeleteWhere(ctx, map[string]interface{}{ - "`uuid`": id, - }) - if err != nil { - return err - } - if deleteCount != 1 { - return errors.New("delete organization failed") - } - _, err = s.partitionStore.DeleteWhere(ctx, map[string]interface{}{ - "`oid`": id, - }) - return err - }) - -} - -func (s *imlOrganizationService) Partitions(ctx context.Context, id string) ([]string, error) { - ps, err := s.partitionStore.List(ctx, map[string]interface{}{"`oid`": id}) - if err != nil { - return nil, err - } - return utils.SliceToSlice(ps, func(i *organization.Partition) string { - return i.Pid - }), nil - -} diff --git a/service/organization/model.go b/service/organization/model.go deleted file mode 100644 index bd746aa..0000000 --- a/service/organization/model.go +++ /dev/null @@ -1,35 +0,0 @@ -package organization - -import ( - "time" - - "github.com/eolinker/apipark/stores/organization" -) - -type Organization struct { - UUID string - Name string - Description string - Master string - Prefix string - Creator string - Partitions []string - CreateTime time.Time - Updater string - UpdateTime time.Time -} - -func fromEntity(ov *organization.Organization, pl []string) *Organization { - return &Organization{ - UUID: ov.UUID, - Name: ov.Name, - Description: ov.Description, - Master: ov.Master, - Creator: ov.Creator, - Updater: ov.Updater, - CreateTime: ov.CreateAt, - UpdateTime: ov.UpdateAt, - Partitions: pl, - Prefix: ov.Prefix, - } -} diff --git a/service/organization/service.go b/service/organization/service.go deleted file mode 100644 index f41292e..0000000 --- a/service/organization/service.go +++ /dev/null @@ -1,27 +0,0 @@ -package organization - -import ( - "context" - "reflect" - - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/autowire" -) - -type IOrganizationService interface { - Create(ctx context.Context, id, name, description, prefix, master string, partitions []string) (*Organization, error) - Edit(ctx context.Context, id string, name, description, master *string, partitions *[]string) (*Organization, error) - Get(ctx context.Context, id string) (*Organization, error) - Search(ctx context.Context, keyword string) ([]*Organization, error) - Delete(ctx context.Context, id string) error - Partitions(ctx context.Context, id string) ([]string, error) - PartitionsByOrganization(ctx context.Context, orgId ...string) (map[string][]string, error) - All(ctx context.Context) ([]*Organization, error) - auto.CompleteService -} - -func init() { - autowire.Auto[IOrganizationService](func() reflect.Value { - return reflect.ValueOf(new(imlOrganizationService)) - }) -} diff --git a/service/project/iml.go b/service/project/iml.go index da9c8b7..8815506 100644 --- a/service/project/iml.go +++ b/service/project/iml.go @@ -70,16 +70,6 @@ func (i *imlProjectService) CountByTeam(ctx context.Context, keyword string) (ma return i.projectStore.CountByGroup(ctx, keyword, map[string]interface{}{"as_server": true}, "team") } -//func (i *imlProjectService) ListByProject(ctx context.Context, projectId string) ([]*Project, error) { -// list, err := i.projectStore.List(ctx, map[string]interface{}{ -// "project": projectId, -// }, "update_at desc") -// if err != nil { -// return nil, err -// } -// return utils.SliceToSlice(list, FromEntity), nil -//} - func (i *imlProjectService) GetLabels(ctx context.Context, ids ...string) map[string]string { if len(ids) == 0 { return nil @@ -113,18 +103,17 @@ func uniquestHandler(i *CreateProject) []map[string]interface{} { func createEntityHandler(i *CreateProject) *project.Project { now := time.Now() return &project.Project{ - Id: 0, - UUID: i.Id, - Name: i.Name, - CreateAt: now, - UpdateAt: now, - Description: i.Description, - Prefix: i.Prefix, - Team: i.Team, - Organization: i.Organization, - Master: i.Master, - AsServer: i.AsServer, - AsApp: i.AsApp, + Id: 0, + UUID: i.Id, + Name: i.Name, + CreateAt: now, + UpdateAt: now, + Description: i.Description, + Prefix: i.Prefix, + Team: i.Team, + Master: i.Master, + AsServer: i.AsServer, + AsApp: i.AsApp, } } func updateHandler(e *project.Project, i *EditProject) { @@ -138,85 +127,3 @@ func updateHandler(e *project.Project, i *EditProject) { e.Master = *i.Master } } - -var _ IProjectPartitionsService = (*imlProjectPartitionService)(nil) - -type imlProjectPartitionService struct { - store project.IProjectPartitionStore `autowired:""` -} - -func (i *imlProjectPartitionService) ListByPartition(ctx context.Context, partitionIds ...string) ([]*Partition, error) { - w := make(map[string]interface{}) - if len(partitionIds) > 0 { - w["partition"] = partitionIds - } - list, err := i.store.List(ctx, w) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(t *project.Partition) *Partition { - return &Partition{ - Project: t.Project, - Partition: t.Partition, - } - }), nil -} - -func (i *imlProjectPartitionService) Delete(ctx context.Context, projectID string) error { - _, err := i.store.DeleteWhere(ctx, map[string]interface{}{ - "project": projectID, - }) - return err -} - -func (i *imlProjectPartitionService) ListByProject(ctx context.Context, projectIDs ...string) ([]*Partition, error) { - w := make(map[string]interface{}) - if len(projectIDs) > 0 { - w["project"] = projectIDs - } - list, err := i.store.List(ctx, w) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(t *project.Partition) *Partition { - return &Partition{ - Project: t.Project, - Partition: t.Partition, - } - }), nil -} - -func (i *imlProjectPartitionService) Save(ctx context.Context, projectID string, partitions []string) error { - if len(partitions) == 0 { - return fmt.Errorf("partitions is empty") - } - return i.store.Transaction(ctx, func(ctx context.Context) error { - _, err := i.store.DeleteWhere(ctx, map[string]interface{}{ - "project": projectID, - }) - if err != nil { - return err - } - now := time.Now() - return i.store.Insert(ctx, utils.SliceToSlice(partitions, func(t string) *project.Partition { - return &project.Partition{ - Project: projectID, - Partition: t, - CreateTime: now, - } - })...) - }) - -} - -func (i *imlProjectPartitionService) GetByProject(ctx context.Context, projectID string) ([]string, error) { - list, err := i.store.List(ctx, map[string]interface{}{ - "project": projectID, - }) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, func(t *project.Partition) string { - return t.Partition - }), nil -} diff --git a/service/project/model.go b/service/project/model.go index 729d36a..c23d773 100644 --- a/service/project/model.go +++ b/service/project/model.go @@ -7,45 +7,42 @@ import ( ) type Project struct { - Id string - Name string - Description string - Team string - Organization string - Master string - Prefix string - AsServer bool - AsApp bool - CreateTime time.Time - UpdateTime time.Time + Id string + Name string + Description string + Team string + Master string + Prefix string + AsServer bool + AsApp bool + CreateTime time.Time + UpdateTime time.Time } func FromEntity(e *project.Project) *Project { return &Project{ - Id: e.UUID, - Name: e.Name, - Description: e.Description, - Team: e.Team, - Organization: e.Organization, - Master: e.Master, - Prefix: e.Prefix, - AsServer: e.AsServer, - AsApp: e.AsApp, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, + Id: e.UUID, + Name: e.Name, + Description: e.Description, + Team: e.Team, + Master: e.Master, + Prefix: e.Prefix, + AsServer: e.AsServer, + AsApp: e.AsApp, + CreateTime: e.CreateAt, + UpdateTime: e.UpdateAt, } } type CreateProject struct { - Id string - Name string - Description string - Master string - Team string - Organization string - Prefix string - AsServer bool - AsApp bool + Id string + Name string + Description string + Master string + Team string + Prefix string + AsServer bool + AsApp bool } type EditProject struct { diff --git a/service/project/service.go b/service/project/service.go index eb0f2d0..0044c6a 100644 --- a/service/project/service.go +++ b/service/project/service.go @@ -19,19 +19,8 @@ type IProjectService interface { AppList(ctx context.Context, appIds ...string) ([]*Project, error) } -type IProjectPartitionsService interface { - ListByProject(ctx context.Context, projectIDs ...string) ([]*Partition, error) - ListByPartition(ctx context.Context, partition ...string) ([]*Partition, error) - Save(ctx context.Context, projectID string, partitions []string) error - Delete(ctx context.Context, projectID string) error - GetByProject(ctx context.Context, projectID string) ([]string, error) -} - func init() { autowire.Auto[IProjectService](func() reflect.Value { return reflect.ValueOf(new(imlProjectService)) }) - autowire.Auto[IProjectPartitionsService](func() reflect.Value { - return reflect.ValueOf(new(imlProjectPartitionService)) - }) } diff --git a/service/service/iml.go b/service/service/iml.go index 6f251bb..1ff5f05 100644 --- a/service/service/iml.go +++ b/service/service/iml.go @@ -110,19 +110,18 @@ func uniquestHandler(i *CreateService) []map[string]interface{} { func createEntityHandler(i *CreateService) *service.Service { now := time.Now() return &service.Service{ - UUID: i.Uuid, - Name: i.Name, - Description: i.Description, - Logo: i.Logo, - ServiceType: i.ServiceType, - Project: i.Project, - Team: i.Team, - Organization: i.Organization, - Catalogue: i.Catalogue, - Status: i.Status, - Tag: i.Tag, - CreateAt: now, - UpdateAt: now, + UUID: i.Uuid, + Name: i.Name, + Description: i.Description, + Logo: i.Logo, + ServiceType: i.ServiceType, + Project: i.Project, + Team: i.Team, + Catalogue: i.Catalogue, + Status: i.Status, + Tag: i.Tag, + CreateAt: now, + UpdateAt: now, } } func updateHandler(e *service.Service, i *EditService) { diff --git a/service/service/model.go b/service/service/model.go index 00976ab..ab44562 100644 --- a/service/service/model.go +++ b/service/service/model.go @@ -12,49 +12,46 @@ const ( ) type Service struct { - Id string - Name string - Description string - Logo string - ServiceType string - Project string - Team string - Organization string - Catalogue string - Status string - CreateTime time.Time - UpdateTime time.Time + Id string + Name string + Description string + Logo string + ServiceType string + Project string + Team string + Catalogue string + Status string + CreateTime time.Time + UpdateTime time.Time } func FromEntity(e *service.Service) *Service { return &Service{ - Id: e.UUID, - Name: e.Name, - Description: e.Description, - Logo: e.Logo, - ServiceType: e.ServiceType, - Project: e.Project, - Team: e.Team, - Organization: e.Organization, - Catalogue: e.Catalogue, - Status: e.Status, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, + Id: e.UUID, + Name: e.Name, + Description: e.Description, + Logo: e.Logo, + ServiceType: e.ServiceType, + Project: e.Project, + Team: e.Team, + Catalogue: e.Catalogue, + Status: e.Status, + CreateTime: e.CreateAt, + UpdateTime: e.UpdateAt, } } type CreateService struct { - Uuid string - Name string - Description string - Logo string - ServiceType string - Project string - Team string - Organization string - Catalogue string - Status string - Tag string + Uuid string + Name string + Description string + Logo string + ServiceType string + Project string + Team string + Catalogue string + Status string + Tag string } type EditService struct { diff --git a/service/subscribe/iml.go b/service/subscribe/iml.go index 750a50e..899d88f 100644 --- a/service/subscribe/iml.go +++ b/service/subscribe/iml.go @@ -73,14 +73,12 @@ func (i *imlSubscribeService) DeleteByApplication(ctx context.Context, service s return err } -func (i *imlSubscribeService) SubscribersByProject(ctx context.Context, partitionId string, projectIds ...string) ([]*Subscribe, error) { +func (i *imlSubscribeService) SubscribersByProject(ctx context.Context, projectIds ...string) ([]*Subscribe, error) { w := make(map[string]interface{}) if len(projectIds) > 0 { w["project"] = projectIds } - if partitionId != "" { - w["partition"] = partitionId - } + w["apply_status"] = ApplyStatusSubscribe list, err := i.store.List(ctx, w, "create_at desc") if err != nil { @@ -175,13 +173,9 @@ func (i *imlSubscribeService) createEntityHandler(t *CreateSubscribe) *subscribe Project: t.Project, Application: t.Application, Service: t.Service, - Partition: t.Partition, - //Applier: t.Applier, - //Approver: t.Approver, From: t.From, CreateAt: time.Now(), ApplyStatus: t.ApplyStatus, - //ApplyID: t.ApplyID, } } @@ -255,22 +249,19 @@ func (i *imlSubscribeApplyService) uniquestHandler(t *CreateApply) []map[string] func (i *imlSubscribeApplyService) createEntityHandler(t *CreateApply) *subscribe.Apply { now := time.Now() return &subscribe.Apply{ - Uuid: t.Uuid, - Service: t.Service, - Project: t.Project, - Team: t.Team, - Organization: t.Organization, - Application: t.Application, - ApplyTeam: t.ApplyTeam, - ApplyOrganization: t.ApplyOrganization, - ApplyPartitions: t.ApplyPartitions, - Applier: t.Applier, - ApplyAt: now, - Approver: "", - ApproveAt: now, - Status: t.Status, - Opinion: "", - Reason: t.Reason, + Uuid: t.Uuid, + Service: t.Service, + Project: t.Project, + Team: t.Team, + Application: t.Application, + ApplyTeam: t.ApplyTeam, + Applier: t.Applier, + ApplyAt: now, + Approver: "", + ApproveAt: now, + Status: t.Status, + Opinion: "", + Reason: t.Reason, } } @@ -288,8 +279,5 @@ func (i *imlSubscribeApplyService) updateHandler(e *subscribe.Apply, t *EditAppl e.Approver = *t.Approver e.ApplyAt = time.Now() } - if t.ApplyPartitions != nil { - e.ApplyPartitions = t.ApplyPartitions - } } diff --git a/service/subscribe/model.go b/service/subscribe/model.go index cf4af7e..a51c0d4 100644 --- a/service/subscribe/model.go +++ b/service/subscribe/model.go @@ -9,9 +9,8 @@ import ( type Subscribe struct { Id string // 被订阅服务相关 - Project string - Service string - Partition string + Project string + Service string // 订阅方相关 Application string @@ -23,22 +22,17 @@ type Subscribe struct { } type CreateSubscribe struct { - Uuid string - Service string - Project string - Partition string + Uuid string + Service string + Project string Application string - //Applier string - //Approver string ApplyStatus int From int } type UpdateSubscribe struct { ApplyStatus *int - //Approver *string - //Applier *string } func FromEntity(e *subscribe.Subscribe) *Subscribe { @@ -46,74 +40,61 @@ func FromEntity(e *subscribe.Subscribe) *Subscribe { Id: e.UUID, Project: e.Project, Service: e.Service, - Partition: e.Partition, ApplyStatus: e.ApplyStatus, Application: e.Application, From: e.From, CreateAt: e.CreateAt, - //Applier: e.Applier, - //Approver: e.Approver, } } type CreateApply struct { - Uuid string - Service string - Project string - Team string - Organization string - ApplyPartitions []string - Application string - ApplyTeam string - ApplyOrganization string - Reason string - Status int - Applier string + Uuid string + Service string + Project string + Team string + Application string + ApplyTeam string + Reason string + Status int + Applier string } type EditApply struct { - ApplyPartitions []string - Opinion *string - Status *int - Approver *string + Opinion *string + Status *int + Approver *string } type Apply struct { - Id string - Service string - Project string - Team string - Application string - ApplyTeam string - ApplyOrganization string - ApplyPartitions []string - Partitions []string - Applier string - ApplyAt time.Time - Approver string - ApproveAt time.Time - Status int - Opinion string - Reason string + Id string + Service string + Project string + Team string + Application string + ApplyTeam string + Applier string + ApplyAt time.Time + Approver string + ApproveAt time.Time + Status int + Opinion string + Reason string } func FromApplyEntity(e *subscribe.Apply) *Apply { return &Apply{ - Id: e.Uuid, - Service: e.Service, - Project: e.Project, - Team: e.Team, - Application: e.Application, - ApplyTeam: e.ApplyTeam, - ApplyOrganization: e.ApplyOrganization, - ApplyPartitions: e.ApplyPartitions, - Partitions: e.Partitions, - Applier: e.Applier, - ApplyAt: e.ApplyAt, - Approver: e.Approver, - ApproveAt: e.ApproveAt, - Status: e.Status, - Opinion: e.Opinion, - Reason: e.Reason, + Id: e.Uuid, + Service: e.Service, + Project: e.Project, + Team: e.Team, + Application: e.Application, + ApplyTeam: e.ApplyTeam, + Applier: e.Applier, + ApplyAt: e.ApplyAt, + Approver: e.Approver, + ApproveAt: e.ApproveAt, + Status: e.Status, + Opinion: e.Opinion, + Reason: e.Reason, } } diff --git a/service/subscribe/service.go b/service/subscribe/service.go index 0c3141a..47d004e 100644 --- a/service/subscribe/service.go +++ b/service/subscribe/service.go @@ -20,7 +20,7 @@ type ISubscribeService interface { MySubscribeServices(ctx context.Context, application string, projectIds []string, serviceIDs []string, partitionIds ...string) ([]*Subscribe, error) UpdateSubscribeStatus(ctx context.Context, application string, service string, status int) error ListBySubscribeStatus(ctx context.Context, projectId string, status int) ([]*Subscribe, error) - SubscribersByProject(ctx context.Context, partition string, projectIds ...string) ([]*Subscribe, error) + SubscribersByProject(ctx context.Context, projectIds ...string) ([]*Subscribe, error) Subscribers(ctx context.Context, project string, status int) ([]*Subscribe, error) SubscriptionsByApplication(ctx context.Context, applicationIds ...string) ([]*Subscribe, error) } diff --git a/service/team/iml.go b/service/team/iml.go index 840efbc..ad9e9a7 100644 --- a/service/team/iml.go +++ b/service/team/iml.go @@ -55,14 +55,13 @@ func uniquestHandler(i *CreateTeam) []map[string]interface{} { } func createEntityHandler(i *CreateTeam) *team.Team { return &team.Team{ - Id: 0, - UUID: i.Id, - Name: i.Name, - Description: i.Description, - Master: i.Master, - Organization: i.Organization, - CreateAt: time.Now(), - UpdateAt: time.Now(), + Id: 0, + UUID: i.Id, + Name: i.Name, + Description: i.Description, + Master: i.Master, + CreateAt: time.Now(), + UpdateAt: time.Now(), } } func updateHandler(e *team.Team, i *EditTeam) { @@ -75,8 +74,6 @@ func updateHandler(e *team.Team, i *EditTeam) { if i.Master != nil { e.Master = *i.Master } - if i.Organization != nil { - e.Organization = *i.Organization - } + e.UpdateAt = time.Now() } diff --git a/service/team/model.go b/service/team/model.go index 34da7e9..51ee360 100644 --- a/service/team/model.go +++ b/service/team/model.go @@ -16,33 +16,29 @@ type Team struct { UpdateTime time.Time `json:"update_time"` Creator string `json:"creator"` Updater string `json:"updater"` - //ProjectNum int64 `json:"project_num"` } func FromEntity(e *team.Team) *Team { return &Team{ - Id: e.UUID, - Name: e.Name, - Description: e.Description, - Master: e.Master, - Organization: e.Organization, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, - Creator: e.Creator, - Updater: e.Updater, + Id: e.UUID, + Name: e.Name, + Description: e.Description, + Master: e.Master, + CreateTime: e.CreateAt, + UpdateTime: e.UpdateAt, + Creator: e.Creator, + Updater: e.Updater, } } type CreateTeam struct { - Id string `json:"id" ` - Name string `json:"name" ` - Description string `json:"description"` - Master string `json:"master" ` - Organization string `json:"organization"` + Id string `json:"id" ` + Name string `json:"name" ` + Description string `json:"description"` + Master string `json:"master" ` } type EditTeam struct { - Name *string `json:"name" ` - Description *string `json:"description"` - Master *string `json:"master" ` - Organization *string `json:"organization"` + Name *string `json:"name" ` + Description *string `json:"description"` + Master *string `json:"master" ` } diff --git a/stores/dynamic-module/model.go b/stores/dynamic-module/model.go index 054c3c1..385a181 100644 --- a/stores/dynamic-module/model.go +++ b/stores/dynamic-module/model.go @@ -3,10 +3,9 @@ package dynamic_module import "time" type DynamicModule struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - //Partition string `gorm:"column:partition;type:VARCHAR(255);NOT NULL;comment:分区"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` Driver string `gorm:"column:driver;type:VARCHAR(255);NOT NULL;comment:驱动"` Description string `gorm:"column:description;type:VARCHAR(255);comment:描述"` Version string `gorm:"column:version;type:VARCHAR(32);NOT NULL;comment:版本"` diff --git a/stores/organization/model.go b/stores/organization/model.go deleted file mode 100644 index 3348101..0000000 --- a/stores/organization/model.go +++ /dev/null @@ -1,43 +0,0 @@ -package organization - -import ( - "time" -) - -// 组织 - -type Organization struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - Creator string `gorm:"type:varchar(36);not null;column:creator;comment:创建人id" aovalue:"creator"` - Updater string `gorm:"type:varchar(36);not null;column:updater;comment:修改人id" aovalue:"updater"` - Description string `gorm:"size:255;not null;column:description;comment:description"` - Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id - Prefix string `gorm:"size:255;not null;column:prefix;comment:分区前缀"` -} - -func (o *Organization) TableName() string { - return "organization" -} - -func (o *Organization) IdValue() int64 { - return o.Id -} - -type Partition struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - Oid string `gorm:"size:36;not null;column:oid;comment:组织id;uniqueIndex:oid_pid;"` - Pid string `gorm:"size:36;not null;column:pid;comment:分区id;uniqueIndex:oid_pid;"` - CreateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` -} - -func (p *Partition) TableName() string { - return "organization_partition" -} - -func (p *Partition) IdValue() int64 { - return p.Id -} diff --git a/stores/organization/store.go b/stores/organization/store.go deleted file mode 100644 index 29659c9..0000000 --- a/stores/organization/store.go +++ /dev/null @@ -1,30 +0,0 @@ -package organization - -import ( - "github.com/eolinker/go-common/autowire" - "github.com/eolinker/go-common/store" - "reflect" -) - -type IOrganizationStore interface { - store.ISearchStore[Organization] -} -type IOrganizationPartitionStore interface { - store.IBaseStore[Partition] -} - -type imlOrganizationStore struct { - store.SearchStore[Organization] -} -type imlOrganizationPartitionStore struct { - store.Store[Partition] -} - -func init() { - autowire.Auto[IOrganizationStore](func() reflect.Value { - return reflect.ValueOf(new(imlOrganizationStore)) - }) - autowire.Auto[IOrganizationPartitionStore](func() reflect.Value { - return reflect.ValueOf(new(imlOrganizationPartitionStore)) - }) -} diff --git a/stores/project/model.go b/stores/project/model.go index 1c6c425..9617952 100644 --- a/stores/project/model.go +++ b/stores/project/model.go @@ -3,20 +3,19 @@ package project import "time" type Project struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"size:255;not null;column:description;comment:description"` - Prefix string `gorm:"size:255;not null;column:prefix;comment:前缀"` - Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id - Organization string `gorm:"size:36;not null;column:organization;comment:组织id;index:organization"` // 组织 - Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id - IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` - AsServer bool `gorm:"type:tinyint(1);not null;column:as_server;comment:是否为服务端项目"` - AsApp bool `gorm:"type:tinyint(1);not null;column:as_app;comment:是否为应用项目"` + Description string `gorm:"size:255;not null;column:description;comment:description"` + Prefix string `gorm:"size:255;not null;column:prefix;comment:前缀"` + Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id + Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` + IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` + AsServer bool `gorm:"type:tinyint(1);not null;column:as_server;comment:是否为服务端项目"` + AsApp bool `gorm:"type:tinyint(1);not null;column:as_app;comment:是否为应用项目"` } func (p *Project) IdValue() int64 { @@ -65,18 +64,3 @@ func (a *Authorization) IdValue() int64 { func (a *Authorization) TableName() string { return "project_authorization" } - -type Partition struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - Project string `gorm:"size:36;not null;column:project;comment:系统id;uniqueIndex:oid_pid;"` - Partition string `gorm:"size:36;not null;column:partition;comment:分区id;uniqueIndex:oid_pid;"` - CreateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` -} - -func (p *Partition) TableName() string { - return "project_partition" -} - -func (p *Partition) IdValue() int64 { - return p.Id -} diff --git a/stores/project/store.go b/stores/project/store.go index da13c55..642dc88 100644 --- a/stores/project/store.go +++ b/stores/project/store.go @@ -31,14 +31,6 @@ type imlAuthorizationStore struct { store.SearchStore[Authorization] } -type IProjectPartitionStore interface { - store.IBaseStore[Partition] -} - -type imlProjectPartitionStore struct { - store.Store[Partition] -} - func init() { autowire.Auto[IProjectStore](func() reflect.Value { return reflect.ValueOf(new(imlProjectStore)) @@ -52,7 +44,4 @@ func init() { autowire.Auto[IAuthorizationStore](func() reflect.Value { return reflect.ValueOf(new(imlAuthorizationStore)) }) - autowire.Auto[IProjectPartitionStore](func() reflect.Value { - return reflect.ValueOf(new(imlProjectPartitionStore)) - }) } diff --git a/stores/service/model.go b/stores/service/model.go index 6e0d572..5ad4350 100644 --- a/stores/service/model.go +++ b/stores/service/model.go @@ -3,23 +3,22 @@ package service import "time" type Service struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"type:varchar(255);not null;column:description;comment:描述"` - Logo string `gorm:"type:text;column:logo;comment:logo"` - ServiceType string `gorm:"type:varchar(36);not null;column:service_type;comment:服务类型"` - Project string `gorm:"type:varchar(36);not null;column:project;comment:项目"` - Team string `gorm:"type:varchar(36);not null;column:team;comment:团队"` - Organization string `gorm:"type:varchar(36);not null;column:organization;comment:组织"` - Catalogue string `gorm:"type:varchar(36);not null;column:catalogue;comment:目录"` - Status string `gorm:"type:varchar(36);not null;column:status;comment:状态"` - Tag string `gorm:"type:varchar(255);not null;column:tag;comment:标签"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - Creator string `gorm:"type:varchar(36);not null;column:creator;comment:创建者" aovalue:"creator"` - Updater string `gorm:"type:varchar(36);not null;column:updater;comment:修改者" aovalue:"updater"` - IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除 0:未删除 1:已删除"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Description string `gorm:"type:varchar(255);not null;column:description;comment:描述"` + Logo string `gorm:"type:text;column:logo;comment:logo"` + ServiceType string `gorm:"type:varchar(36);not null;column:service_type;comment:服务类型"` + Project string `gorm:"type:varchar(36);not null;column:project;comment:项目"` + Team string `gorm:"type:varchar(36);not null;column:team;comment:团队"` + Catalogue string `gorm:"type:varchar(36);not null;column:catalogue;comment:目录"` + Status string `gorm:"type:varchar(36);not null;column:status;comment:状态"` + Tag string `gorm:"type:varchar(255);not null;column:tag;comment:标签"` + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` + Creator string `gorm:"type:varchar(36);not null;column:creator;comment:创建者" aovalue:"creator"` + Updater string `gorm:"type:varchar(36);not null;column:updater;comment:修改者" aovalue:"updater"` + IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除 0:未删除 1:已删除"` } func (o *Service) TableName() string { diff --git a/stores/subscribe/model.go b/stores/subscribe/model.go index d018207..ea094fc 100644 --- a/stores/subscribe/model.go +++ b/stores/subscribe/model.go @@ -8,7 +8,6 @@ type Subscribe struct { Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project;"` // 项目id Service string `gorm:"size:36;not null;column:service;comment:服务id;uniqueIndex:unique_subscribe"` Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;uniqueIndex:unique_subscribe"` - Partition string `gorm:"size:36;not null;column:partition;uniqueIndex:unique_subscribe;comment:分区id"` ApplyStatus int `gorm:"type:tinyint(1);not null;column:apply_status;comment:申请状态;index:status;"` From int `gorm:"type:tinyint(1);not null;column:from;comment:来源;index:status;"` CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` @@ -24,24 +23,20 @@ func (s *Subscribe) TableName() string { } type Apply struct { - Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` - Uuid string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` // uuid - Service string `gorm:"size:36;not null;column:service;comment:服务id;index:server;"` // 服务id - Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project;"` // 项目id - Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team;"` // 团队id - Organization string `gorm:"size:36;not null;column:organization;comment:组织id;index:organization;"` // 组织id - Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;index:application;"` // 订阅应用id - ApplyTeam string `gorm:"size:36;not null;column:apply_team;comment:申请团队id;index:apply_team;"` // 申请团队id - ApplyOrganization string `gorm:"size:36;not null;column:apply_organization;comment:申请组织id;index:apply_organization;"` // 申请组织id - ApplyPartitions []string `gorm:"type:text;not null;column:apply_partitions;comment:申请分区id;serializer:json"` // 申请分区id列表 - Partitions []string `gorm:"type:text;not null;column:partitions;comment:分区id;serializer:json"` // 通过分区id列表 - Applier string `gorm:"size:36;not null;column:applier;comment:申请人;index:applier;" aovalue:"creator"` - ApplyAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:apply_at;comment:申请时间"` - Approver string `gorm:"size:36;not null;column:approver;comment:审批人;index:approver;"` - ApproveAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:approve_at;comment:审批时间"` - Status int `gorm:"type:tinyint(1);not null;column:status;comment:审批状态;index:status;"` - Opinion string `gorm:"type:text;not null;column:opinion;comment:审批意见;"` - Reason string `gorm:"type:text;not null;column:reason;comment:申请原因;"` + Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` + Uuid string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` // uuid + Service string `gorm:"size:36;not null;column:service;comment:服务id;index:server;"` // 服务id + Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project;"` // 项目id + Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team;"` // 团队id + Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;index:application;"` // 订阅应用id + ApplyTeam string `gorm:"size:36;not null;column:apply_team;comment:申请团队id;index:apply_team;"` // 申请团队id + Applier string `gorm:"size:36;not null;column:applier;comment:申请人;index:applier;" aovalue:"creator"` + ApplyAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:apply_at;comment:申请时间"` + Approver string `gorm:"size:36;not null;column:approver;comment:审批人;index:approver;"` + ApproveAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:approve_at;comment:审批时间"` + Status int `gorm:"type:tinyint(1);not null;column:status;comment:审批状态;index:status;"` + Opinion string `gorm:"type:text;not null;column:opinion;comment:审批意见;"` + Reason string `gorm:"type:text;not null;column:reason;comment:申请原因;"` } func (a *Apply) IdValue() int64 { diff --git a/stores/team/model.go b/stores/team/model.go index 05d0493..41e2d35 100644 --- a/stores/team/model.go +++ b/stores/team/model.go @@ -5,18 +5,16 @@ import ( ) type Team struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - - Description string `gorm:"size:255;not null;column:description;comment:description"` - Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id - Organization string `gorm:"size:36;not null;column:organization;comment:组织id"` // 组织id - Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id - Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id - IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Description string `gorm:"size:255;not null;column:description;comment:description"` + Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id + Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id + Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` + IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` } func (t *Team) IdValue() int64 { From 8e6abe511de212c6bc8fffc7a5ca0ef6d2e858c5 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Wed, 24 Jul 2024 10:57:35 +0800 Subject: [PATCH 02/19] =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=88=90=E5=91=98=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/project/iml.go | 60 ++-- controller/project/project.go | 40 +-- module/permit/project/iml.go | 24 +- module/project/dto/input.go | 10 +- module/project/dto/output.go | 18 +- module/project/iml.go | 478 ++++++++++++++++---------------- module/project/project.go | 32 +-- plugins/core/core.go | 14 +- plugins/core/project.go | 26 +- service/project-role/iml.go | 74 ----- service/project-role/model.go | 12 - service/project-role/service.go | 22 -- service/project/iml.go | 12 +- service/project/model.go | 36 +-- stores/project/model.go | 29 +- stores/project/store.go | 18 +- 16 files changed, 394 insertions(+), 511 deletions(-) delete mode 100644 service/project-role/iml.go delete mode 100644 service/project-role/model.go delete mode 100644 service/project-role/service.go diff --git a/controller/project/iml.go b/controller/project/iml.go index a617a77..53c159e 100644 --- a/controller/project/iml.go +++ b/controller/project/iml.go @@ -7,9 +7,9 @@ import ( ) var ( - _ IProjectController = (*imlProjectController)(nil) - _ IProjectMemberController = (*imlProjectMemberController)(nil) - _ IAppController = (*imlAppController)(nil) + _ IProjectController = (*imlProjectController)(nil) + //_ IProjectMemberController = (*imlProjectMemberController)(nil) + _ IAppController = (*imlAppController)(nil) ) type imlProjectController struct { @@ -48,33 +48,33 @@ func (i *imlProjectController) DeleteProject(ctx *gin.Context, id string) error return i.module.DeleteProject(ctx, id) } -type imlProjectMemberController struct { - module project.IProjectMemberModule `autowired:""` -} - -func (i *imlProjectMemberController) SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { - return i.module.SimpleMembersToAdd(ctx, pid, keyword) -} - -func (i *imlProjectMemberController) SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { - return i.module.SimpleMembers(ctx, pid) -} - -func (i *imlProjectMemberController) Members(ctx *gin.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { - return i.module.Members(ctx, id, keyword) -} - -func (i *imlProjectMemberController) AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error { - return i.module.AddMember(ctx, pid, users.Users) -} - -func (i *imlProjectMemberController) RemoveMember(ctx *gin.Context, pid string, uid string) error { - return i.module.RemoveMember(ctx, pid, []string{uid}) -} - -func (i *imlProjectMemberController) EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error { - return i.module.EditProjectMember(ctx, pid, uid, edit.Roles) -} +//type imlProjectMemberController struct { +// module project.IProjectMemberModule `autowired:""` +//} +// +//func (i *imlProjectMemberController) SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { +// return i.module.SimpleMembersToAdd(ctx, pid, keyword) +//} +// +//func (i *imlProjectMemberController) SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { +// return i.module.SimpleMembers(ctx, pid) +//} +// +//func (i *imlProjectMemberController) Members(ctx *gin.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { +// return i.module.Members(ctx, id, keyword) +//} +// +//func (i *imlProjectMemberController) AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error { +// return i.module.AddMember(ctx, pid, users.Users) +//} +// +//func (i *imlProjectMemberController) RemoveMember(ctx *gin.Context, pid string, uid string) error { +// return i.module.RemoveMember(ctx, pid, []string{uid}) +//} +// +//func (i *imlProjectMemberController) EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error { +// return i.module.EditProjectMember(ctx, pid, uid, edit.Roles) +//} type imlAppController struct { module project.IAppModule `autowired:""` diff --git a/controller/project/project.go b/controller/project/project.go index 2d4beeb..127e8a0 100644 --- a/controller/project/project.go +++ b/controller/project/project.go @@ -2,10 +2,10 @@ package project import ( "reflect" - + project_dto "github.com/eolinker/apipark/module/project/dto" "github.com/gin-gonic/gin" - + "github.com/eolinker/go-common/autowire" ) @@ -27,24 +27,24 @@ type IProjectController interface { MySimpleProjects(ctx *gin.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) } -type IProjectMemberController interface { - // Members 获取项目成员列表 - Members(ctx *gin.Context, pid string, keyword string) ([]*project_dto.MemberItem, error) - // AddMember 添加项目成员 - AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error - // RemoveMember 移除项目成员 - RemoveMember(ctx *gin.Context, pid string, uid string) error - // EditProjectMember 修改成员信息 - EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error - // SimpleMembers 简易系统成员列表 - SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) - SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) -} +//type IProjectMemberController interface { +// // Members 获取项目成员列表 +// Members(ctx *gin.Context, pid string, keyword string) ([]*project_dto.MemberItem, error) +// // AddMember 添加项目成员 +// AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error +// // RemoveMember 移除项目成员 +// RemoveMember(ctx *gin.Context, pid string, uid string) error +// // EditProjectMember 修改成员信息 +// EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error +// // SimpleMembers 简易系统成员列表 +// SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) +// SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) +//} type IAppController interface { // CreateApp 创建应用 CreateApp(ctx *gin.Context, teamID string, project *project_dto.CreateApp) (*project_dto.App, error) - + UpdateApp(ctx *gin.Context, appId string, project *project_dto.UpdateApp) (*project_dto.App, error) SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*project_dto.AppItem, error) // SimpleApps 获取简易项目列表 @@ -58,10 +58,10 @@ func init() { autowire.Auto[IProjectController](func() reflect.Value { return reflect.ValueOf(new(imlProjectController)) }) - autowire.Auto[IProjectMemberController](func() reflect.Value { - return reflect.ValueOf(new(imlProjectMemberController)) - }) - + //autowire.Auto[IProjectMemberController](func() reflect.Value { + // return reflect.ValueOf(new(imlProjectMemberController)) + //}) + autowire.Auto[IAppController](func() reflect.Value { return reflect.ValueOf(new(imlAppController)) }) diff --git a/module/permit/project/iml.go b/module/permit/project/iml.go index b74f093..525e47c 100644 --- a/module/permit/project/iml.go +++ b/module/permit/project/iml.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/eolinker/ap-account/service/member" "github.com/eolinker/ap-account/service/role" "github.com/eolinker/ap-account/service/user" @@ -13,7 +14,6 @@ import ( permit_type "github.com/eolinker/apipark/service/permit-type" "github.com/eolinker/apipark/service/project" project_member "github.com/eolinker/apipark/service/project-member" - project_role "github.com/eolinker/apipark/service/project-role" "github.com/eolinker/apipark/service/team" team_member "github.com/eolinker/apipark/service/team-member" "github.com/eolinker/eosc/log" @@ -56,7 +56,7 @@ type imlProjectPermitModule struct { userGroupService user_group.IUserGroupService `autowired:""` userService user.IUserService `autowired:""` roleService role.IRoleService `autowired:""` - projectRoleService project_role.IProjectRoleService `autowired:""` + //projectRoleService project_role.IProjectRoleService `autowired:""` } func (m *imlProjectPermitModule) Permissions(ctx *gin.Context, projectId string) ([]string, error) { @@ -149,10 +149,10 @@ func (m *imlProjectPermitModule) getIdentity(ctx context.Context, p *project.Pro targets := make([]string, 0) targets = append(targets, permit_type.AnyOne.Key) - if p.Master == uid { - targets = append(targets, permit_type.ProjectMaster.Key) - targets = append(targets, permit_type.ProjectMember.Key) - } + //if p.Master == uid { + // targets = append(targets, permit_type.ProjectMaster.Key) + // targets = append(targets, permit_type.ProjectMember.Key) + //} if len(members) != 0 { // 用户属于该项目的成员,则是用户的全局用户组身份生效 targets = append(targets, permit_type.ProjectMember.Key) @@ -165,12 +165,12 @@ func (m *imlProjectPermitModule) getIdentity(ctx context.Context, p *project.Pro targets = append(targets, permit_type.UserGroup.KeyOf(mb.Come)) } } - roles, err := m.projectRoleService.Roles(ctx, p.Id, uid) - if err == nil && roles != nil { - targets = append(targets, utils.SliceToSlice(roles, func(s *project_role.ProjectRole) string { - return permit_type.Role.KeyOf(s.Rid) - })...) - } + //roles, err := m.projectRoleService.Roles(ctx, p.Id, uid) + //if err == nil && roles != nil { + // targets = append(targets, utils.SliceToSlice(roles, func(s *project_role.ProjectRole) string { + // return permit_type.Role.KeyOf(s.Rid) + // })...) + //} teamIdentity, err := m.identityTeamService.IdentifyTeam(ctx, p.Team, uid) if err != nil { diff --git a/module/project/dto/input.go b/module/project/dto/input.go index d4445b9..67738a7 100644 --- a/module/project/dto/input.go +++ b/module/project/dto/input.go @@ -1,10 +1,10 @@ package project_dto type CreateProject struct { - Id string `json:"id"` - Name string `json:"name"` - Prefix string `json:"prefix"` - Master string `json:"master"` + Id string `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix"` + //Master string `json:"master"` Partition []string `json:"partition" aocheck:"partition"` Description string `json:"description"` AsApp *bool `json:"as_app"` @@ -14,7 +14,7 @@ type CreateProject struct { type EditProject struct { Name *string `json:"name"` Description *string `json:"description"` - Master *string `json:"master" aocheck:"user"` + //Master *string `json:"master" aocheck:"user"` } type CreateApp struct { diff --git a/module/project/dto/output.go b/module/project/dto/output.go index 6fb22fd..f7312f1 100644 --- a/module/project/dto/output.go +++ b/module/project/dto/output.go @@ -13,8 +13,8 @@ type ProjectItem struct { ApiNum int64 `json:"api_num"` ServiceNum int64 `json:"service_num"` //SubscribeNum int64 `json:"subscribe_num"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` + Description string `json:"description"` + //Master auto.Label `json:"master" aolabel:"user"` //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` CreateTime auto.TimeLabel `json:"create_time"` UpdateTime auto.TimeLabel `json:"update_time"` @@ -55,8 +55,8 @@ type Project struct { Prefix string `json:"prefix,omitempty"` Description string `json:"description"` //Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - Master auto.Label `json:"master" aolabel:"user"` + Team auto.Label `json:"team" aolabel:"team"` + //Master auto.Label `json:"master" aolabel:"user"` //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` //OrganizationPrefix string `json:"organization_prefix,omitempty"` CreateTime auto.TimeLabel `json:"create_time"` @@ -82,11 +82,11 @@ func ToProject(model *project.Project) *Project { Prefix: model.Prefix, Description: model.Description, Team: auto.UUID(model.Team), - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - AsServer: model.AsServer, - AsApp: model.AsApp, + //Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + AsServer: model.AsServer, + AsApp: model.AsApp, } } diff --git a/module/project/iml.go b/module/project/iml.go index e9903c5..c02e9f0 100644 --- a/module/project/iml.go +++ b/module/project/iml.go @@ -12,16 +12,10 @@ import ( "github.com/eolinker/apipark/service/subscribe" "gorm.io/gorm" - "github.com/eolinker/ap-account/service/member" - "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/service" - project_role "github.com/eolinker/apipark/service/project-role" - - "github.com/eolinker/ap-account/service/user" - "github.com/eolinker/go-common/auto" team_member "github.com/eolinker/apipark/service/team-member" @@ -108,13 +102,13 @@ func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, Id: model.Id, Name: model.Name, Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + //Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + ServiceNum: serviceCount, + CanDelete: apiCount == 0 && serviceCount == 0, }) } return items, nil @@ -234,13 +228,13 @@ func (i *imlProjectModule) Search(ctx context.Context, teamID string, keyword st Id: model.Id, Name: model.Name, Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + //Master: auto.UUID(model.Master), + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + ServiceNum: serviceCount, + CanDelete: apiCount == 0 && serviceCount == 0, }) } return items, nil @@ -255,9 +249,9 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp Id: input.Id, Name: input.Name, Description: input.Description, - Master: input.Master, - Team: teamID, - Prefix: input.Prefix, + //Master: input.Master, + Team: teamID, + Prefix: input.Prefix, } if input.AsApp == nil { // 默认值为false @@ -274,21 +268,18 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") err := i.transaction.Transaction(ctx, func(ctx context.Context) error { - // 判断用户是否在团队内 - members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{input.Master}) - if err != nil { - return err - } - if len(members) == 0 { - return fmt.Errorf("master is not in team") - } + //// 判断用户是否在团队内 + //members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{input.Master}) + //if err != nil { + // return err + //} + //if len(members) == 0 { + // return fmt.Errorf("master is not in team") + //} - err = i.projectService.Create(ctx, mo) - if err != nil { - return err - } + return i.projectService.Create(ctx, mo) - return i.projectMemberService.AddMemberTo(ctx, input.Id, input.Master) + //return i.projectMemberService.AddMemberTo(ctx, input.Id, input.Master) }) if err != nil { return nil, err @@ -303,36 +294,36 @@ func (i *imlProjectModule) EditProject(ctx context.Context, id string, input *pr } err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - if input.Master != nil { - projectInfo, err := i.projectService.Get(ctx, id) - if err != nil { - return err - } - - // 判断用户是否在团队内 - members, err := i.teamMemberService.Members(ctx, []string{projectInfo.Team}, []string{*input.Master}) - if err != nil { - return err - } - if len(members) == 0 { - return fmt.Errorf("master is not in team") - } - // 负责人是否在项目内,若不在,则新增 - projectMembers, err := i.projectMemberService.Members(ctx, []string{id}, []string{*input.Master}) - if err != nil { - return err - } - if len(projectMembers) == 0 { - err = i.projectMemberService.AddMemberTo(ctx, id, *input.Master) - if err != nil { - return err - } - } - } + //if input.Master != nil { + //projectInfo, err := i.projectService.Get(ctx, id) + //if err != nil { + // return err + //} + + //// 判断用户是否在团队内 + //members, err := i.teamMemberService.Members(ctx, []string{projectInfo.Team}, []string{*input.Master}) + //if err != nil { + // return err + //} + //if len(members) == 0 { + // return fmt.Errorf("master is not in team") + //} + //// 负责人是否在项目内,若不在,则新增 + //projectMembers, err := i.projectMemberService.Members(ctx, []string{id}, []string{*input.Master}) + //if err != nil { + // return err + //} + //if len(projectMembers) == 0 { + // err = i.projectMemberService.AddMemberTo(ctx, id, *input.Master) + // if err != nil { + // return err + // } + //} + //} return i.projectService.Save(ctx, id, &project.EditProject{ Name: input.Name, Description: input.Description, - Master: input.Master, + //Master: input.Master, }) }) @@ -363,176 +354,177 @@ func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { return err } -var _ IProjectMemberModule = (*imlProjectMemberModule)(nil) - -type imlProjectMemberModule struct { - projectService project.IProjectService `autowired:""` - projectMemberService project_member.IMemberService `autowired:""` - projectRoleService project_role.IProjectRoleService `autowired:""` - userService user.IUserService `autowired:""` - transaction store.ITransaction `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` -} - -func (i *imlProjectMemberModule) SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { - - pro, err := i.projectService.Get(ctx, pid) - if err != nil { - return nil, err - } - - users, err := i.userService.Search(ctx, keyword, -1) - if err != nil { - return nil, err - } - userIds := utils.SliceToSlice(users, func(s *user.User) string { - return s.UID - }) - - members, err := i.teamMemberService.Members(ctx, []string{pro.Team}, userIds) - if err != nil { - return nil, err - } - userMaps := utils.SliceToMap(users, func(s *user.User) string { - return s.UID - }) - - return utils.SliceToSlice(members, func(s *member.Member) *project_dto.TeamMemberToAdd { - uf := userMaps[s.UID] - return &project_dto.TeamMemberToAdd{ - Id: uf.UID, - Name: uf.Username, - Email: uf.Email, - //Department: uf., - } - }, func(m *member.Member) bool { - _, has := userMaps[m.UID] - return has - }), nil - -} - -func (i *imlProjectMemberModule) SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { - members, err := i.projectMemberService.Members(ctx, []string{pid}, nil) - if err != nil { - return nil, err - } - userIds := utils.SliceToSlice(members, func(s *member.Member) string { - return s.UID - }) - users, err := i.userService.Get(ctx, userIds...) - if err != nil { - return nil, err - } - out := utils.SliceToSlice(users, func(s *user.User) *project_dto.SimpleMemberItem { - return &project_dto.SimpleMemberItem{ - Id: s.UID, - Name: s.Username, - } - }) - return out, nil -} - -func (i *imlProjectMemberModule) Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { - pInfo, err := i.projectService.Get(ctx, id) - if err != nil { - return nil, err - } - users, err := i.userService.Search(ctx, keyword, -1) - if err != nil { - return nil, err - } - userMap := make(map[string]*user.User) - userIds := make([]string, 0, len(users)) - for _, u := range users { - userIds = append(userIds, u.UID) - userMap[u.UID] = u - } - members, err := i.projectMemberService.Members(ctx, []string{id}, userIds) - if err != nil { - return nil, err - } - roleMap, err := i.projectRoleService.RoleMap(ctx, id) - if err != nil { - return nil, err - } - - out := utils.SliceToSlice(members, func(info *project_member.Member) *project_dto.MemberItem { - roleIDs := make([]string, 0, len(roleMap[info.UID])) - for _, r := range roleMap[info.UID] { - roleIDs = append(roleIDs, r.Rid) - } - item := &project_dto.MemberItem{ - User: auto.UUID(info.UID), - Email: "", - Roles: auto.List(roleIDs), - } - - u, ok := userMap[info.UID] - if ok { - item.Email = u.Email - } - if pInfo.Master == info.UID { - item.CanDelete = false - } else { - item.CanDelete = true - } - return item - - }) - return out, nil -} - -func (i *imlProjectMemberModule) AddMember(ctx context.Context, pid string, userIDs []string) error { - _, err := i.projectService.Get(ctx, pid) - if err != nil { - return err - } - return i.projectMemberService.AddMemberTo(ctx, pid, userIDs...) -} - -func (i *imlProjectMemberModule) RemoveMember(ctx context.Context, pid string, userIDs []string) error { - // 删除的成员是否有项目负责人 - info, err := i.projectService.Get(ctx, pid) - if err != nil { - return err - } - uids := make([]string, 0, len(userIDs)) - for _, id := range userIDs { - if id != info.Master { - uids = append(uids, id) - } - } - if len(uids) == 0 { - return nil - } - return i.projectMemberService.RemoveMemberFrom(ctx, pid, userIDs...) -} - -func (i *imlProjectMemberModule) EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error { - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - _, err := i.projectService.Get(ctx, pid) - if err != nil { - return err - } - _, err = i.userService.Get(ctx, uid) - if err != nil { - return err - } - - err = i.projectRoleService.DeleteRole(ctx, pid, uid) - if err != nil { - return err - } - for _, rid := range roles { - err = i.projectRoleService.AddRole(ctx, pid, uid, rid) - if err != nil { - return err - } - } - return nil - }) -} +//var _ IProjectMemberModule = (*imlProjectMemberModule)(nil) +// +//type imlProjectMemberModule struct { +// projectService project.IProjectService `autowired:""` +// projectMemberService project_member.IMemberService `autowired:""` +// //projectRoleService project_role.IProjectRoleService `autowired:""` +// userService user.IUserService `autowired:""` +// transaction store.ITransaction `autowired:""` +// teamMemberService team_member.ITeamMemberService `autowired:""` +//} +// +//func (i *imlProjectMemberModule) SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { +// +// pro, err := i.projectService.Get(ctx, pid) +// if err != nil { +// return nil, err +// } +// +// users, err := i.userService.Search(ctx, keyword, -1) +// if err != nil { +// return nil, err +// } +// userIds := utils.SliceToSlice(users, func(s *user.User) string { +// return s.UID +// }) +// +// members, err := i.teamMemberService.Members(ctx, []string{pro.Team}, userIds) +// if err != nil { +// return nil, err +// } +// userMaps := utils.SliceToMap(users, func(s *user.User) string { +// return s.UID +// }) +// +// return utils.SliceToSlice(members, func(s *member.Member) *project_dto.TeamMemberToAdd { +// uf := userMaps[s.UID] +// return &project_dto.TeamMemberToAdd{ +// Id: uf.UID, +// Name: uf.Username, +// Email: uf.Email, +// //Department: uf., +// } +// }, func(m *member.Member) bool { +// _, has := userMaps[m.UID] +// return has +// }), nil +// +//} +// +//func (i *imlProjectMemberModule) SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { +// members, err := i.projectMemberService.Members(ctx, []string{pid}, nil) +// if err != nil { +// return nil, err +// } +// userIds := utils.SliceToSlice(members, func(s *member.Member) string { +// return s.UID +// }) +// users, err := i.userService.Get(ctx, userIds...) +// if err != nil { +// return nil, err +// } +// out := utils.SliceToSlice(users, func(s *user.User) *project_dto.SimpleMemberItem { +// return &project_dto.SimpleMemberItem{ +// Id: s.UID, +// Name: s.Username, +// } +// }) +// return out, nil +//} + +// +//func (i *imlProjectMemberModule) Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { +// pInfo, err := i.projectService.Get(ctx, id) +// if err != nil { +// return nil, err +// } +// users, err := i.userService.Search(ctx, keyword, -1) +// if err != nil { +// return nil, err +// } +// userMap := make(map[string]*user.User) +// userIds := make([]string, 0, len(users)) +// for _, u := range users { +// userIds = append(userIds, u.UID) +// userMap[u.UID] = u +// } +// members, err := i.projectMemberService.Members(ctx, []string{id}, userIds) +// if err != nil { +// return nil, err +// } +// roleMap, err := i.projectRoleService.RoleMap(ctx, id) +// if err != nil { +// return nil, err +// } +// +// out := utils.SliceToSlice(members, func(info *project_member.Member) *project_dto.MemberItem { +// roleIDs := make([]string, 0, len(roleMap[info.UID])) +// for _, r := range roleMap[info.UID] { +// roleIDs = append(roleIDs, r.Rid) +// } +// item := &project_dto.MemberItem{ +// User: auto.UUID(info.UID), +// Email: "", +// Roles: auto.List(roleIDs), +// } +// +// u, ok := userMap[info.UID] +// if ok { +// item.Email = u.Email +// } +// if pInfo.Master == info.UID { +// item.CanDelete = false +// } else { +// item.CanDelete = true +// } +// return item +// +// }) +// return out, nil +//} +// +//func (i *imlProjectMemberModule) AddMember(ctx context.Context, pid string, userIDs []string) error { +// _, err := i.projectService.Get(ctx, pid) +// if err != nil { +// return err +// } +// return i.projectMemberService.AddMemberTo(ctx, pid, userIDs...) +//} +// +//func (i *imlProjectMemberModule) RemoveMember(ctx context.Context, pid string, userIDs []string) error { +// // 删除的成员是否有项目负责人 +// info, err := i.projectService.Get(ctx, pid) +// if err != nil { +// return err +// } +// uids := make([]string, 0, len(userIDs)) +// for _, id := range userIDs { +// if id != info.Master { +// uids = append(uids, id) +// } +// } +// if len(uids) == 0 { +// return nil +// } +// return i.projectMemberService.RemoveMemberFrom(ctx, pid, userIDs...) +//} +// +//func (i *imlProjectMemberModule) EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error { +// return i.transaction.Transaction(ctx, func(ctx context.Context) error { +// _, err := i.projectService.Get(ctx, pid) +// if err != nil { +// return err +// } +// _, err = i.userService.Get(ctx, uid) +// if err != nil { +// return err +// } +// +// err = i.projectRoleService.DeleteRole(ctx, pid, uid) +// if err != nil { +// return err +// } +// for _, rid := range roles { +// err = i.projectRoleService.AddRole(ctx, pid, uid, rid) +// if err != nil { +// return err +// } +// } +// return nil +// }) +//} var _ IAppModule = &imlAppModule{} @@ -558,9 +550,9 @@ func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *proj Id: input.Id, Name: input.Name, Description: input.Description, - Master: userId, - Team: teamID, - AsApp: true, + //Master: userId, + Team: teamID, + AsApp: true, } // 判断用户是否在团队内 members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{userId}) @@ -587,7 +579,7 @@ func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *proj } func (i *imlAppModule) UpdateApp(ctx context.Context, appId string, input *project_dto.UpdateApp) (*project_dto.App, error) { - userId := utils.UserId(ctx) + //userId := utils.UserId(ctx) info, err := i.projectService.Get(ctx, appId) if err != nil { return nil, err @@ -595,9 +587,9 @@ func (i *imlAppModule) UpdateApp(ctx context.Context, appId string, input *proje if !info.AsApp { return nil, fmt.Errorf("not app") } - if info.Master != userId { - return nil, fmt.Errorf("user is not app master, can not update") - } + //if info.Master != userId { + // return nil, fmt.Errorf("user is not app master, can not update") + //} err = i.projectService.Save(ctx, appId, &project.EditProject{ Name: input.Name, @@ -761,8 +753,8 @@ func (i *imlAppModule) DeleteApp(ctx context.Context, appId string) error { if !info.AsApp { return errors.New("not app, can not delete") } - if info.Master != utils.UserId(ctx) { - return errors.New("not master, can not delete") - } + //if info.Master != utils.UserId(ctx) { + // return errors.New("not master, can not delete") + //} return i.projectService.Delete(ctx, appId) } diff --git a/module/project/project.go b/module/project/project.go index 9850848..a8b457b 100644 --- a/module/project/project.go +++ b/module/project/project.go @@ -40,28 +40,28 @@ type IAppModule interface { DeleteApp(ctx context.Context, appId string) error } -type IProjectMemberModule interface { - // Members 获取项目成员列表 - Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) - // AddMember 添加项目成员 - AddMember(ctx context.Context, id string, userIDs []string) error - // RemoveMember 移除项目成员 - RemoveMember(ctx context.Context, id string, userIDs []string) error - // EditProjectMember 修改成员信息 - EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error - // SimpleMembers 简易成员列表 - SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) - SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) -} +//type IProjectMemberModule interface { +// // Members 获取项目成员列表 +// Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) +// // AddMember 添加项目成员 +// AddMember(ctx context.Context, id string, userIDs []string) error +// // RemoveMember 移除项目成员 +// RemoveMember(ctx context.Context, id string, userIDs []string) error +// // EditProjectMember 修改成员信息 +// EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error +// // SimpleMembers 简易成员列表 +// SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) +// SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) +//} func init() { autowire.Auto[IProjectModule](func() reflect.Value { m := new(imlProjectModule) return reflect.ValueOf(m) }) - autowire.Auto[IProjectMemberModule](func() reflect.Value { - return reflect.ValueOf(new(imlProjectMemberModule)) - }) + //autowire.Auto[IProjectMemberModule](func() reflect.Value { + // return reflect.ValueOf(new(imlProjectMemberModule)) + //}) autowire.Auto[IAppModule](func() reflect.Value { return reflect.ValueOf(new(imlAppModule)) diff --git a/plugins/core/core.go b/plugins/core/core.go index 2d4fc8e..7b73a68 100644 --- a/plugins/core/core.go +++ b/plugins/core/core.go @@ -54,13 +54,13 @@ func (d *Driver) Create() (pm3.IPlugin, error) { } type plugin struct { - partitionController partition.IPartitionController `autowired:""` - certificateController certificate.ICertificateController `autowired:""` - teamManagerController team_manager.ITeamManagerController `autowired:""` - myTeamController my_team.ITeamController `autowired:""` - appController project.IAppController `autowired:""` - projectController project.IProjectController `autowired:""` - projectMemberController project.IProjectMemberController `autowired:""` + partitionController partition.IPartitionController `autowired:""` + certificateController certificate.ICertificateController `autowired:""` + teamManagerController team_manager.ITeamManagerController `autowired:""` + myTeamController my_team.ITeamController `autowired:""` + appController project.IAppController `autowired:""` + projectController project.IProjectController `autowired:""` + //projectMemberController project.IProjectMemberController `autowired:""` serviceController service.IServiceController `autowired:""` catalogueController catalogue.ICatalogueController `autowired:""` upstreamController upstream.IUpstreamController `autowired:""` diff --git a/plugins/core/project.go b/plugins/core/project.go index 80814ff..9592887 100644 --- a/plugins/core/project.go +++ b/plugins/core/project.go @@ -2,7 +2,7 @@ package core import ( "net/http" - + "github.com/eolinker/go-common/pm3" ) @@ -13,20 +13,20 @@ func (p *plugin) ProjectApi() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/info", []string{"context", "query:project", "body"}, []string{"project"}, p.projectController.EditProject), pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/info", []string{"context", "query:project"}, nil, p.projectController.DeleteProject), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_projects", []string{"context", "query:team", "query:keyword"}, []string{"projects"}, p.projectController.SearchMyProjects), - + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/projects/mine", []string{"context", "query:keyword"}, []string{"projects"}, p.projectController.MySimpleProjects), - + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/projects", []string{"context", "query:keyword", "query:partition"}, []string{"projects"}, p.projectController.SimpleProjects), - - // 项目成员相关 - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.Members), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/project/members", []string{"context", "query:project"}, []string{"members"}, p.projectMemberController.SimpleMembers), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members/toadd", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.SimpleMembersToAdd), - - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/member", []string{"context", "query:project", "body"}, nil, p.projectMemberController.AddMember), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/member", []string{"context", "query:project", "query:user"}, nil, p.projectMemberController.RemoveMember), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/member", []string{"context", "query:project", "query:user", "body"}, nil, p.projectMemberController.EditProjectMember), - + + //// 项目成员相关 + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.Members), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/project/members", []string{"context", "query:project"}, []string{"members"}, p.projectMemberController.SimpleMembers), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members/toadd", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.SimpleMembersToAdd), + // + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/member", []string{"context", "query:project", "body"}, nil, p.projectMemberController.AddMember), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/member", []string{"context", "query:project", "query:user"}, nil, p.projectMemberController.RemoveMember), + //pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/member", []string{"context", "query:project", "query:user", "body"}, nil, p.projectMemberController.EditProjectMember), + // 应用相关 pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/info", []string{"context", "query:app"}, []string{"project"}, p.appController.GetApp), pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/app", []string{"context", "query:app"}, nil, p.appController.DeleteApp), diff --git a/service/project-role/iml.go b/service/project-role/iml.go deleted file mode 100644 index 293e78f..0000000 --- a/service/project-role/iml.go +++ /dev/null @@ -1,74 +0,0 @@ -package project_role - -import ( - "context" - "github.com/eolinker/go-common/utils" - "time" - - "github.com/eolinker/apipark/stores/project" -) - -var ( - _ IProjectRoleService = (*imlProjectRoleService)(nil) -) - -type imlProjectRoleService struct { - projectRoleStore project.IMemberRoleStore `autowired:""` -} - -func (i *imlProjectRoleService) AddRole(ctx context.Context, pid string, uid string, rid string) error { - return i.projectRoleStore.Insert(ctx, &project.MemberRole{ - Pid: pid, - Uid: uid, - Rid: rid, - CreateTime: time.Now(), - }) -} - -func (i *imlProjectRoleService) DeleteRole(ctx context.Context, pid string, uid string) error { - _, err := i.projectRoleStore.DeleteWhere(ctx, map[string]interface{}{ - "pid": pid, - "uid": uid, - }) - return err -} - -func (i *imlProjectRoleService) Count(ctx context.Context, condition map[string]interface{}) (int64, error) { - return i.projectRoleStore.CountWhere(ctx, condition) -} - -func (i *imlProjectRoleService) Roles(ctx context.Context, pid string, uid ...string) ([]*ProjectRole, error) { - condition := map[string]interface{}{ - "pid": pid, - } - if len(uid) > 0 { - condition["uid"] = uid - } - roles, err := i.projectRoleStore.List(ctx, condition) - if err != nil { - return nil, err - } - return utils.SliceToSlice(roles, func(role *project.MemberRole) *ProjectRole { - return &ProjectRole{ - Pid: role.Pid, - Uid: role.Uid, - Rid: role.Rid, - CreateTime: role.CreateTime, - } - }), nil -} - -func (i *imlProjectRoleService) RoleMap(ctx context.Context, pid string, uid ...string) (map[string][]*ProjectRole, error) { - roles, err := i.Roles(ctx, pid, uid...) - if err != nil { - return nil, err - } - return utils.SliceToMapArray(roles, func(t *ProjectRole) string { - return t.Uid - }), nil - -} - -func (i *imlProjectRoleService) OnComplete() { - -} diff --git a/service/project-role/model.go b/service/project-role/model.go deleted file mode 100644 index dfb2f10..0000000 --- a/service/project-role/model.go +++ /dev/null @@ -1,12 +0,0 @@ -package project_role - -import ( - "time" -) - -type ProjectRole struct { - Pid string - Uid string - Rid string - CreateTime time.Time -} diff --git a/service/project-role/service.go b/service/project-role/service.go deleted file mode 100644 index c740516..0000000 --- a/service/project-role/service.go +++ /dev/null @@ -1,22 +0,0 @@ -package project_role - -import ( - "context" - "reflect" - - "github.com/eolinker/go-common/autowire" -) - -type IProjectRoleService interface { - RoleMap(ctx context.Context, pid string, uid ...string) (map[string][]*ProjectRole, error) - Roles(ctx context.Context, pid string, uid ...string) ([]*ProjectRole, error) - AddRole(ctx context.Context, pid string, uid string, rid string) error - DeleteRole(ctx context.Context, pid string, uid string) error - Count(ctx context.Context, condition map[string]interface{}) (int64, error) -} - -func init() { - autowire.Auto[IProjectRoleService](func() reflect.Value { - return reflect.ValueOf(new(imlProjectRoleService)) - }) -} diff --git a/service/project/iml.go b/service/project/iml.go index 8815506..abb98be 100644 --- a/service/project/iml.go +++ b/service/project/iml.go @@ -111,9 +111,9 @@ func createEntityHandler(i *CreateProject) *project.Project { Description: i.Description, Prefix: i.Prefix, Team: i.Team, - Master: i.Master, - AsServer: i.AsServer, - AsApp: i.AsApp, + //Master: i.Master, + AsServer: i.AsServer, + AsApp: i.AsApp, } } func updateHandler(e *project.Project, i *EditProject) { @@ -123,7 +123,7 @@ func updateHandler(e *project.Project, i *EditProject) { if i.Description != nil { e.Description = *i.Description } - if i.Master != nil { - e.Master = *i.Master - } + //if i.Master != nil { + // e.Master = *i.Master + //} } diff --git a/service/project/model.go b/service/project/model.go index c23d773..cf3b729 100644 --- a/service/project/model.go +++ b/service/project/model.go @@ -11,12 +11,12 @@ type Project struct { Name string Description string Team string - Master string - Prefix string - AsServer bool - AsApp bool - CreateTime time.Time - UpdateTime time.Time + //Master string + Prefix string + AsServer bool + AsApp bool + CreateTime time.Time + UpdateTime time.Time } func FromEntity(e *project.Project) *Project { @@ -25,12 +25,12 @@ func FromEntity(e *project.Project) *Project { Name: e.Name, Description: e.Description, Team: e.Team, - Master: e.Master, - Prefix: e.Prefix, - AsServer: e.AsServer, - AsApp: e.AsApp, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, + //Master: e.Master, + Prefix: e.Prefix, + AsServer: e.AsServer, + AsApp: e.AsApp, + CreateTime: e.CreateAt, + UpdateTime: e.UpdateAt, } } @@ -38,17 +38,17 @@ type CreateProject struct { Id string Name string Description string - Master string - Team string - Prefix string - AsServer bool - AsApp bool + //Master string + Team string + Prefix string + AsServer bool + AsApp bool } type EditProject struct { Name *string Description *string - Master *string + //Master *string } type Partition struct { diff --git a/stores/project/model.go b/stores/project/model.go index 9617952..0b4117f 100644 --- a/stores/project/model.go +++ b/stores/project/model.go @@ -10,7 +10,6 @@ type Project struct { Description string `gorm:"size:255;not null;column:description;comment:description"` Prefix string `gorm:"size:255;not null;column:prefix;comment:前缀"` Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id - Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` @@ -25,20 +24,20 @@ func (p *Project) TableName() string { return "project" } -type MemberRole struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - Pid string `gorm:"size:36;not null;column:pid;index:pid;comment:项目id;uniqueIndex:pid_uid_rid;"` - Uid string `gorm:"size:36;not null;column:uid;index:uid;comment:用户id;uniqueIndex:pid_uid_rid;"` - Rid string `gorm:"size:36;not null;column:rid;index:rid;comment:角色id;uniqueIndex:pid_uid_rid;"` - CreateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` -} - -func (m *MemberRole) IdValue() int64 { - return m.Id -} -func (m *MemberRole) TableName() string { - return "project_role" -} +//type MemberRole struct { +// Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` +// Pid string `gorm:"size:36;not null;column:pid;index:pid;comment:项目id;uniqueIndex:pid_uid_rid;"` +// Uid string `gorm:"size:36;not null;column:uid;index:uid;comment:用户id;uniqueIndex:pid_uid_rid;"` +// Rid string `gorm:"size:36;not null;column:rid;index:rid;comment:角色id;uniqueIndex:pid_uid_rid;"` +// CreateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` +//} +// +//func (m *MemberRole) IdValue() int64 { +// return m.Id +//} +//func (m *MemberRole) TableName() string { +// return "project_role" +//} type Authorization struct { Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` diff --git a/stores/project/store.go b/stores/project/store.go index 642dc88..9643e15 100644 --- a/stores/project/store.go +++ b/stores/project/store.go @@ -16,12 +16,12 @@ type imlProjectStore struct { type IMemberStore member.IMemberStore -type IMemberRoleStore interface { - store.IBaseStore[MemberRole] -} -type imlMemberRoleStore struct { - store.Store[MemberRole] -} +//type IMemberRoleStore interface { +// store.IBaseStore[MemberRole] +//} +//type imlMemberRoleStore struct { +// store.Store[MemberRole] +//} type IAuthorizationStore interface { store.ISearchStore[Authorization] @@ -38,9 +38,9 @@ func init() { autowire.Auto[IMemberStore](func() reflect.Value { return reflect.ValueOf(member.NewMemberStore("project")) }) - autowire.Auto[IMemberRoleStore](func() reflect.Value { - return reflect.ValueOf(new(imlMemberRoleStore)) - }) + //autowire.Auto[IMemberRoleStore](func() reflect.Value { + // return reflect.ValueOf(new(imlMemberRoleStore)) + //}) autowire.Auto[IAuthorizationStore](func() reflect.Value { return reflect.ValueOf(new(imlAuthorizationStore)) }) From 4ab2d8ca18137cd1e394d73ba87be48c16aa71be Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 29 Jul 2024 17:56:56 +0800 Subject: [PATCH 03/19] =?UTF-8?q?=E6=9D=83=E9=99=90=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/permit_project/iml.go | 38 ---- controller/permit_project/project.go | 22 -- controller/permit_system/iml.go | 80 ------- controller/permit_system/permit.go | 28 --- controller/permit_team/iml.go | 35 --- controller/permit_team/team.go | 22 -- controller/project/project.go | 3 - go.mod | 5 + go.sum | 4 - module/permit/project/iml.go | 8 +- module/permit/team/iml.go | 8 +- module/project/iml.go | 52 +++-- plugins/core/core.go | 3 + plugins/permit/plugin.go | 15 +- plugins/permit/project.go | 11 +- plugins/permit/system.go | 23 +- plugins/permit/team.go | 11 +- resources/access/access.go | 1 + resources/access/access.yaml | 313 +++++++++++++++++++-------- resources/access/access_test.go | 29 +++ resources/access/role.go | 24 ++ resources/access/role.yaml | 114 ++++++++++ service/project-member/model.go | 5 - service/project-member/service.go | 17 -- stores/project/model.go | 15 -- 25 files changed, 457 insertions(+), 429 deletions(-) delete mode 100644 controller/permit_project/iml.go delete mode 100644 controller/permit_project/project.go delete mode 100644 controller/permit_system/iml.go delete mode 100644 controller/permit_system/permit.go delete mode 100644 controller/permit_team/iml.go delete mode 100644 controller/permit_team/team.go create mode 100644 resources/access/access_test.go create mode 100644 resources/access/role.go create mode 100644 resources/access/role.yaml delete mode 100644 service/project-member/model.go delete mode 100644 service/project-member/service.go diff --git a/controller/permit_project/iml.go b/controller/permit_project/iml.go deleted file mode 100644 index fc60fde..0000000 --- a/controller/permit_project/iml.go +++ /dev/null @@ -1,38 +0,0 @@ -package permit_project - -import ( - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/apipark/module/permit/project" - "github.com/gin-gonic/gin" -) - -var ( - _ IProjectPermitController = (*imlProjectPermitController)(nil) -) - -type imlProjectPermitController struct { - projectPermitModule project.IProjectPermitModule `autowired:""` -} - -func (c *imlProjectPermitController) Permissions(ctx *gin.Context, project string) ([]string, error) { - return c.projectPermitModule.Permissions(ctx, project) -} - -func (c *imlProjectPermitController) Grant(ctx *gin.Context, project string, input *permit_dto.SetGrant) error { - return c.projectPermitModule.Grant(ctx, project, input.Access, input.Key) -} - -func (c *imlProjectPermitController) Remove(ctx *gin.Context, project string, access string, key string) error { - return c.projectPermitModule.Remove(ctx, project, access, key) - -} - -func (c *imlProjectPermitController) List(ctx *gin.Context, project string) ([]*permit_dto.Permission, error) { - - return c.projectPermitModule.ProjectAccess(ctx, project) - -} - -func (c *imlProjectPermitController) Options(ctx *gin.Context, project string, keyword string) ([]*permit_dto.Option, error) { - return c.projectPermitModule.Options(ctx, project, keyword) -} diff --git a/controller/permit_project/project.go b/controller/permit_project/project.go deleted file mode 100644 index ef1f899..0000000 --- a/controller/permit_project/project.go +++ /dev/null @@ -1,22 +0,0 @@ -package permit_project - -import ( - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -type IProjectPermitController interface { - Grant(ctx *gin.Context, project string, input *permit_dto.SetGrant) error - Remove(ctx *gin.Context, project string, access string, key string) error - List(ctx *gin.Context, project string) ([]*permit_dto.Permission, error) - Options(ctx *gin.Context, project string, keyword string) ([]*permit_dto.Option, error) - Permissions(ctx *gin.Context, project string) ([]string, error) -} - -func init() { - autowire.Auto[IProjectPermitController](func() reflect.Value { - return reflect.ValueOf(new(imlProjectPermitController)) - }) -} diff --git a/controller/permit_system/iml.go b/controller/permit_system/iml.go deleted file mode 100644 index 75a08d7..0000000 --- a/controller/permit_system/iml.go +++ /dev/null @@ -1,80 +0,0 @@ -package permit_system - -import ( - permit_identity "github.com/eolinker/apipark/middleware/permit/identity" - "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/apipark/module/permit/system" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" -) - -var ( - _ ISystemPermitController = (*imlSystemPermitController)(nil) - _ autowire.Complete = (*imlSystemPermitController)(nil) -) - -type imlSystemPermitController struct { - systemPermitModule system.ISystemPermitModule `autowired:""` - - identitySystem permit_identity.IdentitySystemService `autowired:""` -} - -func (c *imlSystemPermitController) Permissions(ctx *gin.Context) ([]string, error) { - return c.systemPermitModule.Permissions(ctx) -} - -func (c *imlSystemPermitController) RemoveTemplateForTeam(ctx *gin.Context, access string, key string) error { - return c.systemPermitModule.RemoveTeamTemplateAccess(ctx, access, key) -} - -func (c *imlSystemPermitController) RemoveTemplateForSystem(ctx *gin.Context, access string, key string) error { - return c.systemPermitModule.RemoveProjectTemplateAccess(ctx, access, key) -} - -func (c *imlSystemPermitController) GrantTemplateForTeam(ctx *gin.Context, input *permit_dto.SetGrant) error { - return c.systemPermitModule.GrantTemplateForTeam(ctx, input.Access, input.Key) -} - -func (c *imlSystemPermitController) GrantTemplateForProject(ctx *gin.Context, input *permit_dto.SetGrant) error { - return c.systemPermitModule.GrantTemplateForProject(ctx, input.Access, input.Key) -} - -func (c *imlSystemPermitController) OptionsForTeamTemplate(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) { - return c.systemPermitModule.OptionsForTeamTemplate(ctx, keyword) -} - -func (c *imlSystemPermitController) OptionsForProjectTemplate(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) { - return c.systemPermitModule.OptionsForProjectTemplate(ctx, keyword) -} - -func (c *imlSystemPermitController) OnComplete() { - -} - -func (c *imlSystemPermitController) Grant(ctx *gin.Context, input *permit_dto.SetGrant) error { - return c.systemPermitModule.GrantSystem(ctx, input.Access, input.Key) -} - -func (c *imlSystemPermitController) Remove(ctx *gin.Context, access string, key string) error { - return c.systemPermitModule.RemoveSystemAccess(ctx, access, key) -} - -func (c *imlSystemPermitController) List(ctx *gin.Context) ([]*permit_dto.Permission, []*permit_dto.Permission, []*permit_dto.Permission, error) { - systemAccess, err := c.systemPermitModule.SystemAccess(ctx) - if err != nil { - return nil, nil, nil, err - } - teamAccess, err := c.systemPermitModule.TeamAccess(ctx) - if err != nil { - return nil, nil, nil, err - } - projectAccess, err := c.systemPermitModule.ProjectAccess(ctx) - if err != nil { - return nil, nil, nil, err - } - return systemAccess, teamAccess, projectAccess, err -} - -func (c *imlSystemPermitController) Options(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) { - return c.systemPermitModule.OptionsForSystem(ctx, keyword) -} diff --git a/controller/permit_system/permit.go b/controller/permit_system/permit.go deleted file mode 100644 index 7bfcf4a..0000000 --- a/controller/permit_system/permit.go +++ /dev/null @@ -1,28 +0,0 @@ -package permit_system - -import ( - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -type ISystemPermitController interface { - Grant(ctx *gin.Context, input *permit_dto.SetGrant) error - GrantTemplateForTeam(ctx *gin.Context, input *permit_dto.SetGrant) error - GrantTemplateForProject(ctx *gin.Context, input *permit_dto.SetGrant) error - Remove(ctx *gin.Context, access string, key string) error - RemoveTemplateForTeam(ctx *gin.Context, access string, key string) error - RemoveTemplateForSystem(ctx *gin.Context, access string, key string) error - List(ctx *gin.Context) ([]*permit_dto.Permission, []*permit_dto.Permission, []*permit_dto.Permission, error) - Options(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) - OptionsForTeamTemplate(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) - OptionsForProjectTemplate(ctx *gin.Context, keyword string) ([]*permit_dto.Option, error) - Permissions(ctx *gin.Context) ([]string, error) -} - -func init() { - autowire.Auto[ISystemPermitController](func() reflect.Value { - return reflect.ValueOf(new(imlSystemPermitController)) - }) -} diff --git a/controller/permit_team/iml.go b/controller/permit_team/iml.go deleted file mode 100644 index 7196ac5..0000000 --- a/controller/permit_team/iml.go +++ /dev/null @@ -1,35 +0,0 @@ -package permit_team - -import ( - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/apipark/module/permit/team" - "github.com/gin-gonic/gin" -) - -var ( - _ ITeamPermitController = (*imlTeamPermitController)(nil) -) - -type imlTeamPermitController struct { - teamPermitModule team.ITeamPermitModule `autowired:""` -} - -func (c *imlTeamPermitController) Permissions(ctx *gin.Context, team string) ([]string, error) { - return c.teamPermitModule.Permissions(ctx, team) -} - -func (c *imlTeamPermitController) Grant(ctx *gin.Context, team string, input *permit_dto.SetGrant) error { - return c.teamPermitModule.Grant(ctx, team, input.Access, input.Key) -} - -func (c *imlTeamPermitController) Remove(ctx *gin.Context, team string, access string, key string) error { - return c.teamPermitModule.Remove(ctx, team, access, key) -} - -func (c *imlTeamPermitController) List(ctx *gin.Context, team string) ([]*permit_dto.Permission, error) { - return c.teamPermitModule.TeamAccess(ctx, team) -} - -func (c *imlTeamPermitController) Options(ctx *gin.Context, team string, keyword string) ([]*permit_dto.Option, error) { - return c.teamPermitModule.Options(ctx, team, keyword) -} diff --git a/controller/permit_team/team.go b/controller/permit_team/team.go deleted file mode 100644 index 085b710..0000000 --- a/controller/permit_team/team.go +++ /dev/null @@ -1,22 +0,0 @@ -package permit_team - -import ( - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -type ITeamPermitController interface { - Grant(ctx *gin.Context, team string, input *permit_dto.SetGrant) error - Remove(ctx *gin.Context, team string, access string, key string) error - List(ctx *gin.Context, team string) ([]*permit_dto.Permission, error) - Options(ctx *gin.Context, team string, keyword string) ([]*permit_dto.Option, error) - Permissions(ctx *gin.Context, team string) ([]string, error) -} - -func init() { - autowire.Auto[ITeamPermitController](func() reflect.Value { - return reflect.ValueOf(new(imlTeamPermitController)) - }) -} diff --git a/controller/project/project.go b/controller/project/project.go index 127e8a0..a3de0cc 100644 --- a/controller/project/project.go +++ b/controller/project/project.go @@ -58,9 +58,6 @@ func init() { autowire.Auto[IProjectController](func() reflect.Value { return reflect.ValueOf(new(imlProjectController)) }) - //autowire.Auto[IProjectMemberController](func() reflect.Value { - // return reflect.ValueOf(new(imlProjectMemberController)) - //}) autowire.Auto[IAppController](func() reflect.Value { return reflect.ValueOf(new(imlAppController)) diff --git a/go.mod b/go.mod index 44b2f0e..2612bad 100644 --- a/go.mod +++ b/go.mod @@ -65,3 +65,8 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.5.2 // indirect ) + +replace ( + github.com/eolinker/ap-account => ../ap-account + github.com/eolinker/go-common => ../go-common +) diff --git a/go.sum b/go.sum index 08f9336..55db0a8 100644 --- a/go.sum +++ b/go.sum @@ -23,12 +23,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/eolinker/ap-account v1.0.2 h1:wSPBrOu0FoL27lAkYVOdIXak6YUVq2nCP6dw+StQDz8= -github.com/eolinker/ap-account v1.0.2/go.mod h1:DmBBodZRFmQLeppKY63PCnNGL/IGjT6FIOWCpAK0vSg= github.com/eolinker/eosc v0.17.3 h1:sr2yT+v/AsqEdciRaaZZj0zL9pTufR5RvDW6+65hraQ= github.com/eolinker/eosc v0.17.3/go.mod h1:xgq816hpanlMXFtZw7Ztdctb1eEk9UPHchY4NfFO6Cw= -github.com/eolinker/go-common v1.0.0 h1:gqR0d6juRrJVc6OKpl7DFB5Xml5uGx6q9eCetrPqEq8= -github.com/eolinker/go-common v1.0.0/go.mod h1:Kb/jENMN1mApnodvRgV4YwO9FJby1Jkt2EUjrBjvSX4= github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I= github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= diff --git a/module/permit/project/iml.go b/module/permit/project/iml.go index 525e47c..51b9428 100644 --- a/module/permit/project/iml.go +++ b/module/permit/project/iml.go @@ -309,10 +309,10 @@ func (m *imlProjectPermitModule) ProjectAccess(ctx *gin.Context, projectId strin result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - Description: s.Desc, - Grant: nil, + Access: s.Name, + Name: s.CName, + //Description: s.Desc, + Grant: nil, } if gs, has := grants[r.Access]; has { r.Grant = permit_type.TargetsOf(gs...) diff --git a/module/permit/team/iml.go b/module/permit/team/iml.go index 10c5f6c..494a312 100644 --- a/module/permit/team/iml.go +++ b/module/permit/team/iml.go @@ -247,10 +247,10 @@ func (m *imlTeamPermitModule) TeamAccess(ctx *gin.Context, teamId string) ([]*pe result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - Description: s.Desc, - Grant: nil, + Access: s.Name, + Name: s.CName, + //Description: s.Desc, + Grant: nil, } if gs, has := grants[r.Access]; has { r.Grant = permit_type.TargetsOf(gs...) diff --git a/module/project/iml.go b/module/project/iml.go index c02e9f0..6395ae8 100644 --- a/module/project/iml.go +++ b/module/project/iml.go @@ -20,8 +20,6 @@ import ( team_member "github.com/eolinker/apipark/service/team-member" - project_member "github.com/eolinker/apipark/service/project-member" - "github.com/eolinker/go-common/store" "github.com/google/uuid" @@ -40,14 +38,14 @@ var ( ) type imlProjectModule struct { - partitionService partition.IPartitionService `autowired:""` - projectService project.IProjectService `autowired:""` - projectMemberService project_member.IMemberService `autowired:""` - teamService team.ITeamService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - serviceService service.IServiceService `autowired:""` - apiService api.IAPIService `autowired:""` - transaction store.ITransaction `autowired:""` + partitionService partition.IPartitionService `autowired:""` + projectService project.IProjectService `autowired:""` + //projectMemberService project_member.IMemberService `autowired:""` + teamService team.ITeamService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + serviceService service.IServiceService `autowired:""` + apiService api.IAPIService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlProjectModule) searchMyProjects(ctx context.Context, teamId string, keyword string) ([]*project.Project, error) { @@ -343,11 +341,11 @@ func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { if count > 0 { return fmt.Errorf("project has apis, can not delete") } - // 删除项目成员 - err = i.projectMemberService.Delete(ctx, id) - if err != nil { - return err - } + //// 删除项目成员 + //err = i.projectMemberService.Delete(ctx, id) + //if err != nil { + // return err + //} return i.projectService.Delete(ctx, id) }) @@ -529,12 +527,12 @@ func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { var _ IAppModule = &imlAppModule{} type imlAppModule struct { - teamService team.ITeamService `autowired:""` - projectService project.IProjectService `autowired:""` - projectMemberService project_member.IMemberService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - transaction store.ITransaction `autowired:""` + teamService team.ITeamService `autowired:""` + projectService project.IProjectService `autowired:""` + //projectMemberService project_member.IMemberService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) { @@ -565,12 +563,12 @@ func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *proj err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.projectService.Create(ctx, mo) - if err != nil { - return err - } - - return i.projectMemberService.AddMemberTo(ctx, input.Id, userId) + return i.projectService.Create(ctx, mo) + //if err != nil { + // return err + //} + // + //return i.projectMemberService.AddMemberTo(ctx, input.Id, userId) }) if err != nil { return nil, err diff --git a/plugins/core/core.go b/plugins/core/core.go index 7b73a68..330c8c8 100644 --- a/plugins/core/core.go +++ b/plugins/core/core.go @@ -3,6 +3,8 @@ package core import ( "net/http" + "github.com/eolinker/ap-account/controller/role" + "github.com/eolinker/apipark/controller/common" plugin_partition "github.com/eolinker/apipark/controller/plugin-partition" @@ -68,6 +70,7 @@ type plugin struct { subscribeController subscribe.ISubscribeController `autowired:""` projectAuthorizationController project_authorization.IProjectAuthorizationController `autowired:""` releaseController release.IReleaseController `autowired:""` + roleController role.IRoleController `autowired:""` subscribeApprovalController subscribe.ISubscribeApprovalController `autowired:""` dynamicModuleController dynamic_module.IDynamicModuleController `autowired:""` topologyController topology.ITopologyController `autowired:""` diff --git a/plugins/permit/plugin.go b/plugins/permit/plugin.go index 1cac086..f9e9af1 100644 --- a/plugins/permit/plugin.go +++ b/plugins/permit/plugin.go @@ -1,9 +1,6 @@ package permit import ( - "github.com/eolinker/apipark/controller/permit_project" - "github.com/eolinker/apipark/controller/permit_system" - "github.com/eolinker/apipark/controller/permit_team" permit_middleware "github.com/eolinker/apipark/middleware/permit" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/pm3" @@ -16,12 +13,12 @@ var ( ) type pluginPermit struct { - systemPermitController permit_system.ISystemPermitController `autowired:""` - teamPermitController permit_team.ITeamPermitController `autowired:""` - projectPermitController permit_project.IProjectPermitController `autowired:""` - apis []pm3.Api - middlewares []pm3.IMiddleware - permitChecker permit_middleware.IPermitMiddleware `autowired:""` + //systemPermitController permit_system.ISystemPermitController `autowired:""` + //teamPermitController permit_team.ITeamPermitController `autowired:""` + //projectPermitController permit_project.IProjectPermitController `autowired:""` + apis []pm3.Api + middlewares []pm3.IMiddleware + permitChecker permit_middleware.IPermitMiddleware `autowired:""` } func (p *pluginPermit) OnComplete() { diff --git a/plugins/permit/project.go b/plugins/permit/project.go index 190842d..d88828d 100644 --- a/plugins/permit/project.go +++ b/plugins/permit/project.go @@ -2,15 +2,14 @@ package permit import ( "github.com/eolinker/go-common/pm3" - "net/http" ) func (p *pluginPermit) getSProjectPermitApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permissions", []string{"context", "query:project"}, []string{"permissions"}, p.projectPermitController.List), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/setting/permission", []string{"context", "query:project", "body"}, []string{}, p.projectPermitController.Grant), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/setting/permission", []string{"context", "query:project", "query:access", "query:key"}, []string{}, p.projectPermitController.Remove), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permission/options", []string{"context", "query:project", "query:keyword"}, []string{"options"}, p.projectPermitController.Options), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/project", []string{"context", "query:project"}, []string{"access"}, p.projectPermitController.Permissions), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permissions", []string{"context", "query:project"}, []string{"permissions"}, p.projectPermitController.List), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/setting/permission", []string{"context", "query:project", "body"}, []string{}, p.projectPermitController.Grant), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/setting/permission", []string{"context", "query:project", "query:access", "query:key"}, []string{}, p.projectPermitController.Remove), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permission/options", []string{"context", "query:project", "query:keyword"}, []string{"options"}, p.projectPermitController.Options), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/project", []string{"context", "query:project"}, []string{"access"}, p.projectPermitController.Permissions), } } diff --git a/plugins/permit/system.go b/plugins/permit/system.go index 0221441..5b6837e 100644 --- a/plugins/permit/system.go +++ b/plugins/permit/system.go @@ -2,21 +2,20 @@ package permit import ( "github.com/eolinker/go-common/pm3" - "net/http" ) func (p *pluginPermit) getSystemApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permissions", []string{"context"}, []string{"system", "team", "project"}, p.systemPermitController.List), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission", []string{"context", "body"}, []string{}, p.systemPermitController.Grant), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/team", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForTeam), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/project", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForProject), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/team", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/project", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.Options), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/team", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForTeamTemplate), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/project", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForProjectTemplate), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/system", []string{"context"}, []string{"access"}, p.systemPermitController.Permissions), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permissions", []string{"context"}, []string{"system", "team", "project"}, p.systemPermitController.List), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission", []string{"context", "body"}, []string{}, p.systemPermitController.Grant), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/team", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForTeam), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/project", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForProject), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/team", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/project", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.Options), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/team", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForTeamTemplate), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/project", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForProjectTemplate), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/system", []string{"context"}, []string{"access"}, p.systemPermitController.Permissions), } } diff --git a/plugins/permit/team.go b/plugins/permit/team.go index fc3e6a5..c2eca53 100644 --- a/plugins/permit/team.go +++ b/plugins/permit/team.go @@ -2,15 +2,14 @@ package permit import ( "github.com/eolinker/go-common/pm3" - "net/http" ) func (p *pluginPermit) getSTeamPermitApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permissions", []string{"context", "query:team"}, []string{"permissions"}, p.teamPermitController.List), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/setting/permission", []string{"context", "query:team", "body"}, []string{}, p.teamPermitController.Grant), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/setting/permission", []string{"context", "query:team", "query:access", "query:key"}, []string{}, p.teamPermitController.Remove), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permission/options", []string{"context", "query:team", "query:keyword"}, []string{"options"}, p.teamPermitController.Options), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/team", []string{"context", "query:team"}, []string{"access"}, p.teamPermitController.Permissions), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permissions", []string{"context", "query:team"}, []string{"permissions"}, p.teamPermitController.List), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/setting/permission", []string{"context", "query:team", "body"}, []string{}, p.teamPermitController.Grant), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/setting/permission", []string{"context", "query:team", "query:access", "query:key"}, []string{}, p.teamPermitController.Remove), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permission/options", []string{"context", "query:team", "query:keyword"}, []string{"options"}, p.teamPermitController.Options), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/team", []string{"context", "query:team"}, []string{"access"}, p.teamPermitController.Permissions), } } diff --git a/resources/access/access.go b/resources/access/access.go index 80e1828..4a56b8e 100644 --- a/resources/access/access.go +++ b/resources/access/access.go @@ -2,6 +2,7 @@ package access import ( _ "embed" + "github.com/eolinker/go-common/access" "gopkg.in/yaml.v3" ) diff --git a/resources/access/access.yaml b/resources/access/access.yaml index c7d2061..6fb4175 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -1,96 +1,225 @@ system: - - name: user_manager - cname: '成员管理' - desc: '成员管理' - - name: user_group - cname: '用户组管理' - desc: '用户组管理' - - name: team_manager - cname: '团队管理' - desc: '团队管理' - - name: organization_manager + - name: organization cname: '组织管理' - desc: '组织管理' - - name: role_manager - cname: '角色管理' - desc: '角色管理' - - name: system_permission_setting - cname: '系统权限设置' - desc: '系统权限设置' + value: 'organization' + children: + - name: member + cname: '成员' + value: 'member' + children: + - name: view + cname: '查看' + value: 'view' + - name: manager + cname: '管理' + value: 'manager' + apis: + - "GET:/api/v1/simple/member" + - "GET:/api/v1/simple/organization/member/:id" + - name: team + cname: '团队' + value: 'team' + children: + - name: view + cname: '查看' + value: 'view' + - name: manager + cname: '管理' + value: 'manager' + - name: role + cname: '角色' + value: 'role' + children: + - name: view system role + cname: '查看系统角色' + value: 'view_system_role' + - name: view team role + cname: '查看团队角色' + value: 'view_team_role' + - name: API Market + cname: 'API市场' + value: 'api_market' + children: + - name: service classification + cname: '服务分类' + value: 'service_classification' + children: + - name: view + cname: '查看' + value: 'view' + - name: manager + cname: '管理' + value: 'manager' - name: devops - cname: '运维管理' - desc: '运维管理' - - name: environs_setting - cname: '环境管理' - desc: '环境管理' - - name: service_categories_setting - cname: '服务类目管理' - desc: '管理服务广场内的服务类目' + cname: 运维 + value: 'devops' + children: + - name: cluster + cname: 集群 + value: 'cluster' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: ssl certificate + cname: 证书 + value: 'ssl_certificate' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: log configuration + cname: 日志 + value: 'log_configuration' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: workspace + cname: 工作空间 + value: 'workspace' + children: + - name: application + cname: 应用 + value: 'application' + children: + - name: view all + cname: 查看所有应用 + value: 'view_all' + - name: service + cname: 服务 + value: 'service' + children: + - name: view all + cname: 查看所有服务 + value: 'view_all' + - name: team + cname: 团队 + value: 'team' + children: + - name: view all + cname: 查看所有团队 + value: 'view_all' + - name: api market + cname: API市场 + value: 'api_market' + children: + - name: view + cname: 查看 + value: 'view' team: - - name: project_manager - cname: '项目管理' - desc: '项目管理' - - name: project_view - cname: '项目查看' - desc: '项目查看' - - name: team_permission_setting - cname: '团队权限管理' - desc: '团队权限管理' - - name: team_setting - cname: '团队设置' - desc: '团队设置' - - name: member_setting - cname: '成员管理' - desc: '成员管理' -project: - - name: project_setting - cname: '系统设置' - desc: '管理系统设置' - - name: member_setting - cname: '成员管理' - desc: '成员管理' - - name: api_manager - cname: 'API管理' - desc: 'API管理' - - name: api_view - cname: 'API查看' - desc: 'API查看' - - name: upstream_manager - cname: '上游管理' - desc: '上游管理' - - name: upstream_view - cname: '上游查看' - desc: '上游查看' - - name: service_manager - cname: '服务管理' - desc: '服务管理' - - name: service_view - cname: '服务查看' - desc: '服务查看' - - name: subscribe_view - cname: '订阅查看' - desc: '查看订阅的第三方服务' - - name: subscribe_apply - cname: '申请订阅' - desc: '申请订阅第三方服务' - - name: subscribers_manager - cname: '订阅方管理' - desc: '管理订阅的第三方服务, 新增,删除订阅方' - - name: subscribe_approval - cname: '订阅审批' - desc: '审批订阅申请' - - name: authentication_view - cname: '查看鉴权' - desc: '查看鉴权配置' - - name: authentication_manager - cname: '鉴权管理' - desc: '新增/编辑/删除鉴权信息' - - name: publish_manager - cname: '发布管理' - desc: '申请\执行发布, 删除版本' - - name: publish_approve - cname: '发布审批' - desc: '审批发布申请' - - name: permission_manager - cname: '权限管理' - desc: '权限管理' \ No newline at end of file + - name: service + cname: 服务 + value: 'service' + children: + - name: api + cname: API + value: 'api' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: upstream + cname: 上游 + value: 'upstream' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: release + cname: 发布 + value: 'release' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: subscription management + cname: 订阅方管理 + value: 'subscription' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: service + cname: 服务管理 + value: 'service' + children: + - name: view + cname: 查看 + value: 'view' + - name: application + cname: 应用 + value: 'application' + children: + - name: subscription Service + cname: 订阅服务 + value: 'subscription' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: authorization + cname: 访问授权 + value: 'authorization' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: application + cname: 应用 + value: 'application' + children: + - name: manager + cname: 管理 + value: 'manager' + - name: team + cname: 团队 + value: 'team' + children: + - name: member + cname: 成员 + value: 'member' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' + - name: team + cname: 团队管理 + value: 'team' + children: + - name: view + cname: 查看 + value: 'view' + - name: manager + cname: 管理 + value: 'manager' \ No newline at end of file diff --git a/resources/access/access_test.go b/resources/access/access_test.go new file mode 100644 index 0000000..1e24d46 --- /dev/null +++ b/resources/access/access_test.go @@ -0,0 +1,29 @@ +package access + +import ( + "fmt" + "sort" + "testing" + + "github.com/eolinker/go-common/access" +) + +func TestPrintlnRoleAccess(t *testing.T) { + system, has := access.GetPermit("system") + if has { + keys := system.AccessKeys() + sort.Strings(keys) + for _, k := range keys { + fmt.Printf("- %s\n", k) + } + + } + team, has := access.GetPermit("team") + if has { + keys := team.AccessKeys() + sort.Strings(keys) + for _, k := range keys { + fmt.Printf("- %s\n", k) + } + } +} diff --git a/resources/access/role.go b/resources/access/role.go new file mode 100644 index 0000000..4b1ba46 --- /dev/null +++ b/resources/access/role.go @@ -0,0 +1,24 @@ +package access + +import ( + _ "embed" + + "github.com/eolinker/go-common/access" + "gopkg.in/yaml.v3" +) + +type Role = access.Role + +var ( + //go:embed role.yaml + roleData []byte +) + +func init() { + ts := make(map[string][]Role) + err := yaml.Unmarshal(roleData, &ts) + if err != nil { + panic(err) + } + access.RoleAdd(ts) +} diff --git a/resources/access/role.yaml b/resources/access/role.yaml new file mode 100644 index 0000000..e033bb4 --- /dev/null +++ b/resources/access/role.yaml @@ -0,0 +1,114 @@ +system: + - name: supper_admin + cname: 超级管理员 + permits: + - system.api_market.service_classification.manager + - system.api_market.service_classification.view + - system.devops.cluster.manager + - system.devops.cluster.view + - system.devops.log_configuration.manager + - system.devops.log_configuration.view + - system.devops.ssl_certificate.manager + - system.devops.ssl_certificate.view + - system.organization.member.manager + - system.organization.member.view + - system.organization.role.view_system_role + - system.organization.role.view_team_role + - system.organization.team.manager + - system.organization.team.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all + - name: team_admin + cname: 团队管理员 + permits: + - system.organization.role.view_team_role + - system.organization.team.manager + - system.organization.team.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all + - name: devops_admin + cname: 运维管理员 + permits: + - system.api_market.service_classification.manager + - system.api_market.service_classification.view + - system.devops.cluster.manager + - system.devops.cluster.view + - system.devops.log_configuration.manager + - system.devops.log_configuration.view + - system.devops.ssl_certificate.manager + - system.devops.ssl_certificate.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all + - name: member + cname: 普通成员 + permits: + - system.workspace.api_market.view + default: true +team: + - name: team_admin + cname: 团队管理员 + permits: + - team.application.application.manager + - team.application.authorization.manager + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.service.api.manager + - team.service.api.view + - team.service.release.manager + - team.service.release.view + - team.service.service.manager + - team.service.subscription.manager + - team.service.subscription.view + - team.service.upstream.manager + - team.service.upstream.view + - team.team.member.manager + - team.team.member.view + - team.team.team.manager + - team.team.team.view + - name: service_admin + cname: 服务管理员 + permits: + - team.service.service.manager + - team.service.upstream.manager + - team.service.upstream.view + - team.service.api.manager + - team.service.api.view + - team.service.subscription.manager + - team.service.subscription.view + - team.service.release.manager + - team.service.release.view + - team.team.member.view + - name: service_developer + cname: 服务开发者 + permits: + - team.service.upstream.manager + - team.service.upstream.view + - team.service.api.manager + - team.service.api.view + - team.service.release.manager + - team.service.release.view + - team.team.member.view + - name: application_admin + cname: 应用管理员 + permits: + - team.application.application.manager + - team.application.authorization.manager + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.team.member.view + - name: application_developer + cname: 应用开发者 + permits: + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.team.member.view + default: true \ No newline at end of file diff --git a/service/project-member/model.go b/service/project-member/model.go deleted file mode 100644 index 7fe86bd..0000000 --- a/service/project-member/model.go +++ /dev/null @@ -1,5 +0,0 @@ -package project_member - -import "github.com/eolinker/ap-account/service/member" - -type Member = member.Member diff --git a/service/project-member/service.go b/service/project-member/service.go deleted file mode 100644 index 47b29e0..0000000 --- a/service/project-member/service.go +++ /dev/null @@ -1,17 +0,0 @@ -package project_member - -import ( - "reflect" - - "github.com/eolinker/ap-account/service/member" - "github.com/eolinker/apipark/stores/project" - "github.com/eolinker/go-common/autowire" -) - -type IMemberService member.IMemberService - -func init() { - autowire.Auto[IMemberService](func() reflect.Value { - return reflect.ValueOf(new(member.Service[project.IMemberStore])) - }) -} diff --git a/stores/project/model.go b/stores/project/model.go index 0b4117f..efc8b64 100644 --- a/stores/project/model.go +++ b/stores/project/model.go @@ -24,21 +24,6 @@ func (p *Project) TableName() string { return "project" } -//type MemberRole struct { -// Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` -// Pid string `gorm:"size:36;not null;column:pid;index:pid;comment:项目id;uniqueIndex:pid_uid_rid;"` -// Uid string `gorm:"size:36;not null;column:uid;index:uid;comment:用户id;uniqueIndex:pid_uid_rid;"` -// Rid string `gorm:"size:36;not null;column:rid;index:rid;comment:角色id;uniqueIndex:pid_uid_rid;"` -// CreateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` -//} -// -//func (m *MemberRole) IdValue() int64 { -// return m.Id -//} -//func (m *MemberRole) TableName() string { -// return "project_role" -//} - type Authorization struct { Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` UUID string `gorm:"size:36;not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` From 8294ad455923da7d03600852ca50118dc67ee194 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Tue, 30 Jul 2024 23:28:57 +0800 Subject: [PATCH 04/19] =?UTF-8?q?=E9=9B=86=E7=BE=A4=E3=80=81=E8=AF=81?= =?UTF-8?q?=E4=B9=A6=E6=8F=90=E5=8F=96=E5=87=BA=E4=B8=80=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/certificate/iml.go | 2 +- controller/cluster/cluster.go | 22 + controller/cluster/iml.go | 73 ++ controller/dynamic-module/dynamic-module.go | 8 +- controller/dynamic-module/iml.go | 34 +- controller/my_team/iml.go | 4 + controller/my_team/team.go | 1 + controller/partition/iml.go | 69 -- controller/partition/partition.go | 31 - controller/plugin-cluster/iml.go | 36 + controller/plugin-cluster/plugin_partiton.go | 24 + controller/plugin-partition/iml.go | 36 - .../plugin-partition/plugin_partiton.go | 23 - controller/service/iml.go | 62 +- controller/service/service.go | 19 +- controller/upstream/iml.go | 8 +- frontend/README.md | 6 + frontend/README.pro.md | 21 + frontend/package.json | 12 +- frontend/packages/businessEntry/.env | 10 + frontend/packages/businessEntry/.eslintrc.cjs | 18 + frontend/packages/businessEntry/.gitignore | 26 + frontend/packages/businessEntry/README.md | 11 + .../__tests__/businessEntry.test.js | 7 + frontend/packages/businessEntry/index.html | 21 + frontend/packages/businessEntry/package.json | 17 + .../packages/businessEntry/postcss.config.js | 15 + .../packages/businessEntry/public/favicon.ico | Bin 0 -> 32038 bytes .../businessEntry/public/iconpark_apinto.js | 8 + .../businessEntry/public/iconpark_eolink.js | 7 + .../packages/businessEntry/public/vite.svg | 1 + frontend/packages/businessEntry/src/App.tsx | 153 ++++ .../components/aoplatform/RenderRoutes.tsx | 533 ++++++++++++++ frontend/packages/businessEntry/src/main.tsx | 33 + .../packages/businessEntry/src/vite-env.d.ts | 1 + frontend/packages/businessEntry/start-vite.js | 22 + .../packages/businessEntry/tailwind.config.js | 87 +++ frontend/packages/businessEntry/tsconfig.json | 39 ++ .../packages/businessEntry/tsconfig.node.json | 10 + .../packages/businessEntry/vite.config.ts | 86 +++ frontend/packages/common/package.json | 1 - frontend/packages/common/src/assets/logo.png | Bin 3417 -> 4240 bytes .../src/components/aoplatform/BasicLayout.tsx | 4 +- .../src/components/aoplatform/Navigation.tsx | 15 +- .../PublishApprovalModalContent.tsx | 2 +- .../SubscribeApprovalModalContent.tsx | 2 +- .../components/aoplatform/TreeWithMore.tsx | 9 +- .../IntelligentPluginList.tsx | 8 +- .../IntelligentPluginPublish.tsx | 4 +- .../apispace/code-snippet/generate-code.ts | 34 +- .../apispace/code-snippet/index.tsx | 14 +- .../common/src/const/approval/const.tsx | 18 +- frontend/packages/common/src/const/const.ts | 2 +- .../packages/common/src/const/permissions.ts | 5 + frontend/packages/common/src/const/type.ts | 10 + .../src/contexts/GlobalStateContext.tsx | 2 +- .../packages/common/src/utils/dataTransfer.ts | 10 +- .../packages/common/src/utils/permission.ts | 4 +- frontend/packages/core/.env | 1 + frontend/packages/core/package.json | 7 +- .../components/aoplatform/RenderRoutes.tsx | 122 +--- .../core/src/const/organization/const.tsx | 4 +- .../core/src/const/partitions/const.tsx | 38 +- .../packages/core/src/const/system/const.tsx | 36 +- .../packages/core/src/const/system/type.ts | 22 +- .../packages/core/src/const/team/const.tsx | 2 +- frontend/packages/core/src/pages/Login.tsx | 7 +- .../core/src/pages/approval/ApprovalList.tsx | 2 +- .../core/src/pages/approval/ApprovalPage.tsx | 2 +- .../core/src/pages/auditLog/AuditLog.tsx | 6 +- .../src/pages/logsettings/LogSettings.tsx | 2 +- .../logsettings/LogSettingsInstruction.tsx | 10 +- .../core/src/pages/member/MemberPage.tsx | 8 +- .../pages/organization/OrganizationConfig.tsx | 4 +- .../pages/organization/OrganizationList.tsx | 2 +- .../src/pages/partitions/PartitionConfig.tsx | 25 +- .../pages/partitions/PartitionInsideCert.tsx | 2 +- .../PartitionInsideDashboardSetting.tsx | 4 +- .../pages/partitions/PartitionInsidePage.tsx | 4 +- .../src/pages/partitions/PartitionList.tsx | 12 +- .../resourcesettings/ResourceSettings.tsx | 2 +- .../ResourceSettingsInstruction.tsx | 10 +- .../pages/serviceCategory/ServiceCategory.tsx | 2 + .../ServiceHubCategoryConfig.tsx | 1 - .../core/src/pages/system/SystemConfig.tsx | 4 +- .../src/pages/system/SystemInsideMember.tsx | 1 - .../src/pages/system/SystemInsidePage.tsx | 8 +- .../pages/system/SystemInsideSubscriber.tsx | 6 +- .../core/src/pages/system/SystemList.tsx | 4 +- .../core/src/pages/system/SystemTopology.tsx | 3 +- .../pages/system/api/SystemInsideApiList.tsx | 22 +- .../approval/SystemInsideApprovalList.tsx | 3 +- .../authority/SystemInsideAuthority.tsx | 3 +- .../myService/MyServiceInsideConfig.tsx | 2 +- .../system/myService/MyServiceInsideMenu.tsx | 2 +- .../myService/SystemInsideMyService.tsx | 1 - .../publish/SystemInsidePublishList.tsx | 5 +- .../subSubscribe/SystemInsideSubService.tsx | 3 +- .../upstream/SystemInsideUpstreamConfig.tsx | 2 +- .../upstream/SystemInsideUpstreamList.tsx | 3 +- .../pages/systemRunning/SystemRunning3.tsx | 550 --------------- .../core/src/pages/team/TeamInsideMember.tsx | 10 - .../core/src/pages/team/TeamInsidePage.tsx | 2 +- .../packages/core/src/pages/team/TeamList.tsx | 4 +- .../core/src/pages/webhook/Webhook.tsx | 5 +- frontend/packages/core/tsconfig.json | 6 +- frontend/packages/core/vite.config.ts | 13 +- ....timestamp-1720797741902-0827b2d7ab219.mjs | 90 --- frontend/packages/dashboard/README.md | 11 + .../dashboard/__tests__/dashboard.test.js | 7 + frontend/packages/dashboard/package.json | 11 + frontend/packages/dashboard/postcss.config.js | 15 + .../src/component}/MonitorApiPage.tsx | 6 +- .../src/component}/MonitorAppPage.tsx | 6 +- .../src/component}/MonitorDetailPage.tsx | 6 +- .../src/component}/MonitorLineGraph.tsx | 10 +- .../src/component}/MonitorPieGraph.tsx | 2 +- .../src/component}/MonitorSubPage.tsx | 6 +- .../src/component}/MonitorTable.tsx | 6 +- .../src/component}/MonitorTotalPage.tsx | 11 +- .../src/const}/const.tsx | 0 .../dashboard => dashboard/src/const}/type.ts | 0 .../src/pages}/Dashboard.tsx | 0 .../src/pages}/DashboardApiList.tsx | 8 +- .../src/pages}/DashboardApplicationList.tsx | 16 +- .../src/pages}/DashboardDetail.tsx | 8 +- .../src/pages}/DashboardInstruction.tsx | 10 +- .../src/pages}/DashboardList.tsx | 0 .../src/pages}/DashboardProjectList.tsx | 14 +- .../src/pages}/DashboardTabPage.tsx | 0 .../src/pages}/DashboardTotal.tsx | 8 +- .../src/utils/dashboard.ts | 0 .../packages/dashboard/tailwind.config.js | 86 +++ frontend/packages/dashboard/tsconfig.json | 29 + .../packages/dashboard/tsconfig.node.json | 10 + .../market/src/const/serviceHub/const.tsx | 2 +- .../pages/serviceHub/ApplyServiceModal.tsx | 2 +- .../src/pages/serviceHub/ServiceHubGroup.tsx | 2 +- frontend/packages/openApi/README.md | 11 + .../openApi/__tests__/openApi.test.js | 7 + frontend/packages/openApi/package.json | 15 + frontend/packages/openApi/postcss.config.js | 15 + .../src/pages}/OpenApiConfig.tsx | 0 .../src/pages}/OpenApiList.tsx | 8 +- frontend/packages/openApi/tailwind.config.js | 86 +++ frontend/packages/openApi/tsconfig.json | 29 + frontend/packages/openApi/tsconfig.node.json | 10 + frontend/packages/systemRunning/README.md | 11 + .../__tests__/systemRunning.test.js | 7 + frontend/packages/systemRunning/package.json | 8 + .../packages/systemRunning/postcss.config.js | 15 + .../src/pages}/SystemRunning.tsx | 8 +- .../src/pages}/SystemRunningInstruction.tsx | 0 .../packages/systemRunning/tailwind.config.js | 86 +++ frontend/packages/systemRunning/tsconfig.json | 28 + .../packages/systemRunning/tsconfig.node.json | 10 + gateway/handler.go | 22 +- module/catalogue/dto/output.go | 19 +- module/catalogue/iml.go | 21 +- module/certificate/certificate.go | 4 +- module/certificate/dto/dto.go | 2 +- module/certificate/impl.go | 77 +- module/cluster/cluster.go | 21 + module/cluster/dto/input.go | 40 ++ module/{partition => cluster}/dto/output.go | 2 +- module/cluster/impl.go | 300 ++++++++ module/{partition => cluster}/util.go | 8 +- module/dynamic-module/dto/input.go | 4 +- module/dynamic-module/dynamic_module.go | 10 +- module/dynamic-module/iml.go | 324 ++++----- module/my-team/dto/input.go | 5 + module/my-team/dto/output.go | 114 ++- module/my-team/iml.go | 208 +++--- module/my-team/team.go | 3 + module/partition/dto/input.go | 40 -- module/partition/impl.go | 317 --------- module/partition/partition.go | 29 - module/permit/project/iml.go | 21 +- .../dto/input.go | 0 .../dto/plugin.go | 2 +- module/plugin-cluster/iml.go | 174 +++++ .../plugin-partition.go | 19 +- module/plugin-partition/iml.go | 176 ----- module/project-authorization/iml.go | 26 +- module/project/dto/output.go | 53 +- module/project/iml.go | 322 ++------- module/project_diff/iml.go | 88 ++- module/project_diff/out.go | 4 +- module/publish/dto/out.go | 8 +- module/publish/iml.go | 48 +- module/release/iml.go | 14 +- module/service/iml.go | 658 +----------------- module/service/service.go | 28 +- module/subscribe/dto/input.go | 4 +- module/subscribe/dto/output.go | 4 +- module/subscribe/iml.go | 115 +-- module/team/dto/input.go | 3 +- module/team/dto/output.go | 68 +- module/team/iml.go | 56 +- module/upstream/dto/output.go | 2 +- module/upstream/iml.go | 60 +- plugins/core/cluster.go | 6 +- plugins/core/core.go | 21 +- plugins/core/dynamic-module.go | 4 +- plugins/core/my-team.go | 2 + plugins/core/partition.go | 16 +- plugins/core/plugin.go | 13 +- plugins/core/service.go | 17 +- resources/access/role.yaml | 166 ++--- resources/plugin/plugin-load.go | 11 +- service/certificate/model.go | 2 +- service/certificate/service.go | 18 +- service/cluster/cluster.go | 68 +- service/cluster/model.go | 2 - service/dynamic-module/iml.go | 2 - service/dynamic-module/model.go | 5 +- service/partition/iml.go | 100 --- service/partition/model.go | 33 - service/partition/service.go | 20 - .../iml.go | 19 +- .../model.go | 5 +- .../service.go | 11 +- service/project_diff/diff.go | 6 +- service/publish/iml.go | 22 +- service/publish/model.go | 12 +- service/release/iml.go | 12 +- service/release/model.go | 5 +- service/team/iml.go | 4 - service/team/model.go | 22 +- service/upstream/iml.go | 20 +- service/upstream/model.go | 4 +- stores/certificate/model.go | 2 +- stores/cluster/model.go | 30 +- stores/cluster/store.go | 11 +- stores/dynamic-module/model.go | 1 - stores/publish/model.go | 13 +- stores/team/model.go | 20 +- stores/upstream/model.go | 22 +- 238 files changed, 3666 insertions(+), 4079 deletions(-) create mode 100644 controller/cluster/cluster.go create mode 100644 controller/cluster/iml.go delete mode 100644 controller/partition/iml.go delete mode 100644 controller/partition/partition.go create mode 100644 controller/plugin-cluster/iml.go create mode 100644 controller/plugin-cluster/plugin_partiton.go delete mode 100644 controller/plugin-partition/iml.go delete mode 100644 controller/plugin-partition/plugin_partiton.go create mode 100644 frontend/README.pro.md create mode 100644 frontend/packages/businessEntry/.env create mode 100644 frontend/packages/businessEntry/.eslintrc.cjs create mode 100644 frontend/packages/businessEntry/.gitignore create mode 100644 frontend/packages/businessEntry/README.md create mode 100644 frontend/packages/businessEntry/__tests__/businessEntry.test.js create mode 100644 frontend/packages/businessEntry/index.html create mode 100644 frontend/packages/businessEntry/package.json create mode 100644 frontend/packages/businessEntry/postcss.config.js create mode 100644 frontend/packages/businessEntry/public/favicon.ico create mode 100644 frontend/packages/businessEntry/public/iconpark_apinto.js create mode 100644 frontend/packages/businessEntry/public/iconpark_eolink.js create mode 100644 frontend/packages/businessEntry/public/vite.svg create mode 100644 frontend/packages/businessEntry/src/App.tsx create mode 100644 frontend/packages/businessEntry/src/components/aoplatform/RenderRoutes.tsx create mode 100644 frontend/packages/businessEntry/src/main.tsx create mode 100644 frontend/packages/businessEntry/src/vite-env.d.ts create mode 100644 frontend/packages/businessEntry/start-vite.js create mode 100644 frontend/packages/businessEntry/tailwind.config.js create mode 100644 frontend/packages/businessEntry/tsconfig.json create mode 100644 frontend/packages/businessEntry/tsconfig.node.json create mode 100644 frontend/packages/businessEntry/vite.config.ts create mode 100644 frontend/packages/core/.env delete mode 100644 frontend/packages/core/src/pages/systemRunning/SystemRunning3.tsx delete mode 100644 frontend/packages/core/vite.config.ts.timestamp-1720797741902-0827b2d7ab219.mjs create mode 100644 frontend/packages/dashboard/README.md create mode 100644 frontend/packages/dashboard/__tests__/dashboard.test.js create mode 100644 frontend/packages/dashboard/package.json create mode 100644 frontend/packages/dashboard/postcss.config.js rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorApiPage.tsx (98%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorAppPage.tsx (97%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorDetailPage.tsx (97%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorLineGraph.tsx (98%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorPieGraph.tsx (98%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorSubPage.tsx (97%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorTable.tsx (94%) rename frontend/packages/{common/src/components/aoplatform/dashboard => dashboard/src/component}/MonitorTotalPage.tsx (97%) rename frontend/packages/{common/src/const/dashboard => dashboard/src/const}/const.tsx (100%) rename frontend/packages/{common/src/const/dashboard => dashboard/src/const}/type.ts (100%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/Dashboard.tsx (100%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardApiList.tsx (87%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardApplicationList.tsx (80%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardDetail.tsx (91%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardInstruction.tsx (80%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardList.tsx (100%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardProjectList.tsx (82%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardTabPage.tsx (100%) rename frontend/packages/{core/src/pages/dashboard => dashboard/src/pages}/DashboardTotal.tsx (91%) rename frontend/packages/{common => dashboard}/src/utils/dashboard.ts (100%) create mode 100644 frontend/packages/dashboard/tailwind.config.js create mode 100644 frontend/packages/dashboard/tsconfig.json create mode 100644 frontend/packages/dashboard/tsconfig.node.json create mode 100644 frontend/packages/openApi/README.md create mode 100644 frontend/packages/openApi/__tests__/openApi.test.js create mode 100644 frontend/packages/openApi/package.json create mode 100644 frontend/packages/openApi/postcss.config.js rename frontend/packages/{core/src/pages/openApi => openApi/src/pages}/OpenApiConfig.tsx (100%) rename frontend/packages/{core/src/pages/openApi => openApi/src/pages}/OpenApiList.tsx (97%) create mode 100644 frontend/packages/openApi/tailwind.config.js create mode 100644 frontend/packages/openApi/tsconfig.json create mode 100644 frontend/packages/openApi/tsconfig.node.json create mode 100644 frontend/packages/systemRunning/README.md create mode 100644 frontend/packages/systemRunning/__tests__/systemRunning.test.js create mode 100644 frontend/packages/systemRunning/package.json create mode 100644 frontend/packages/systemRunning/postcss.config.js rename frontend/packages/{core/src/pages/systemRunning => systemRunning/src/pages}/SystemRunning.tsx (98%) rename frontend/packages/{core/src/pages/systemRunning => systemRunning/src/pages}/SystemRunningInstruction.tsx (100%) create mode 100644 frontend/packages/systemRunning/tailwind.config.js create mode 100644 frontend/packages/systemRunning/tsconfig.json create mode 100644 frontend/packages/systemRunning/tsconfig.node.json create mode 100644 module/cluster/cluster.go create mode 100644 module/cluster/dto/input.go rename module/{partition => cluster}/dto/output.go (98%) create mode 100644 module/cluster/impl.go rename module/{partition => cluster}/util.go (69%) delete mode 100644 module/partition/dto/input.go delete mode 100644 module/partition/impl.go delete mode 100644 module/partition/partition.go rename module/{plugin-partition => plugin-cluster}/dto/input.go (100%) rename module/{plugin-partition => plugin-cluster}/dto/plugin.go (94%) create mode 100644 module/plugin-cluster/iml.go rename module/{plugin-partition => plugin-cluster}/plugin-partition.go (56%) delete mode 100644 module/plugin-partition/iml.go delete mode 100644 service/partition/iml.go delete mode 100644 service/partition/model.go delete mode 100644 service/partition/service.go rename service/{plugin-partition => plugin-cluster}/iml.go (90%) rename service/{plugin-partition => plugin-cluster}/model.go (97%) rename service/{plugin-partition => plugin-cluster}/service.go (63%) diff --git a/controller/certificate/iml.go b/controller/certificate/iml.go index 925d35d..2936e27 100644 --- a/controller/certificate/iml.go +++ b/controller/certificate/iml.go @@ -23,7 +23,7 @@ func (c *imlCertificate) Update(ctx *gin.Context, id string, edit *certificate_d } func (c *imlCertificate) ListForPartition(ctx *gin.Context, partitionId string) ([]*certificate_dto.Certificate, error) { - return c.module.ListForPartition(ctx, partitionId) + return c.module.List(ctx, partitionId) } func (c *imlCertificate) Detail(ctx *gin.Context, id string) (*certificate_dto.Certificate, *certificate_dto.File, error) { diff --git a/controller/cluster/cluster.go b/controller/cluster/cluster.go new file mode 100644 index 0000000..4bdd43e --- /dev/null +++ b/controller/cluster/cluster.go @@ -0,0 +1,22 @@ +package cluster + +import ( + "reflect" + + cluster_dto "github.com/eolinker/apipark/module/cluster/dto" + + "github.com/eolinker/go-common/autowire" + "github.com/gin-gonic/gin" +) + +type IClusterController interface { + Nodes(ctx *gin.Context, clusterId string) ([]*cluster_dto.Node, error) + ResetCluster(ctx *gin.Context, clusterId string, input *cluster_dto.ResetCluster) ([]*cluster_dto.Node, error) + Check(ctx *gin.Context, input *cluster_dto.CheckCluster) ([]*cluster_dto.Node, error) +} + +func init() { + autowire.Auto[IClusterController](func() reflect.Value { + return reflect.ValueOf(new(imlCluster)) + }) +} diff --git a/controller/cluster/iml.go b/controller/cluster/iml.go new file mode 100644 index 0000000..21dee15 --- /dev/null +++ b/controller/cluster/iml.go @@ -0,0 +1,73 @@ +package cluster + +import ( + "github.com/eolinker/apipark/module/cluster" + cluster_dto "github.com/eolinker/apipark/module/cluster/dto" + "github.com/gin-gonic/gin" +) + +var ( + _ IClusterController = (*imlCluster)(nil) +) + +type imlCluster struct { + module cluster.IClusterModule `autowired:""` +} + +func (p *imlCluster) Nodes(ctx *gin.Context, clusterId string) ([]*cluster_dto.Node, error) { + if clusterId == "" { + clusterId = "default" + } + return p.module.ClusterNodes(ctx, clusterId) +} + +func (p *imlCluster) ResetCluster(ctx *gin.Context, clusterId string, input *cluster_dto.ResetCluster) ([]*cluster_dto.Node, error) { + if clusterId == "" { + clusterId = "default" + } + return p.module.ResetCluster(ctx, clusterId, input.ManagerAddress) +} + +func (p *imlCluster) Check(ctx *gin.Context, input *cluster_dto.CheckCluster) ([]*cluster_dto.Node, error) { + return p.module.CheckCluster(ctx, input.Address) +} + +// +//func (p *imlCluster) SimpleWithCluster(ctx *gin.Context) ([]*parition_dto.SimpleWithCluster, error) { +// return p.module.SimpleWithCluster(ctx) +//} +// +//func (p *imlCluster) Delete(ctx *gin.Context, id string) (string, error) { +// err := p.module.Delete(ctx, id) +// if err != nil { +// return "", err +// } +// return id, nil +//} +// +//func (p *imlCluster) Search(ctx *gin.Context, keyword string) ([]*parition_dto.Item, error) { +// return p.module.Search(ctx, keyword) +//} +// +//func (p *imlCluster) Simple(ctx *gin.Context) ([]*parition_dto.Simple, error) { +// return p.module.Simple(ctx) +//} +// +//func (p *imlCluster) Info(ctx *gin.Context, id string) (*parition_dto.Detail, error) { +// if id == "" { +// return nil, errors.New("id is empty") +// } +// return p.module.Get(ctx, id) +//} +// +//func (p *imlCluster) Update(ctx *gin.Context, id string, input *parition_dto.Edit) (*parition_dto.Detail, error) { +// return p.module.Update(ctx, id, input) +//} +// +//func (p *imlCluster) Create(ctx *gin.Context, input *parition_dto.Create) (*parition_dto.Detail, string, auto.TimeLabel, error) { +// detail, err := p.module.CreatePartition(ctx, input) +// if err != nil { +// return nil, "", auto.TimeLabel{}, err +// } +// return detail, detail.Id, detail.UpdateTime, nil +//} diff --git a/controller/dynamic-module/dynamic-module.go b/controller/dynamic-module/dynamic-module.go index ab9ca50..2580922 100644 --- a/controller/dynamic-module/dynamic-module.go +++ b/controller/dynamic-module/dynamic-module.go @@ -16,10 +16,10 @@ type IDynamicModuleController interface { List(ctx *gin.Context, module string, keyword string, cluster string, page string, pageSize string) ([]map[string]interface{}, *dynamic_module_dto.PluginInfo, int64, error) Render(ctx *gin.Context, module string) (*dynamic_module_dto.PluginBasic, map[string]interface{}, error) ModuleDrivers(ctx *gin.Context, group string) ([]*dynamic_module_dto.ModuleDriver, error) - Online(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error - Offline(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error - PartitionStatuses(ctx *gin.Context, module string, keyword string, page string, pageSize string) (map[string]map[string]string, error) - PartitionStatus(ctx *gin.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) + Online(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.ClusterInput) error + Offline(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.ClusterInput) error + //PartitionStatuses(ctx *gin.Context, module string, keyword string, page string, pageSize string) (map[string]map[string]string, error) + //PartitionStatus(ctx *gin.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) } func init() { diff --git a/controller/dynamic-module/iml.go b/controller/dynamic-module/iml.go index 5d16071..5e67f77 100644 --- a/controller/dynamic-module/iml.go +++ b/controller/dynamic-module/iml.go @@ -15,29 +15,29 @@ type imlDynamicModuleController struct { module dynamic_module.IDynamicModuleModule `autowired:""` } -func (i *imlDynamicModuleController) Online(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error { +func (i *imlDynamicModuleController) Online(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.ClusterInput) error { return i.module.Online(ctx, module, id, partitionInput) } -func (i *imlDynamicModuleController) Offline(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error { +func (i *imlDynamicModuleController) Offline(ctx *gin.Context, module string, id string, partitionInput *dynamic_module_dto.ClusterInput) error { return i.module.Offline(ctx, module, id, partitionInput) } -func (i *imlDynamicModuleController) PartitionStatuses(ctx *gin.Context, module string, keyword string, page string, pageSize string) (map[string]map[string]string, error) { - p, err := strconv.Atoi(page) - if err != nil { - p = 1 - } - ps, err := strconv.Atoi(pageSize) - if err != nil { - ps = 20 - } - return i.module.PartitionStatuses(ctx, module, keyword, p, ps) -} - -func (i *imlDynamicModuleController) PartitionStatus(ctx *gin.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) { - return i.module.PartitionStatus(ctx, module, id) -} +//func (i *imlDynamicModuleController) PartitionStatuses(ctx *gin.Context, module string, keyword string, page string, pageSize string) (map[string]map[string]string, error) { +// p, err := strconv.Atoi(page) +// if err != nil { +// p = 1 +// } +// ps, err := strconv.Atoi(pageSize) +// if err != nil { +// ps = 20 +// } +// return i.module.PartitionStatuses(ctx, module, keyword, p, ps) +//} +// +//func (i *imlDynamicModuleController) PartitionStatus(ctx *gin.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) { +// return i.module.PartitionStatus(ctx, module, id) +//} func (i *imlDynamicModuleController) ModuleDrivers(ctx *gin.Context, group string) ([]*dynamic_module_dto.ModuleDriver, error) { return i.module.ModuleDrivers(ctx, group) diff --git a/controller/my_team/iml.go b/controller/my_team/iml.go index c8888f9..7d554a8 100644 --- a/controller/my_team/iml.go +++ b/controller/my_team/iml.go @@ -14,6 +14,10 @@ type imlTeamController struct { module my_team.ITeamModule `autowired:""` } +func (c *imlTeamController) UpdateMemberRole(ctx *gin.Context, id string, input *team_dto.UpdateMemberRole) error { + return c.module.UpdateMemberRole(ctx, id, input) +} + func (c *imlTeamController) GetTeam(ctx *gin.Context, id string) (*team_dto.Team, error) { return c.module.GetTeam(ctx, id) } diff --git a/controller/my_team/team.go b/controller/my_team/team.go index 7d8407b..d701bec 100644 --- a/controller/my_team/team.go +++ b/controller/my_team/team.go @@ -18,6 +18,7 @@ type ITeamController interface { RemoveMember(ctx *gin.Context, id string, uuid string) error Members(ctx *gin.Context, id string, keyword string) ([]*team_dto.Member, error) SimpleMembers(ctx *gin.Context, id string, keyword string) ([]*team_dto.SimpleMember, error) + UpdateMemberRole(ctx *gin.Context, id string, input *team_dto.UpdateMemberRole) error } func init() { diff --git a/controller/partition/iml.go b/controller/partition/iml.go deleted file mode 100644 index 03a8c65..0000000 --- a/controller/partition/iml.go +++ /dev/null @@ -1,69 +0,0 @@ -package partition - -import ( - "errors" - - "github.com/eolinker/apipark/module/partition" - parition_dto "github.com/eolinker/apipark/module/partition/dto" - "github.com/eolinker/go-common/auto" - "github.com/gin-gonic/gin" -) - -var ( - _ IPartitionController = (*imlPartition)(nil) -) - -type imlPartition struct { - partitionModule partition.IPartitionModule `autowired:""` -} - -func (p *imlPartition) Nodes(ctx *gin.Context, partitionId string) ([]*parition_dto.Node, error) { - return p.partitionModule.ClusterNodes(ctx, partitionId) -} - -func (p *imlPartition) ResetCluster(ctx *gin.Context, partitionId string, input *parition_dto.ResetCluster) ([]*parition_dto.Node, error) { - return p.partitionModule.ResetCluster(ctx, partitionId, input.ManagerAddress) -} - -func (p *imlPartition) Check(ctx *gin.Context, input *parition_dto.CheckCluster) ([]*parition_dto.Node, error) { - return p.partitionModule.CheckCluster(ctx, input.Address) -} - -func (p *imlPartition) SimpleWithCluster(ctx *gin.Context) ([]*parition_dto.SimpleWithCluster, error) { - return p.partitionModule.SimpleWithCluster(ctx) -} - -func (p *imlPartition) Delete(ctx *gin.Context, id string) (string, error) { - err := p.partitionModule.Delete(ctx, id) - if err != nil { - return "", err - } - return id, nil -} - -func (p *imlPartition) Search(ctx *gin.Context, keyword string) ([]*parition_dto.Item, error) { - return p.partitionModule.Search(ctx, keyword) -} - -func (p *imlPartition) Simple(ctx *gin.Context) ([]*parition_dto.Simple, error) { - return p.partitionModule.Simple(ctx) -} - -func (p *imlPartition) Info(ctx *gin.Context, id string) (*parition_dto.Detail, error) { - if id == "" { - return nil, errors.New("id is empty") - } - return p.partitionModule.Get(ctx, id) -} - -func (p *imlPartition) Update(ctx *gin.Context, id string, input *parition_dto.Edit) (*parition_dto.Detail, error) { - return p.partitionModule.Update(ctx, id, input) -} - -func (p *imlPartition) Create(ctx *gin.Context, input *parition_dto.Create) (*parition_dto.Detail, string, auto.TimeLabel, error) { - detail, err := p.partitionModule.CreatePartition(ctx, input) - if err != nil { - return nil, "", auto.TimeLabel{}, err - } - return detail, detail.Id, detail.UpdateTime, nil -} diff --git a/controller/partition/partition.go b/controller/partition/partition.go deleted file mode 100644 index 05402b6..0000000 --- a/controller/partition/partition.go +++ /dev/null @@ -1,31 +0,0 @@ -package partition - -import ( - "reflect" - - parition_dto "github.com/eolinker/apipark/module/partition/dto" - - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" -) - -type IPartitionController interface { - Create(ctx *gin.Context, input *parition_dto.Create) (*parition_dto.Detail, string, auto.TimeLabel, error) - Search(ctx *gin.Context, keyword string) ([]*parition_dto.Item, error) - Simple(ctx *gin.Context) ([]*parition_dto.Simple, error) - Info(ctx *gin.Context, id string) (*parition_dto.Detail, error) - Update(ctx *gin.Context, id string, input *parition_dto.Edit) (*parition_dto.Detail, error) - Delete(ctx *gin.Context, id string) (string, error) - SimpleWithCluster(ctx *gin.Context) ([]*parition_dto.SimpleWithCluster, error) - - Nodes(ctx *gin.Context, partitionId string) ([]*parition_dto.Node, error) - ResetCluster(ctx *gin.Context, partitionId string, input *parition_dto.ResetCluster) ([]*parition_dto.Node, error) - Check(ctx *gin.Context, input *parition_dto.CheckCluster) ([]*parition_dto.Node, error) -} - -func init() { - autowire.Auto[IPartitionController](func() reflect.Value { - return reflect.ValueOf(new(imlPartition)) - }) -} diff --git a/controller/plugin-cluster/iml.go b/controller/plugin-cluster/iml.go new file mode 100644 index 0000000..f3b0c6e --- /dev/null +++ b/controller/plugin-cluster/iml.go @@ -0,0 +1,36 @@ +package plugin_cluster + +import ( + "github.com/eolinker/apipark/model/plugin_model" + "github.com/eolinker/apipark/module/plugin-cluster" + "github.com/eolinker/apipark/module/plugin-cluster/dto" + "github.com/gin-gonic/gin" +) + +var ( + _ IPluginClusterController = (*imlPluginClusterController)(nil) +) + +type imlPluginClusterController struct { + module plugin_cluster.IPluginClusterModule `autowired:""` +} + +func (i *imlPluginClusterController) Info(ctx *gin.Context, name string) (*dto.Define, error) { + return i.module.GetDefine(ctx, name) +} + +func (i *imlPluginClusterController) Option(ctx *gin.Context, project string) ([]*dto.PluginOption, error) { + return i.module.Options(ctx) +} + +func (i *imlPluginClusterController) List(ctx *gin.Context, clusterId string) ([]*dto.Item, error) { + return i.module.List(ctx, clusterId) +} + +func (i *imlPluginClusterController) Get(ctx *gin.Context, clusterId string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) { + return i.module.Get(ctx, clusterId, name) +} + +func (i *imlPluginClusterController) Set(ctx *gin.Context, clusterId string, name string, config *dto.PluginSetting) error { + return i.module.Set(ctx, clusterId, name, config) +} diff --git a/controller/plugin-cluster/plugin_partiton.go b/controller/plugin-cluster/plugin_partiton.go new file mode 100644 index 0000000..f212e82 --- /dev/null +++ b/controller/plugin-cluster/plugin_partiton.go @@ -0,0 +1,24 @@ +package plugin_cluster + +import ( + "reflect" + + "github.com/eolinker/apipark/model/plugin_model" + "github.com/eolinker/apipark/module/plugin-cluster/dto" + "github.com/eolinker/go-common/autowire" + "github.com/gin-gonic/gin" +) + +type IPluginClusterController interface { + List(ctx *gin.Context, clusterId string) ([]*dto.Item, error) + Get(ctx *gin.Context, clusterId string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) + Set(ctx *gin.Context, clusterId string, name string, config *dto.PluginSetting) error + Option(ctx *gin.Context, project string) ([]*dto.PluginOption, error) + Info(ctx *gin.Context, name string) (*dto.Define, error) +} + +func init() { + autowire.Auto[IPluginClusterController](func() reflect.Value { + return reflect.ValueOf(new(imlPluginClusterController)) + }) +} diff --git a/controller/plugin-partition/iml.go b/controller/plugin-partition/iml.go deleted file mode 100644 index a949732..0000000 --- a/controller/plugin-partition/iml.go +++ /dev/null @@ -1,36 +0,0 @@ -package plugin_partition - -import ( - "github.com/eolinker/apipark/model/plugin_model" - plugin_partition "github.com/eolinker/apipark/module/plugin-partition" - "github.com/eolinker/apipark/module/plugin-partition/dto" - "github.com/gin-gonic/gin" -) - -var ( - _ IPluginPartitionController = (*imlPluginPartitionController)(nil) -) - -type imlPluginPartitionController struct { - module plugin_partition.IPluginPartitionModule `autowired:""` -} - -func (i *imlPluginPartitionController) Info(ctx *gin.Context, name string) (*dto.Define, error) { - return i.module.GetDefine(ctx, name) -} - -func (i *imlPluginPartitionController) Option(ctx *gin.Context, project string) ([]*dto.PluginOption, error) { - return i.module.Options(ctx) -} - -func (i *imlPluginPartitionController) List(ctx *gin.Context, partition string) ([]*dto.Item, error) { - return i.module.List(ctx, partition) -} - -func (i *imlPluginPartitionController) Get(ctx *gin.Context, partition string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) { - return i.module.Get(ctx, partition, name) -} - -func (i *imlPluginPartitionController) Set(ctx *gin.Context, partition string, name string, config *dto.PluginSetting) error { - return i.module.Set(ctx, partition, name, config) -} diff --git a/controller/plugin-partition/plugin_partiton.go b/controller/plugin-partition/plugin_partiton.go deleted file mode 100644 index 81698e4..0000000 --- a/controller/plugin-partition/plugin_partiton.go +++ /dev/null @@ -1,23 +0,0 @@ -package plugin_partition - -import ( - "github.com/eolinker/apipark/model/plugin_model" - "github.com/eolinker/apipark/module/plugin-partition/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -type IPluginPartitionController interface { - List(ctx *gin.Context, partition string) ([]*dto.Item, error) - Get(ctx *gin.Context, partition string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) - Set(ctx *gin.Context, partition string, name string, config *dto.PluginSetting) error - Option(ctx *gin.Context, project string) ([]*dto.PluginOption, error) - Info(ctx *gin.Context, name string) (*dto.Define, error) -} - -func init() { - autowire.Auto[IPluginPartitionController](func() reflect.Value { - return reflect.ValueOf(new(imlPluginPartitionController)) - }) -} diff --git a/controller/service/iml.go b/controller/service/iml.go index 9eefaa9..0bd3d9f 100644 --- a/controller/service/iml.go +++ b/controller/service/iml.go @@ -1,7 +1,6 @@ package service import ( - "encoding/json" "github.com/gin-gonic/gin" "github.com/eolinker/apipark/module/service" @@ -16,63 +15,10 @@ type imlServiceController struct { module service.IServiceModule `autowired:""` } -func (i *imlServiceController) SimpleList(ctx *gin.Context, pid string) ([]*service_dto.SimpleItem, error) { - return i.module.SimpleList(ctx, pid) +func (i *imlServiceController) ServiceDoc(ctx *gin.Context, pid string) (*service_dto.ServiceDoc, error) { + return i.module.ServiceDoc(ctx, pid) } -func (i *imlServiceController) ServiceApis(ctx *gin.Context, pid string, sid string) ([]*service_dto.ServiceApi, error) { - return i.module.ServiceApis(ctx, pid, sid) -} - -func (i *imlServiceController) BindServiceApi(ctx *gin.Context, pid string, sid string, apis *service_dto.BindApis) error { - return i.module.BindServiceApi(ctx, pid, sid, apis) -} - -func (i *imlServiceController) UnbindServiceApi(ctx *gin.Context, pid string, sid string, api string) error { - apis := make([]string, 0) - err := json.Unmarshal([]byte(api), &apis) - if err != nil { - return err - } - return i.module.UnbindServiceApi(ctx, pid, sid, apis) -} - -func (i *imlServiceController) SortApis(ctx *gin.Context, pid string, sid string, apis *service_dto.BindApis) error { - return i.module.SortApis(ctx, pid, sid, apis) -} - -func (i *imlServiceController) ServiceDoc(ctx *gin.Context, pid string, sid string) (*service_dto.ServiceDoc, error) { - return i.module.ServiceDoc(ctx, pid, sid) -} - -func (i *imlServiceController) SaveServiceDoc(ctx *gin.Context, pid string, sid string, input *service_dto.SaveServiceDoc) error { - return i.module.SaveServiceDoc(ctx, pid, sid, input) -} - -func (i *imlServiceController) Get(ctx *gin.Context, pid string, sid string) (*service_dto.Service, error) { - return i.module.Get(ctx, pid, sid) -} - -func (i *imlServiceController) Search(ctx *gin.Context, keyword string, pid string) ([]*service_dto.ServiceItem, error) { - return i.module.Search(ctx, keyword, pid) -} - -func (i *imlServiceController) Create(ctx *gin.Context, pid string, input *service_dto.CreateService) (*service_dto.Service, error) { - return i.module.Create(ctx, pid, input) -} - -func (i *imlServiceController) Edit(ctx *gin.Context, pid string, sid string, input *service_dto.EditService) (*service_dto.Service, error) { - return i.module.Edit(ctx, pid, sid, input) -} - -func (i *imlServiceController) Delete(ctx *gin.Context, pid string, sid string) error { - return i.module.Delete(ctx, pid, sid) -} - -func (i *imlServiceController) Enable(ctx *gin.Context, pid string, sid string) error { - return i.module.Enable(ctx, pid, sid) -} - -func (i *imlServiceController) Disable(ctx *gin.Context, pid string, sid string) error { - return i.module.Disable(ctx, pid, sid) +func (i *imlServiceController) SaveServiceDoc(ctx *gin.Context, pid string, input *service_dto.SaveServiceDoc) error { + return i.module.SaveServiceDoc(ctx, pid, input) } diff --git a/controller/service/service.go b/controller/service/service.go index 770741f..23fc1e5 100644 --- a/controller/service/service.go +++ b/controller/service/service.go @@ -1,29 +1,18 @@ package service import ( - "github.com/gin-gonic/gin" "reflect" + "github.com/gin-gonic/gin" + service_dto "github.com/eolinker/apipark/module/service/dto" "github.com/eolinker/go-common/autowire" ) type IServiceController interface { - Get(ctx *gin.Context, pid string, sid string) (*service_dto.Service, error) - Search(ctx *gin.Context, keyword string, pid string) ([]*service_dto.ServiceItem, error) - Create(ctx *gin.Context, pid string, input *service_dto.CreateService) (*service_dto.Service, error) - Edit(ctx *gin.Context, pid string, sid string, input *service_dto.EditService) (*service_dto.Service, error) - Delete(ctx *gin.Context, pid string, sid string) error - Enable(ctx *gin.Context, pid string, sid string) error - Disable(ctx *gin.Context, pid string, sid string) error - ServiceDoc(ctx *gin.Context, pid string, sid string) (*service_dto.ServiceDoc, error) - SaveServiceDoc(ctx *gin.Context, pid string, sid string, input *service_dto.SaveServiceDoc) error - ServiceApis(ctx *gin.Context, pid string, sid string) ([]*service_dto.ServiceApi, error) - BindServiceApi(ctx *gin.Context, pid string, sid string, apis *service_dto.BindApis) error - UnbindServiceApi(ctx *gin.Context, pid string, sid string, api string) error - SortApis(ctx *gin.Context, pid string, sid string, apis *service_dto.BindApis) error - SimpleList(ctx *gin.Context, pid string) ([]*service_dto.SimpleItem, error) + ServiceDoc(ctx *gin.Context, pid string) (*service_dto.ServiceDoc, error) + SaveServiceDoc(ctx *gin.Context, pid string, input *service_dto.SaveServiceDoc) error } func init() { diff --git a/controller/upstream/iml.go b/controller/upstream/iml.go index 96416aa..936ebb4 100644 --- a/controller/upstream/iml.go +++ b/controller/upstream/iml.go @@ -1,7 +1,7 @@ package upstream import ( - "github.com/eolinker/apipark/module/partition" + "github.com/eolinker/apipark/module/cluster" "github.com/eolinker/apipark/module/project" "github.com/eolinker/apipark/module/upstream" upstream_dto "github.com/eolinker/apipark/module/upstream/dto" @@ -13,9 +13,9 @@ var ( ) type imlUpstreamController struct { - upstreamModule upstream.IUpstreamModule `autowired:""` - projectModule project.IProjectModule `autowired:""` - partitionModule partition.IPartitionModule `autowired:""` + upstreamModule upstream.IUpstreamModule `autowired:""` + projectModule project.IProjectModule `autowired:""` + partitionModule cluster.IClusterModule `autowired:""` } func (i *imlUpstreamController) Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, error) { diff --git a/frontend/README.md b/frontend/README.md index 5fea0bb..921d7f2 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -1,3 +1,9 @@ + # 部署 ## 安装依赖 diff --git a/frontend/README.pro.md b/frontend/README.pro.md new file mode 100644 index 0000000..e080d34 --- /dev/null +++ b/frontend/README.pro.md @@ -0,0 +1,21 @@ +# 部署 + +## 代码同步 + packages目录下,部分子项目为企业版独有,不要同步到开源版: + packages/businessEntry, packages/dashboard, packages/openApi, packages/systemRunning, README.pro.md + +## 安装依赖 + 建议使用pnpm + `npm install -g pnpm` + 使用pnpm安装依赖 + `pnpm install` + +## 编译 +### 开源版本 + 仅编译管理后台(打包目录为dist):`pnpm run build` + 仅编译租户端(打包目录为tenant_dist):`pnpm run build:tenant` + 同时编译管理后台和租户端:`pnpm run build:all` +### 企业版本 + 仅编译管理后台(打包目录为dist):`pnpm run build:pro` + 仅编译租户端(租户端暂时不区分企业版和开源版,打包目录为tenant_dist):`pnpm run build:tenant` + 同时编译管理后台和租户端:`pnpm run build:pro:all` \ No newline at end of file diff --git a/frontend/package.json b/frontend/package.json index 24e1e8a..d2c6462 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,4 +1,3 @@ - { "name": "frontend", "version": "1.0.0", @@ -9,12 +8,15 @@ "description": "", "scripts": { "test": "jest", - "build:all": "set NODE_OPTIONS=--max-old-space-size=16384 && lerna run build --stream", - "build": "set NODE_OPTIONS=--max-old-space-size=4096 && node -e \"console.log(v8.getHeapStatistics().heap_size_limit / 1024 / 1024)\"&& lerna run build --scope=core --stream --verbose ", + "build:all": "set NODE_OPTIONS=--max-old-space-size=16384 && lerna run build --scope=core --scope=market --stream", + "build:pro:all": "set NODE_OPTIONS=--max-old-space-size=16384 && lerna run build --scope=businessEntry --scope=market --stream", + "build": "set NODE_OPTIONS=--max-old-space-size=4096 && lerna run build --scope=core --stream --verbose ", + "build:pro": "set NODE_OPTIONS=--max-old-space-size=4096 && lerna run build --scope=business-entry --stream --verbose ", "build:tenant": "set NODE_OPTIONS=--max-old-space-size=16384 && lerna run build --scope=market --stream", "serve": "lerna run preview --parallel", "serve:remotes": "lerna run serve --scope=remote --parallel", "dev": "lerna run dev --scope=core --stream", + "dev:pro": "lerna run dev --scope=business-entry --stream", "dev:tenant": "lerna run dev --scope=market --stream", "stop": "kill-port --port 5000,5001" }, @@ -34,13 +36,15 @@ "js-base64": "^3.7.5", "moment": "^2.29.4", "postcss": "^8.4.31", + "postcss-import": "^16.1.0", "postcss-nesting": "^12.1.5", "react": "^18.2.0", "react-ace": "^10.1.0", "react-dom": "^18.2.0", "react-router-dom": "^6.20.0", "tailwindcss": "^3.3.5", - "uuid": "^9.0.1" + "uuid": "^9.0.1", + "vite-tsconfig-paths": "^4.3.2" }, "devDependencies": { "@ant-design/cssinjs": "^1.18.2", diff --git a/frontend/packages/businessEntry/.env b/frontend/packages/businessEntry/.env new file mode 100644 index 0000000..35f2ce9 --- /dev/null +++ b/frontend/packages/businessEntry/.env @@ -0,0 +1,10 @@ +### + # @Date: 2024-07-12 13:53:03 + # @LastEditors: maggieyyy + # @LastEditTime: 2024-07-12 18:26:34 + # @FilePath: \frontend\packages\core\.env.business +### +// .env.pro +VITE_APP_MODE=pro +VITE_APP_TITLE=My Production App +VITE_API_BASE_URL=https://api.production.example.com \ No newline at end of file diff --git a/frontend/packages/businessEntry/.eslintrc.cjs b/frontend/packages/businessEntry/.eslintrc.cjs new file mode 100644 index 0000000..87e6dac --- /dev/null +++ b/frontend/packages/businessEntry/.eslintrc.cjs @@ -0,0 +1,18 @@ +module.exports = { + root: true, + env: { browser: true, es2020: true }, + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + 'plugin:react-hooks/recommended', + ], + ignorePatterns: ['dist', '.eslintrc.cjs','public','code-snippet','ace-editor'], + parser: '@typescript-eslint/parser', + plugins: ['react-refresh'], + rules: { + 'react-refresh/only-export-components': [ + 'warn', + { allowConstantExport: true }, + ], + }, +} diff --git a/frontend/packages/businessEntry/.gitignore b/frontend/packages/businessEntry/.gitignore new file mode 100644 index 0000000..c564772 --- /dev/null +++ b/frontend/packages/businessEntry/.gitignore @@ -0,0 +1,26 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local +public/tinymce + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + diff --git a/frontend/packages/businessEntry/README.md b/frontend/packages/businessEntry/README.md new file mode 100644 index 0000000..38866cf --- /dev/null +++ b/frontend/packages/businessEntry/README.md @@ -0,0 +1,11 @@ +# `businessEntry` + +> TODO: description + +## Usage + +``` +const businessEntry = require('businessEntry'); + +// TODO: DEMONSTRATE API +``` diff --git a/frontend/packages/businessEntry/__tests__/businessEntry.test.js b/frontend/packages/businessEntry/__tests__/businessEntry.test.js new file mode 100644 index 0000000..46213a5 --- /dev/null +++ b/frontend/packages/businessEntry/__tests__/businessEntry.test.js @@ -0,0 +1,7 @@ +'use strict'; + +const businessEntry = require('..'); +const assert = require('assert').strict; + +assert.strictEqual(businessEntry(), 'Hello from businessEntry'); +console.info('businessEntry tests passed'); diff --git a/frontend/packages/businessEntry/index.html b/frontend/packages/businessEntry/index.html new file mode 100644 index 0000000..71bb310 --- /dev/null +++ b/frontend/packages/businessEntry/index.html @@ -0,0 +1,21 @@ + + + + + + + + APIPark - 企业API数据开放平台 + + +
+ + + +
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载
+ diff --git a/frontend/packages/businessEntry/package.json b/frontend/packages/businessEntry/package.json new file mode 100644 index 0000000..9db872f --- /dev/null +++ b/frontend/packages/businessEntry/package.json @@ -0,0 +1,17 @@ +{ + "name": "business-entry", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": " vite --port 5000 --strictPort", + "build": "vite build ", + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", + "preview": "vite preview --port 5000 --strictPort", + "serve": "vite preview --port 5000 --strictPort" + }, + "dependencies": { + }, + "devDependencies": { + } +} diff --git a/frontend/packages/businessEntry/postcss.config.js b/frontend/packages/businessEntry/postcss.config.js new file mode 100644 index 0000000..6921594 --- /dev/null +++ b/frontend/packages/businessEntry/postcss.config.js @@ -0,0 +1,15 @@ +/* + * @Date: 2023-11-27 17:31:54 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:42:18 + * @FilePath: \frontend\packages\core\postcss.config.js + */ +export default { + plugins: { + 'postcss-import': {}, + 'tailwindcss/nesting': {}, + tailwindcss: {}, + autoprefixer: {} + }, + } + \ No newline at end of file diff --git a/frontend/packages/businessEntry/public/favicon.ico b/frontend/packages/businessEntry/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..2c1de84c3cae0948b4b90c0376d3440ef481a47e GIT binary patch literal 32038 zcmeHQca&6RvY&U({{7DW^UgbG-`ibw&1pd-#~I>~1q2D=ki(D$7;+LMM?obD2n&e% zkOh_C0=l4xN)ixIf*BEzna=6nTkrR)dv7y@9(n>{&h|a0>7MQzzN)Xjs`{#aRivf; zN80bwe*gP4yq8Ps`@6KXMrmnj<;vNAZ@~BO;JXSHoWCDPOKbmMX=&-{_TLZJOG~qA zq@_KKYj7&=V1JLdG~70A?|<4a{Tu(ty>ghA$k#uL_2pTSNbH7DS$STGy}MhC&yI*# zIQP24+VrtlBbSLe^c6AYtQUzH@iTaBsLKcmG{_QPt@aXGhTm~m1@2>wTrTE_C1T_( zkXXN25}UbN%!4Py*mqb${a%nj3Le?qL4+r@h2A7X9(MC8JiK0kMnZNCQ17h}{Sk$m6vm&E@z_8yR6v)-_4 zy(G{G_Jy{M`j+;s>eCY2@vr!~i9T54VdqA_Ce|p}Y|=gqb{n?W7&upAeWpun3dVNs zClS-UdW$G{zJ0F*+YXjMQ#_kCxqcV5%f4E8cD2^FeeE;)>NN>IS%Y4|vu&Gi=DsS% zkcDClnkTXB+4}rw)(aBtIay-!*GcTH9TIzEtAt0*lVGd;bzBzQZS=ZT8h@ zBi<^o&#;re);$wE_3GEwq&4bqT*G(AcZhb!bLXuS6F!7>{EWnAuaZ#HeiCenXE*Pw z&ki)iv+Kb&*LfCvZ)^Jom0+V`X9J_AUwu%5Pu8~2G2gG+{u1O)`QC4)#ClATSnhlg z*x>jPiArSfbkN;LeVIU`ZuXqRuPDfOPsJvnzlp>Sd>Owq;fHWktPQ*1FU=Dpn?BPF ziFL=bM=liWyI*d&EV5t?=DUY8=g&KH4&Org4*#NJQ}H~}K!W3Di`+!sZ@3}9fIL}; zzY+8A+r?b=4>7mzgMZ_>@l>q!(0~^q>!3T%ch0%X_vYfM&{#ZGnv41Kjbp#@hDH0v z*!d}Z*RELWHs9&b=~|<2RH+4MZzB1R)syh@bw#^z5@%aiJQB$4&6;Cud~84}&~v3p6Wy_-M&B7qi= zdFnX&!PIe_^J-k@nDdI6>L2>M3{2WLO?q&!BavxKB>*3qI?hM^t~%~%_@$ilOkL~w zPhmfB{OhD|o9v0k=SLkK=kT5T4|mSF7pTxk`5v4&=UN?|>;nor5Bet9XM(NUuh(&W zHugaIkJT4X4eUqqZn9nryLS@5nI}$5pl)Y8|2gbIuJYYe*;#9U1MLshk?^WFlek;a zPl;{bsrKBT0o#K86ZbLhTBCl?f26MXI%JFG^%wo-NnBy<`9l0P@Lbv!SI6m`gYQ`D z`488T*q;4K+^Kk{SYDs_n{;=cO?k&!rfFUAipMGLPsJ(jo)=1OJvBU~cA$SLA2-GCy1t`QIuQ!(^Um96Tch{q&6 zF6P_uQpOC&AU5d64w19d7#ib;0};C%_Oh6p_ue!|nCRZtFP9`dV6p@mUuufDW@dM1 z{MdVQ59Y=;5pN02S)MSTVe<3c<;sjo3WSB%*Barnecn7KjMnyy(>42IlD1$j-7FD#$U6M`$haY znl(wHgXV~_ahF)`DrPRGu;a9nN>D??nI z8=*=u3Z>aPC|QwizTr$U5W6@pv}li*7vKjW;pA>hPYiZRSJ${ffT-w#Gtk z80#P9Ein;HI7^}BPxYG#8c`peyb7J8w z@b1LoZMmV$BTk3Bu^p3lEP5?60teq_tqP`k*9!6Un4in8BlJJ zv*5Z#-k&)G^4{F}xd?1g{6Gwuc!F@}5fW;V?Zon(csk{#p(FF@h&R0N3mAcZEdFq?m;Jq8Oa%A4au`_=2XgvuIn_Q?)NJtOyA&k|(unPHt zxpv+Fd^cQ~?*@6#njpr!wIY`j#{{Fu9|baCpW=BGN9Hxo=#0Gvb4ggQh%tLBLT;GX zDBn=L^`4d3S0#wGGB0ubTQTRpA;xgb0dXchr>We;hC>If+#=Qm_(C_rTjFeqy|o?V zhmF0du4HT+V`rQeSP|+Qd+dlAK3H4AudNp=SU@J@cP-)v=s@!b=3?7^F}LgybN2zU z&ishHOCk1;kHE7-L#9ihK5`jNkUt|f1u<5i+F0hXDD%)alpDsl8FOTe9dhGs+)1oU z;LY7SnD1pChP=mm)m%&i=$mv$-w@}bx)Qu6-lY;{9&!VHPuYoX-f_1^uFtiQ%LsKH zg|WjwAm5q0bZxBW5W#!OJmp4n8yNeOjV15Cni3c|POOWU?%w#ZUx>WENdoCzRNtuF zWFRM^`o@V-Q|9A#3cP1t=&=ms2wF+>gInjLZzpl)@oyy90XQ)F!(YquZ{Jp`8Y>cR>FFv%p*UPhy0Ac;{Y*lLvAc-+Fyy^U%aT=-4Uq)HfLWBk9nW4J5p7 zW1+rl(t{|$i8}sQ*Mk4g+GBV0jpoqf`i3&kd@{!V1ay75suJik5fbPr zuQCt0;d*@xV}G!w_<9e&ierGjA&%jpx{~*&%HpllR-#+)uAME6C&czdH*OREb2(~X^Zr~x z^8Qj;JhfX(a4cd)$4=f|U0>MX-QOTf#E}_ao&YZLki-rmmIWPejk{xI4yjUswcZ=mPl$KDGsDKkm5j!11S!qIFRB%+2BAZ zB69jCv34I3YvW!ao=1Cze1uw6;39?ilG|}0cTHSpZ2h|unZ8s)LucSMO~TU_NqFU3 zVtjE_1idzH>+u~hm#p_*3e4*4w}D$l?KLoz#L}2E-wg?!+t>y)0t4%>3%a$2mzWpe z0O}y8RjsY~Dz*?`l{ONd01V$(r<1Csj3v`!fEeo&--|VWBXD=bn*x7V5I0L4-UwhI zhXa2K45!ID?7qM|F2?!5JC^8R4r#^P$l(Fk30!KRDR6GYr7F&i^fNDpyee}`b(xby zexrP*geIf^!S}a*b~KswaxqV=*MZ3%OS~;#q@R2Meo}i5VE&2!1cp-k_7DR~9t;Ma zZ^e5h!dw`i9Fk!B9K{n~gAG;O4dz~HcXQ!RUJ!X?U%gJidA} z39vK7aAVhDuY*L_Z7wPKVhw<<8~-}!hTJRW8T7|7+wAq>V9rT9WgdMu z6ib-|8$;gvMTrcUA(7m95}v$7qLUX( zWEgPdSz~~~1`a#Z!IC$Ju1D`KyAFZaq;I}(f?)QQi-kIDzR-J zi@9|#?7}9A4w)sP#-O!c4+%A5-2!N5Pned#bfZ5CZJulE6mP~gub6b3cIv#Vv^)4A z$i3!gi6KIMKfDAO<`N#(V)%3uSAlNKdAvrZfZP+eKG4P8J9FO`>%Irpebz+ne`g&5 z*12H)27F`-wN$0<`tI=n@`*k{T#)RaPEm&v-Q2w zPr0YgBPKvG4Zwe)hl&5${-x8)&6* zaYkOASQNz^VywTG0@fDwb>^B6VB>JV!7q!Y`VRE7*N@IUXdeLDS?|JikD8rm7rWW+C91IlkTc`_A zOvQtBw6{X+qkYNQ+XC}((~q=G=YJFHwJln+VGM+St#sRRueCmI?Eo;gg>f|BYi`L+@qV z^?vS}S37@o%@@QkDTax-Js0P!v_tNJAM-p^Tl`r$VjMnRT9jXVpG&A6{OFJv%QlNK zaXI7w_8z+4pza@!o}Vi=!lLw1d@I%$(2e`CKR9?wtW)2i zwheP$g!l)sE3D%PHnMdc>DPJ!Vl`Puli}F9o9KJRSySh6-2*d79GJgT|FYB91okkt z;}g_@z^8${b8i#WeI3@j?(3-U9o$|VGYPrJ{zh?=YU>=_C-ADC^mY>a7j#}3Im|Cl zN*I2AfO?PgtF42rZ$N#Axp%Pj_P&mIQD@Dg_Ehy9@qbzimLYktcfs-SQ*T4xu-n2; z#x-6;KeAdK9X|(lp4f2Odir?uaVhg$^R)A>e@lJOdLZh2$~`f&z*>77cb3?G>@k5E zzUL441B_L&FPGLMpg)uPx72y*sHs5g!mbGc{oL2kzXw)WZ5?a5NI&Z@ff>$wxR!XT zwUp58#adT;&(n?pT9>X!WcCWX28rvP{;i|$RPJ4zaZLxKPCLiiP4({_J5Q`Paj)g7 zi@#@X>G*kfh`gWsL}Gx~}}OlK46eK<^3UyON2gmLeU+x)tkqJ~@cG%^cBumHK#~ojoDBucf|M z+PUtXI2LrC`u416qmM(m=f3{229o#J>JnaoTw7_>Ul)s@qFuyVnDE4fm~-?MVGOSk z=N(tg`&Fh|?x}Go0J@z)NzoouoeNf*0HN~6pjKuaGxMQO)>4VtsIl5+(Q$Gip z*PNA`x3Tv&eqHxi^Xzwyp4YnWx#r!y4RzlAkbB5}a2jHdd5ABRk;DA%C-hxj9PhtN zeIH;9)AjGQ_Lp$7Eqa(kGpdyY(c8Tze* z=IZ>6<+!!}1>+gq-%#$+Psi>>jXCGMvo7w>RmD@YwM5o!!n#NPvofef5P0?Y9+Dvca{x5?(CDoljj)J5PIud8f|H`%884w(l#kPk|*X|fL3~cUj+nY0`&rh` zU-|Fy;;q$M^H zC9?fP^ak`Mx>K3{-tu@+C;p)Xrz{kI|BwArc(%qJ-Dr|ExQAcl(8uY38N| ipW;A@11S!qIFRB%iUTPQq&Sci2hbiMb^IH1;Qs;bQdW}y literal 0 HcmV?d00001 diff --git a/frontend/packages/businessEntry/public/iconpark_apinto.js b/frontend/packages/businessEntry/public/iconpark_apinto.js new file mode 100644 index 0000000..d125a4a --- /dev/null +++ b/frontend/packages/businessEntry/public/iconpark_apinto.js @@ -0,0 +1,8 @@ +/* + * @Date: 2024-05-06 09:47:27 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-05-06 09:47:47 + * @FilePath: \frontend\packages\core\src\assets\iconpark_apinto.js + */ +(function(){window.__iconpark__=window.__iconpark__||{};var obj=JSON.parse("{\"680840\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"},\"680856\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680857\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680858\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680859\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680860\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680861\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680862\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680863\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680864\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680865\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680866\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680867\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680868\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680869\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680870\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680871\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680872\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680873\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680874\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680875\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680876\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680877\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680878\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680879\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680880\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680881\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680882\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680883\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680884\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680885\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680886\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680887\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680888\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680889\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680890\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680891\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680892\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680893\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680894\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680895\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680896\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680897\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680898\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680899\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680900\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680901\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680902\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680903\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680904\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680905\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680906\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680907\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680908\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680909\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680910\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680911\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680912\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680913\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680914\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680915\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680916\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680917\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680918\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680919\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680920\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680921\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680922\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680923\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680924\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680925\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680926\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680927\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680928\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680929\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680930\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680931\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680932\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680933\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680934\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680935\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680936\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680937\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680938\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"680939\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681014\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681015\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681016\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681017\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681018\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681019\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"currentColor\",\"content\":\"\"},\"681787\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"},\"694557\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"694558\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707431\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707736\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707739\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707741\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707742\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707743\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707744\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"707749\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708142\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708144\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708145\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708146\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708147\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"708181\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"709715\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"808898\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"808900\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"808916\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"810363\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"810396\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"818250\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"818340\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"}}");for(var _k in obj){window.__iconpark__[_k] = obj[_k]};var nm={"fuzhi1":680840,"bianji":680856,"tishi":680857,"xinkaibiaoqian":680858,"bianjiyoujian":680859,"suoyou":680860,"fuzhi":680861,"shijian":680862,"gundongxuanze":680863,"guanbi":680864,"zanting":680865,"chenggong":680866,"chakanyinyong":680867,"guidang":680868,"tihuan":680869,"zhankai":680870,"duankailianjie":680871,"Cookieguanli":680872,"riqi":680873,"zhongwen":680874,"yingwen":680875,"shuaxinjiankongzhuangtai":680876,"rili":680877,"genmulu":680878,"shangxianguanli":680879,"daimashili":680880,"yingyong":680881,"tianjia-2":680882,"qingchu":680883,"daoru":680884,"xiala":680885,"kuaisuceshi-2":680886,"saoyisao":680887,"shiyongjiaocheng":680888,"tianjiafujian":680889,"xiazai":680890,"jinzhidengji":680891,"fasongyoujian":680892,"bug":680893,"chaping":680894,"kuaisuceshi":680895,"yunshangchuan":680896,"yunxiazai":680897,"sousuo":680898,"peizhi":680899,"xinchuangkoudakai":680900,"shanchu-2":680901,"quanjusuoxiao":680902,"qiehuan":680903,"jianshao":680904,"chakanAPIlishi":680905,"lianjie":680906,"dunpaibaoxianrenzheng":680907,"shaixuan":680908,"zhihang":680909,"congmobanzhongchuangjianyongli":680910,"zhengligeshi":680911,"haoping":680912,"shouqi-2":680913,"gouwuche":680914,"lishi":680915,"tianjiaziji":680916,"tianjia":680917,"shouqi":680918,"gailan":680919,"paixu":680920,"gengduo":680921,"guanliyuanrenzheng":680922,"fenxiang":680923,"shanchu":680924,"yidong":680925,"chakan":680926,"shujuku":680927,"shangyoufuwu-":680928,"huanyuangeshi":680929,"jiangxu":680930,"shengxu":680931,"quanjufangda":680932,"xuanzhong":680933,"riqiqujian":680934,"ditu-1":680935,"qunzu":680936,"daochu":680937,"zhankai-":680938,"ditu-2":680939,"Eolink":681014,"APISpace":681015,"Apinto":681016,"json":681017,"webhook":681018,"linux":681019,"xinzengfenzu":681787,"circle-right-up":694557,"circle-right-down":694558,"APIjiekou-7mme3dcg":707431,"connection-box":707736,"system":707739,"form-one":707741,"yingyong-7mmhj11e":707742,"jiankongshexiangtou":707743,"file-cabinet":707744,"network-tree":707749,"search":708142,"find":708144,"circle-right-up-7mnlo5g9":708145,"circle-right-down-7mnlphn2":708146,"reduce-one":708147,"tool":708181,"shangxianguanli-new":709715,"hamburger-button":808898,"puzzle":808900,"keyline":808916,"daohang":810363,"lanjieqiguanli":810396,"shop":818250,"xiangmu":818340};for(var _i in nm){window.__iconpark__[_i] = obj[nm[_i]]}})();"object"!=typeof globalThis&&(Object.prototype.__defineGetter__("__magic__",function(){return this}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__);(()=>{"use strict";var t={816:(t,e,i)=>{var s,r,o,n;i.d(e,{Vm:()=>z,dy:()=>P,Jb:()=>x,Ld:()=>$,sY:()=>T,YP:()=>A});const l=globalThis.trustedTypes,a=l?l.createPolicy("lit-html",{createHTML:t=>t}):void 0,h=`lit$${(Math.random()+"").slice(9)}$`,c="?"+h,d=`<${c}>`,u=document,p=(t="")=>u.createComment(t),v=t=>null===t||"object"!=typeof t&&"function"!=typeof t,f=Array.isArray,y=t=>{var e;return f(t)||"function"==typeof(null===(e=t)||void 0===e?void 0:e[Symbol.iterator])},m=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,g=/-->/g,b=/>/g,S=/>|[ \n \r](?:([^\s"'>=/]+)([ \n \r]*=[ \n \r]*(?:[^ \n \r"'`<>=]|("|')|))|$)/g,w=/'/g,k=/"/g,E=/^(?:script|style|textarea)$/i,C=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),P=C(1),A=C(2),x=Symbol.for("lit-noChange"),$=Symbol.for("lit-nothing"),O=new WeakMap,T=(t,e,i)=>{var s,r;const o=null!==(s=null==i?void 0:i.renderBefore)&&void 0!==s?s:e;let n=o._$litPart$;if(void 0===n){const t=null!==(r=null==i?void 0:i.renderBefore)&&void 0!==r?r:null;o._$litPart$=n=new H(e.insertBefore(p(),t),t,void 0,i)}return n.I(t),n},R=u.createTreeWalker(u,129,null,!1),_=(t,e)=>{const i=t.length-1,s=[];let r,o=2===e?"":"",n=m;for(let e=0;e"===a[0]?(n=null!=r?r:m,c=-1):void 0===a[1]?c=-2:(c=n.lastIndex-a[2].length,l=a[1],n=void 0===a[3]?S:'"'===a[3]?k:w):n===k||n===w?n=S:n===g||n===b?n=m:(n=S,r=void 0);const p=n===S&&t[e+1].startsWith("/>")?" ":"";o+=n===m?i+d:c>=0?(s.push(l),i.slice(0,c)+"$lit$"+i.slice(c)+h+p):i+h+(-2===c?(s.push(void 0),e):p)}const l=o+(t[i]||"")+(2===e?"":"");return[void 0!==a?a.createHTML(l):l,s]};class N{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let r=0,o=0;const n=t.length-1,a=this.parts,[d,u]=_(t,e);if(this.el=N.createElement(d,i),R.currentNode=this.el.content,2===e){const t=this.el.content,e=t.firstChild;e.remove(),t.append(...e.childNodes)}for(;null!==(s=R.nextNode())&&a.length0){s.textContent=l?l.emptyScript:"";for(let i=0;i2||""!==i[0]||""!==i[1]?(this.H=Array(i.length-1).fill($),this.strings=i):this.H=$}get tagName(){return this.element.tagName}I(t,e=this,i,s){const r=this.strings;let o=!1;if(void 0===r)t=U(this,t,e,0),o=!v(t)||t!==this.H&&t!==x,o&&(this.H=t);else{const s=t;let n,l;for(t=r[0],n=0;n{i.r(e),i.d(e,{customElement:()=>s,eventOptions:()=>a,property:()=>o,query:()=>h,queryAll:()=>c,queryAssignedNodes:()=>v,queryAsync:()=>d,state:()=>n});const s=t=>e=>"function"==typeof e?((t,e)=>(window.customElements.define(t,e),e))(t,e):((t,e)=>{const{kind:i,elements:s}=e;return{kind:i,elements:s,finisher(e){window.customElements.define(t,e)}}})(t,e),r=(t,e)=>"method"===e.kind&&e.descriptor&&!("value"in e.descriptor)?{...e,finisher(i){i.createProperty(e.key,t)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:e.key,initializer(){"function"==typeof e.initializer&&(this[e.key]=e.initializer.call(this))},finisher(i){i.createProperty(e.key,t)}};function o(t){return(e,i)=>void 0!==i?((t,e,i)=>{e.constructor.createProperty(i,t)})(t,e,i):r(t,e)}function n(t){return o({...t,state:!0,attribute:!1})}const l=({finisher:t,descriptor:e})=>(i,s)=>{var r;if(void 0===s){const s=null!==(r=i.originalKey)&&void 0!==r?r:i.key,o=null!=e?{kind:"method",placement:"prototype",key:s,descriptor:e(i.key)}:{...i,key:s};return null!=t&&(o.finisher=function(e){t(e,s)}),o}{const r=i.constructor;void 0!==e&&Object.defineProperty(i,s,e(s)),null==t||t(r,s)}};function a(t){return l({finisher:(e,i)=>{Object.assign(e.prototype[i],t)}})}function h(t,e){return l({descriptor:i=>{const s={get(){var e;return null===(e=this.renderRoot)||void 0===e?void 0:e.querySelector(t)},enumerable:!0,configurable:!0};if(e){const e="symbol"==typeof i?Symbol():"__"+i;s.get=function(){var i;return void 0===this[e]&&(this[e]=null===(i=this.renderRoot)||void 0===i?void 0:i.querySelector(t)),this[e]}}return s}})}function c(t){return l({descriptor:e=>({get(){var e;return null===(e=this.renderRoot)||void 0===e?void 0:e.querySelectorAll(t)},enumerable:!0,configurable:!0})})}function d(t){return l({descriptor:e=>({async get(){var e;return await this.updateComplete,null===(e=this.renderRoot)||void 0===e?void 0:e.querySelector(t)},enumerable:!0,configurable:!0})})}const u=Element.prototype,p=u.msMatchesSelector||u.webkitMatchesSelector;function v(t="",e=!1,i=""){return l({descriptor:s=>({get(){var s,r;const o="slot"+(t?`[name=${t}]`:":not([name])");let n=null===(r=null===(s=this.renderRoot)||void 0===s?void 0:s.querySelector(o))||void 0===r?void 0:r.assignedNodes({flatten:e});return n&&i&&(n=n.filter((t=>t.nodeType===Node.ELEMENT_NODE&&(t.matches?t.matches(i):p.call(t,i))))),n},enumerable:!0,configurable:!0})})}},23:(t,e,i)=>{i.r(e),i.d(e,{unsafeSVG:()=>l});const s=t=>(...e)=>({_$litDirective$:t,values:e});var r=i(816);class o extends class{constructor(t){}T(t,e,i){this.Σdt=t,this.M=e,this.Σct=i}S(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}{constructor(t){if(super(t),this.vt=r.Ld,2!==t.type)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===r.Ld)return this.Vt=void 0,this.vt=t;if(t===r.Jb)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.vt)return this.Vt;this.vt=t;const e=[t];return e.raw=e,this.Vt={_$litType$:this.constructor.resultType,strings:e,values:[]}}}o.directiveName="unsafeHTML",o.resultType=1,s(o);class n extends o{}n.directiveName="unsafeSVG",n.resultType=2;const l=s(n)},249:(t,e,i)=>{i.r(e),i.d(e,{CSSResult:()=>n,LitElement:()=>x,ReactiveElement:()=>b,UpdatingElement:()=>A,_Σ:()=>s.Vm,_Φ:()=>$,adoptStyles:()=>c,css:()=>h,defaultConverter:()=>y,getCompatibleStyle:()=>d,html:()=>s.dy,noChange:()=>s.Jb,notEqual:()=>m,nothing:()=>s.Ld,render:()=>s.sY,supportsAdoptingStyleSheets:()=>r,svg:()=>s.YP,unsafeCSS:()=>l});var s=i(816);const r=window.ShadowRoot&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,o=Symbol();class n{constructor(t,e){if(e!==o)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t}get styleSheet(){return r&&void 0===this.t&&(this.t=new CSSStyleSheet,this.t.replaceSync(this.cssText)),this.t}toString(){return this.cssText}}const l=t=>new n(t+"",o),a=new Map,h=(t,...e)=>{const i=e.reduce(((e,i,s)=>e+(t=>{if(t instanceof n)return t.cssText;if("number"==typeof t)return t;throw Error(`Value passed to 'css' function must be a 'css' function result: ${t}. Use 'unsafeCSS' to pass non-literal values, but\n take care to ensure page security.`)})(i)+t[s+1]),t[0]);let s=a.get(i);return void 0===s&&a.set(i,s=new n(i,o)),s},c=(t,e)=>{r?t.adoptedStyleSheets=e.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):e.forEach((e=>{const i=document.createElement("style");i.textContent=e.cssText,t.appendChild(i)}))},d=r?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return l(e)})(t):t;var u,p,v,f;const y={toAttribute(t,e){switch(e){case Boolean:t=t?"":null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},m=(t,e)=>e!==t&&(e==e||t==t),g={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:m};class b extends HTMLElement{constructor(){super(),this.Πi=new Map,this.Πo=void 0,this.Πl=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.Πh=null,this.u()}static addInitializer(t){var e;null!==(e=this.v)&&void 0!==e||(this.v=[]),this.v.push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((e,i)=>{const s=this.Πp(i,e);void 0!==s&&(this.Πm.set(s,i),t.push(s))})),t}static createProperty(t,e=g){if(e.state&&(e.attribute=!1),this.finalize(),this.elementProperties.set(t,e),!e.noAccessor&&!this.prototype.hasOwnProperty(t)){const i="symbol"==typeof t?Symbol():"__"+t,s=this.getPropertyDescriptor(t,i,e);void 0!==s&&Object.defineProperty(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){return{get(){return this[e]},set(s){const r=this[t];this[e]=s,this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||g}static finalize(){if(this.hasOwnProperty("finalized"))return!1;this.finalized=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),this.elementProperties=new Map(t.elementProperties),this.Πm=new Map,this.hasOwnProperty("properties")){const t=this.properties,e=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const i of e)this.createProperty(i,t[i])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(d(t))}else void 0!==t&&e.push(d(t));return e}static Πp(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}u(){var t;this.Πg=new Promise((t=>this.enableUpdating=t)),this.L=new Map,this.Π_(),this.requestUpdate(),null===(t=this.constructor.v)||void 0===t||t.forEach((t=>t(this)))}addController(t){var e,i;(null!==(e=this.ΠU)&&void 0!==e?e:this.ΠU=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(i=t.hostConnected)||void 0===i||i.call(t))}removeController(t){var e;null===(e=this.ΠU)||void 0===e||e.splice(this.ΠU.indexOf(t)>>>0,1)}Π_(){this.constructor.elementProperties.forEach(((t,e)=>{this.hasOwnProperty(e)&&(this.Πi.set(e,this[e]),delete this[e])}))}createRenderRoot(){var t;const e=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return c(e,this.constructor.elementStyles),e}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostConnected)||void 0===e?void 0:e.call(t)})),this.Πl&&(this.Πl(),this.Πo=this.Πl=void 0)}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostDisconnected)||void 0===e?void 0:e.call(t)})),this.Πo=new Promise((t=>this.Πl=t))}attributeChangedCallback(t,e,i){this.K(t,i)}Πj(t,e,i=g){var s,r;const o=this.constructor.Πp(t,i);if(void 0!==o&&!0===i.reflect){const n=(null!==(r=null===(s=i.converter)||void 0===s?void 0:s.toAttribute)&&void 0!==r?r:y.toAttribute)(e,i.type);this.Πh=t,null==n?this.removeAttribute(o):this.setAttribute(o,n),this.Πh=null}}K(t,e){var i,s,r;const o=this.constructor,n=o.Πm.get(t);if(void 0!==n&&this.Πh!==n){const t=o.getPropertyOptions(n),l=t.converter,a=null!==(r=null!==(s=null===(i=l)||void 0===i?void 0:i.fromAttribute)&&void 0!==s?s:"function"==typeof l?l:null)&&void 0!==r?r:y.fromAttribute;this.Πh=n,this[n]=a(e,t.type),this.Πh=null}}requestUpdate(t,e,i){let s=!0;void 0!==t&&(((i=i||this.constructor.getPropertyOptions(t)).hasChanged||m)(this[t],e)?(this.L.has(t)||this.L.set(t,e),!0===i.reflect&&this.Πh!==t&&(void 0===this.Πk&&(this.Πk=new Map),this.Πk.set(t,i))):s=!1),!this.isUpdatePending&&s&&(this.Πg=this.Πq())}async Πq(){this.isUpdatePending=!0;try{for(await this.Πg;this.Πo;)await this.Πo}catch(t){Promise.reject(t)}const t=this.performUpdate();return null!=t&&await t,!this.isUpdatePending}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this.Πi&&(this.Πi.forEach(((t,e)=>this[e]=t)),this.Πi=void 0);let e=!1;const i=this.L;try{e=this.shouldUpdate(i),e?(this.willUpdate(i),null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostUpdate)||void 0===e?void 0:e.call(t)})),this.update(i)):this.Π$()}catch(t){throw e=!1,this.Π$(),t}e&&this.E(i)}willUpdate(t){}E(t){var e;null===(e=this.ΠU)||void 0===e||e.forEach((t=>{var e;return null===(e=t.hostUpdated)||void 0===e?void 0:e.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}Π$(){this.L=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.Πg}shouldUpdate(t){return!0}update(t){void 0!==this.Πk&&(this.Πk.forEach(((t,e)=>this.Πj(e,this[e],t))),this.Πk=void 0),this.Π$()}updated(t){}firstUpdated(t){}}var S,w,k,E,C,P;b.finalized=!0,b.shadowRootOptions={mode:"open"},null===(p=(u=globalThis).reactiveElementPlatformSupport)||void 0===p||p.call(u,{ReactiveElement:b}),(null!==(v=(f=globalThis).reactiveElementVersions)&&void 0!==v?v:f.reactiveElementVersions=[]).push("1.0.0-rc.1");const A=b;(null!==(S=(P=globalThis).litElementVersions)&&void 0!==S?S:P.litElementVersions=[]).push("3.0.0-rc.1");class x extends b{constructor(){super(...arguments),this.renderOptions={host:this},this.Φt=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const e=this.render();super.update(t),this.Φt=(0,s.sY)(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this.Φt)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.Φt)||void 0===t||t.setConnected(!1)}render(){return s.Jb}}x.finalized=!0,x._$litElement$=!0,null===(k=(w=globalThis).litElementHydrateSupport)||void 0===k||k.call(w,{LitElement:x}),null===(C=(E=globalThis).litElementPlatformSupport)||void 0===C||C.call(E,{LitElement:x});const $={K:(t,e,i)=>{t.K(e,i)},L:t=>t.L}},409:function(t,e,i){var s=this&&this.__decorate||function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var l=t.length-1;l>=0;l--)(r=t[l])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};Object.defineProperty(e,"__esModule",{value:!0}),e.IconparkIconElement=void 0;const r=i(249),o=i(26),n=i(23),l={color:1,fill:1,stroke:1},a={STROKE:{trackAttr:"data-follow-stroke",rawAttr:"stroke"},FILL:{trackAttr:"data-follow-fill",rawAttr:"fill"}};class h extends r.LitElement{constructor(){super(...arguments),this.name="",this.identifyer="",this.size="1em"}get _width(){return this.width||this.size}get _height(){return this.height||this.size}get _stroke(){return this.stroke||this.color}get _fill(){return this.fill||this.color}get SVGConfig(){return(window.__iconpark__||{})[this.identifyer]||(window.__iconpark__||{})[this.name]||{viewBox:"0 0 0 0",content:""}}connectedCallback(){super.connectedCallback(),setTimeout((()=>{this.monkeyPatch("STROKE",!0),this.monkeyPatch("FILL",!0)}))}monkeyPatch(t,e){switch(t){case"STROKE":this.updateDOMByHand(this.strokeAppliedNodes,"STROKE",this._stroke,!!e);break;case"FILL":this.updateDOMByHand(this.fillAppliedNodes,"FILL",this._fill,!!e)}}updateDOMByHand(t,e,i,s){!i&&s||t&&t.forEach((t=>{i&&i===t.getAttribute(a[e].rawAttr)||t.setAttribute(a[e].rawAttr,i||t.getAttribute(a[e].trackAttr))}))}attributeChangedCallback(t,e,i){super.attributeChangedCallback(t,e,i),"name"===t||"identifyer"===t?setTimeout((()=>{this.monkeyPatch("STROKE"),this.monkeyPatch("FILL")})):l[t]&&(this.monkeyPatch("STROKE"),this.monkeyPatch("FILL"))}render(){return r.svg`${n.unsafeSVG(this.SVGConfig.content)}`}}h.styles=r.css`:host {display: inline-flex; align-items: center; justify-content: center;} :host([spin]) svg {animation: iconpark-spin 1s infinite linear;} :host([spin][rtl]) svg {animation: iconpark-spin-rtl 1s infinite linear;} :host([rtl]) svg {transform: scaleX(-1);} @keyframes iconpark-spin {0% { -webkit-transform: rotate(0); transform: rotate(0);} 100% {-webkit-transform: rotate(360deg); transform: rotate(360deg);}} @keyframes iconpark-spin-rtl {0% {-webkit-transform: scaleX(-1) rotate(0); transform: scaleX(-1) rotate(0);} 100% {-webkit-transform: scaleX(-1) rotate(360deg); transform: scaleX(-1) rotate(360deg);}}`,s([o.property({reflect:!0})],h.prototype,"name",void 0),s([o.property({reflect:!0,attribute:"icon-id"})],h.prototype,"identifyer",void 0),s([o.property({reflect:!0})],h.prototype,"color",void 0),s([o.property({reflect:!0})],h.prototype,"stroke",void 0),s([o.property({reflect:!0})],h.prototype,"fill",void 0),s([o.property({reflect:!0})],h.prototype,"size",void 0),s([o.property({reflect:!0})],h.prototype,"width",void 0),s([o.property({reflect:!0})],h.prototype,"height",void 0),s([o.queryAll(`[${a.STROKE.trackAttr}]`)],h.prototype,"strokeAppliedNodes",void 0),s([o.queryAll(`[${a.FILL.trackAttr}]`)],h.prototype,"fillAppliedNodes",void 0),e.IconparkIconElement=h,customElements.get("iconpark-icon")||customElements.define("iconpark-icon",h)}},e={};function i(s){var r=e[s];if(void 0!==r)return r.exports;var o=e[s]={exports:{}};return t[s].call(o.exports,o,o.exports,i),o.exports}i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i(409)})(); + \ No newline at end of file diff --git a/frontend/packages/businessEntry/public/iconpark_eolink.js b/frontend/packages/businessEntry/public/iconpark_eolink.js new file mode 100644 index 0000000..5c7f639 --- /dev/null +++ b/frontend/packages/businessEntry/public/iconpark_eolink.js @@ -0,0 +1,7 @@ +/* + * @Date: 2024-05-06 09:53:45 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-05-06 09:53:50 + * @FilePath: \frontend\packages\core\src\assets\iconpark_eolink.js + */ +(function(){window.__iconpark__=window.__iconpark__||{};var obj=JSON.parse("{\"647367\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"684408\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"684409\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"684411\":{\"viewBox\":\"0 0 119.19 102.5\",\"content\":\"\"},\"684412\":{\"viewBox\":\"0 0 108.55 93.99\",\"fill\":\"currentColor\",\"content\":\"\"},\"684413\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"684414\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"686740\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686741\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686742\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686743\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686744\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686745\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686746\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686747\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686748\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686749\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686750\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686751\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686752\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686753\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686754\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"686993\":{\"viewBox\":\"0 0 38.22 22.18\",\"fill\":\"currentColor\",\"content\":\"\"},\"687741\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"687742\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"691262\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"691537\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"691538\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"691806\":{\"viewBox\":\"0 0 194 194\",\"content\":\"\"},\"695738\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695739\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695740\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695741\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695742\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695743\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695746\":{\"viewBox\":\"0 0 1185 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695747\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695748\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695750\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695751\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695752\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695754\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695755\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695756\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"695758\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695759\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695760\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695761\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695762\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695763\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695764\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695801\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695802\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695803\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695804\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695805\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695806\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695807\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695810\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695811\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695812\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695817\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695818\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695819\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695820\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695821\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695822\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695828\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695829\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695830\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695831\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695833\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695834\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695835\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695836\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695837\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695838\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695839\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695840\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695841\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695842\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695844\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695845\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695846\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695865\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695867\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695868\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695869\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695870\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695876\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695877\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695878\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695883\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695884\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695886\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695887\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695888\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695889\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695890\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695891\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695892\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695893\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695896\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695899\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695900\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695901\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695902\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695903\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695904\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695905\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695906\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695907\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695908\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695909\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695913\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695914\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695915\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695916\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695933\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695934\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695935\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695936\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695938\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695940\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695941\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695942\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695944\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695945\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695946\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695947\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695948\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695950\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695951\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695953\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695954\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695955\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695956\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695957\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695958\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695959\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695960\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695961\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695962\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695963\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695964\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695966\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695967\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695968\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695969\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695971\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695972\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695973\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695975\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695978\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695979\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695980\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695981\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695982\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695984\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695985\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695986\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695987\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695988\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695990\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695993\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695995\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695997\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"695999\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696002\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696003\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696004\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696005\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696007\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696009\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696010\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696011\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696012\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696013\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696014\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696015\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696016\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696017\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696018\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696019\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696020\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696021\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696022\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696023\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696024\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696025\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696027\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696028\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696029\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696030\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696031\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696032\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696033\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696034\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696035\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696036\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696037\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696038\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696039\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696040\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696041\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696042\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696043\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696044\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696045\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696046\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696048\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696049\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696660\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"696661\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"744163\":{\"viewBox\":\"0 0 1024 1024\",\"fill\":\"currentColor\",\"content\":\"\"},\"744173\":{\"viewBox\":\"0 0 128 128\",\"fill\":\"none\",\"content\":\"\"},\"744175\":{\"viewBox\":\"0 0 128 128\",\"fill\":\"none\",\"content\":\"\"},\"750656\":{\"viewBox\":\"0 0 61 61\",\"fill\":\"none\",\"content\":\"\"},\"752737\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"756392\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757321\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757499\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757504\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757518\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757519\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757520\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757521\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757616\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"757650\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"767277\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"767278\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"775549\":{\"viewBox\":\"0 0 18 14\",\"fill\":\"none\",\"content\":\"\"},\"779333\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"},\"779418\":{\"viewBox\":\"0 0 1024 1024\",\"content\":\"\"},\"779705\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"779706\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"},\"787702\":{\"viewBox\":\"0 0 1024 1024\",\"content\":\"\"},\"788577\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"802334\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"804269\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"804612\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"804614\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"806103\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"813707\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"815901\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"820089\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"826687\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"854318\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"855246\":{\"viewBox\":\"0 0 16 16\",\"fill\":\"none\",\"content\":\"\"},\"855247\":{\"viewBox\":\"0 0 16 16\",\"fill\":\"none\",\"content\":\"\"},\"855248\":{\"viewBox\":\"0 0 16 16\",\"fill\":\"none\",\"content\":\"\"},\"855927\":{\"viewBox\":\"0 0 83 20\",\"fill\":\"none\",\"content\":\"\"},\"855928\":{\"viewBox\":\"0 0 68 24\",\"fill\":\"none\",\"content\":\"\"},\"855929\":{\"viewBox\":\"0 0 66 24\",\"fill\":\"none\",\"content\":\"\"},\"855938\":{\"viewBox\":\"0 0 198 72\",\"fill\":\"none\",\"content\":\"\"},\"857931\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"857985\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"861388\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"876705\":{\"viewBox\":\"0 0 16 16\",\"fill\":\"none\",\"content\":\"\"},\"884011\":{\"viewBox\":\"0 0 20 20\",\"fill\":\"none\",\"content\":\"\"},\"885387\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"897026\":{\"viewBox\":\"0 0 250 250\",\"fill\":\"none\",\"content\":\"\"},\"915485\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"929257\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"932197\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"949128\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"970590\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"973801\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"985435\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1002903\":{\"viewBox\":\"0 0 24 24\",\"fill\":\"none\",\"content\":\"\"},\"1021623\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1021686\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1035721\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1035737\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1037074\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1037815\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1037816\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1037817\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1039918\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1042170\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"},\"1042171\":{\"viewBox\":\"0 0 48 48\",\"fill\":\"none\",\"content\":\"\"}}");for(var _k in obj){window.__iconpark__[_k] = obj[_k]};var nm={"round-fill":647367,"apinto-pro-icon":684408,"apinto-icon":684409,"apinto-pro":684411,"apinto":684412,"check-circle":684413,"apispace":684414,"auto-generate-api":686740,"compare-api":686741,"multi-protocal":686742,"read-good":686743,"richdoc":686744,"mockapi":686745,"script-support":686746,"diy-test":686747,"send":686748,"stereo-perspective":686749,"automatic-robot":686750,"switch-env":686751,"flash":686752,"chart-pie":686753,"date-drive":686754,"apistudio":686993,"postcat-icon":687741,"postcat":687742,"apistudio-icon":691262,"update-rotation":691537,"page":691538,"apispace-icon":691806,"avatar":695738,"people":695739,"people-minus":695740,"people-plus":695741,"peoples":695742,"user-business":695743,"folder-close-fill":695746,"windows":695747,"github":695748,"qq":695750,"browser-chrome":695751,"linux":695752,"edge":695754,"wechat":695755,"browser":695756,"gitlab":695758,"apple":695759,"alipay":695760,"facebook":695761,"twitter":695762,"paypal":695763,"new-lark":695764,"delete":695801,"return":695802,"search":695803,"import":695804,"export":695805,"add":695806,"add-child":695807,"file-addition":695810,"add-circle":695811,"minus":695812,"close":695817,"close-small":695818,"check-small":695819,"check":695820,"code-terminal":695821,"code":695822,"preview-open":695828,"preview-close":695829,"folder-close":695830,"folder-open":695831,"upload":695833,"download":695834,"copy":695835,"upload-file":695836,"compare":695837,"edit":695838,"share":695839,"share-all":695840,"share-url-fill":695841,"share-url":695842,"back":695844,"back-fill":695845,"share-fill":695846,"sort":695865,"filter":695867,"reduce":695868,"done-all":695869,"full-selection":695870,"right-bar":695876,"left-bar":695877,"direction-adjustment":695878,"down-small":695883,"left-small":695884,"right-small":695886,"right-one":695887,"right":695888,"up":695889,"up-one":695890,"up-small":695891,"up-two":695892,"down-two":695893,"enter":695896,"down":695899,"left":695900,"down-one":695901,"left-two":695902,"right-two":695903,"left-one":695904,"more":695905,"expand-left":695906,"expand-right":695907,"column":695908,"center-alignment":695909,"list-add":695913,"sort-amount-down":695914,"sort-amount-up":695915,"list":695916,"remind":695933,"close-remind":695934,"api":695935,"rocket":695936,"monitor":695938,"robot":695940,"plan":695941,"application":695942,"chart-proportion":695944,"data":695945,"chart-line":695946,"pie-10":695947,"pie":695948,"chart-bubble":695950,"cube":695951,"application-menu":695953,"crown":695954,"crown-fill":695955,"market":695956,"file-word":695957,"file-excel":695958,"hashtag-key":695959,"file-hash":695960,"refresh":695961,"order":695962,"command":695963,"branch":695964,"page-template":695966,"smart-optimization":695967,"assembly-line":695968,"stopwatch":695969,"checklist":695971,"menu-fold":695972,"menu-unfold":695973,"alarm":695975,"protection":695978,"caution":695979,"openapi":695980,"webhook":695981,"holding-hands":695982,"support":695984,"agreement":695985,"community":695986,"roadmap":695987,"family-7knl2ae1":695988,"smiling-face":695990,"play-fill":695993,"play":695995,"pause":695997,"magic":695999,"whole-site-accelerator":696002,"link-cloud-faild":696003,"link-cloud-sucess":696004,"translate":696005,"funds":696007,"unhappy-face":696009,"message":696010,"connection-arrow":696011,"loading":696012,"fork":696013,"quote":696014,"headset":696015,"attention":696016,"theme":696017,"keyboard":696018,"briefcase":696019,"star":696020,"star-7knmka28":696021,"protect":696022,"finance":696023,"setting":696024,"link":696025,"undo":696027,"inbox-success":696028,"home":696029,"local":696030,"laptop":696031,"view-list":696032,"lock":696033,"unlock":696034,"lightning":696035,"file-text":696036,"cooperative-handshake":696037,"navigation":696038,"view-grid-detail":696039,"help":696040,"history":696041,"logout-7knnioon":696042,"chinese":696043,"calendar":696044,"play-cycle":696045,"world":696046,"plugins":696048,"link-cloud":696049,"book":696660,"table-report":696661,"qiyeweixin":744163,"Oauth":744173,"dingding":744175,"eolink":750656,"tool":752737,"category-management":756392,"folder-code-one":757321,"link-three-8ah7lifn":757499,"download-two-8ah85008":757504,"quanjusuoxiao1":757518,"quanjufangda21":757519,"quanjusuoxiao211":757520,"quanjufangda1":757521,"wenjianshezhi":757616,"key":757650,"zidingyijiaoben":767277,"tiqubianliang":767278,"mock":775549,"tongzhishezhi":779333,"csdn":779418,"ceshibaogao":779705,"biangengtongzhi":779706,"icon-api":787702,"youjian":788577,"pushpin":802334,"announcement":804269,"collapse-text-input":804612,"zhankai":804614,"replay-music":806103,"download-web":813707,"permissions":815901,"file-editing":820089,"wallet":826687,"file-focus":854318,"pingpu-9a913n0n":855246,"zuoyoufenping-9a913n1f":855247,"shangxiafenping-9a913n1i":855248,"Paypal11":855927,"zhifubaozhifu1":855928,"weixinzhifu11":855929,"weixinzhifu":855938,"update-rotation-9and40f5":857931,"terminal":857985,"switch":861388,"zhinengrucan":876705,"biaoqian-banbenleixinzeng":884011,"book-open":885387,"morentouxiang-2":897026,"xiajia":915485,"drag":929257,"new-up":932197,"rss":949128,"yewuchangjing":970590,"newlybuild":973801,"bianji":985435,"jiekoushouquan":1002903,"interfacefenzutubiao":1021623,"yidong":1021686,"link-one":1035721,"canshugouzaoqi":1035737,"bianliang":1037074,"tars":1037815,"if":1037816,"tars-2":1037817,"yingyongguanxi":1039918,"save-one":1042170,"save":1042171};for(var _i in nm){window.__iconpark__[_i] = obj[nm[_i]]}})();"object"!=typeof globalThis&&(Object.prototype.__defineGetter__("__magic__",function(){return this}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__);(()=>{"use strict";var t={816:(t,e,i)=>{var s,r,o,n;i.d(e,{Vm:()=>z,dy:()=>P,Jb:()=>x,Ld:()=>$,sY:()=>T,YP:()=>A});const l=globalThis.trustedTypes,a=l?l.createPolicy("lit-html",{createHTML:t=>t}):void 0,h=`lit$${(Math.random()+"").slice(9)}$`,c="?"+h,d=`<${c}>`,u=document,p=(t="")=>u.createComment(t),v=t=>null===t||"object"!=typeof t&&"function"!=typeof t,f=Array.isArray,y=t=>{var e;return f(t)||"function"==typeof(null===(e=t)||void 0===e?void 0:e[Symbol.iterator])},m=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,g=/-->/g,b=/>/g,S=/>|[ \n \r](?:([^\s"'>=/]+)([ \n \r]*=[ \n \r]*(?:[^ \n \r"'`<>=]|("|')|))|$)/g,w=/'/g,k=/"/g,E=/^(?:script|style|textarea)$/i,C=t=>(e,...i)=>({_$litType$:t,strings:e,values:i}),P=C(1),A=C(2),x=Symbol.for("lit-noChange"),$=Symbol.for("lit-nothing"),O=new WeakMap,T=(t,e,i)=>{var s,r;const o=null!==(s=null==i?void 0:i.renderBefore)&&void 0!==s?s:e;let n=o._$litPart$;if(void 0===n){const t=null!==(r=null==i?void 0:i.renderBefore)&&void 0!==r?r:null;o._$litPart$=n=new H(e.insertBefore(p(),t),t,void 0,i)}return n.I(t),n},R=u.createTreeWalker(u,129,null,!1),_=(t,e)=>{const i=t.length-1,s=[];let r,o=2===e?"":"",n=m;for(let e=0;e"===a[0]?(n=null!=r?r:m,c=-1):void 0===a[1]?c=-2:(c=n.lastIndex-a[2].length,l=a[1],n=void 0===a[3]?S:'"'===a[3]?k:w):n===k||n===w?n=S:n===g||n===b?n=m:(n=S,r=void 0);const p=n===S&&t[e+1].startsWith("/>")?" ":"";o+=n===m?i+d:c>=0?(s.push(l),i.slice(0,c)+"$lit$"+i.slice(c)+h+p):i+h+(-2===c?(s.push(void 0),e):p)}const l=o+(t[i]||"")+(2===e?"":"");return[void 0!==a?a.createHTML(l):l,s]};class N{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let r=0,o=0;const n=t.length-1,a=this.parts,[d,u]=_(t,e);if(this.el=N.createElement(d,i),R.currentNode=this.el.content,2===e){const t=this.el.content,e=t.firstChild;e.remove(),t.append(...e.childNodes)}for(;null!==(s=R.nextNode())&&a.length0){s.textContent=l?l.emptyScript:"";for(let i=0;i2||""!==i[0]||""!==i[1]?(this.H=Array(i.length-1).fill($),this.strings=i):this.H=$}get tagName(){return this.element.tagName}I(t,e=this,i,s){const r=this.strings;let o=!1;if(void 0===r)t=U(this,t,e,0),o=!v(t)||t!==this.H&&t!==x,o&&(this.H=t);else{const s=t;let n,l;for(t=r[0],n=0;n{i.r(e),i.d(e,{customElement:()=>s,eventOptions:()=>a,property:()=>o,query:()=>h,queryAll:()=>c,queryAssignedNodes:()=>v,queryAsync:()=>d,state:()=>n});const s=t=>e=>"function"==typeof e?((t,e)=>(window.customElements.define(t,e),e))(t,e):((t,e)=>{const{kind:i,elements:s}=e;return{kind:i,elements:s,finisher(e){window.customElements.define(t,e)}}})(t,e),r=(t,e)=>"method"===e.kind&&e.descriptor&&!("value"in e.descriptor)?{...e,finisher(i){i.createProperty(e.key,t)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:e.key,initializer(){"function"==typeof e.initializer&&(this[e.key]=e.initializer.call(this))},finisher(i){i.createProperty(e.key,t)}};function o(t){return(e,i)=>void 0!==i?((t,e,i)=>{e.constructor.createProperty(i,t)})(t,e,i):r(t,e)}function n(t){return o({...t,state:!0,attribute:!1})}const l=({finisher:t,descriptor:e})=>(i,s)=>{var r;if(void 0===s){const s=null!==(r=i.originalKey)&&void 0!==r?r:i.key,o=null!=e?{kind:"method",placement:"prototype",key:s,descriptor:e(i.key)}:{...i,key:s};return null!=t&&(o.finisher=function(e){t(e,s)}),o}{const r=i.constructor;void 0!==e&&Object.defineProperty(i,s,e(s)),null==t||t(r,s)}};function a(t){return l({finisher:(e,i)=>{Object.assign(e.prototype[i],t)}})}function h(t,e){return l({descriptor:i=>{const s={get(){var e;return null===(e=this.renderRoot)||void 0===e?void 0:e.querySelector(t)},enumerable:!0,configurable:!0};if(e){const e="symbol"==typeof i?Symbol():"__"+i;s.get=function(){var i;return void 0===this[e]&&(this[e]=null===(i=this.renderRoot)||void 0===i?void 0:i.querySelector(t)),this[e]}}return s}})}function c(t){return l({descriptor:e=>({get(){var e;return null===(e=this.renderRoot)||void 0===e?void 0:e.querySelectorAll(t)},enumerable:!0,configurable:!0})})}function d(t){return l({descriptor:e=>({async get(){var e;return await this.updateComplete,null===(e=this.renderRoot)||void 0===e?void 0:e.querySelector(t)},enumerable:!0,configurable:!0})})}const u=Element.prototype,p=u.msMatchesSelector||u.webkitMatchesSelector;function v(t="",e=!1,i=""){return l({descriptor:s=>({get(){var s,r;const o="slot"+(t?`[name=${t}]`:":not([name])");let n=null===(r=null===(s=this.renderRoot)||void 0===s?void 0:s.querySelector(o))||void 0===r?void 0:r.assignedNodes({flatten:e});return n&&i&&(n=n.filter((t=>t.nodeType===Node.ELEMENT_NODE&&(t.matches?t.matches(i):p.call(t,i))))),n},enumerable:!0,configurable:!0})})}},23:(t,e,i)=>{i.r(e),i.d(e,{unsafeSVG:()=>l});const s=t=>(...e)=>({_$litDirective$:t,values:e});var r=i(816);class o extends class{constructor(t){}T(t,e,i){this.Σdt=t,this.M=e,this.Σct=i}S(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}{constructor(t){if(super(t),this.vt=r.Ld,2!==t.type)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===r.Ld)return this.Vt=void 0,this.vt=t;if(t===r.Jb)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.vt)return this.Vt;this.vt=t;const e=[t];return e.raw=e,this.Vt={_$litType$:this.constructor.resultType,strings:e,values:[]}}}o.directiveName="unsafeHTML",o.resultType=1,s(o);class n extends o{}n.directiveName="unsafeSVG",n.resultType=2;const l=s(n)},249:(t,e,i)=>{i.r(e),i.d(e,{CSSResult:()=>n,LitElement:()=>x,ReactiveElement:()=>b,UpdatingElement:()=>A,_Σ:()=>s.Vm,_Φ:()=>$,adoptStyles:()=>c,css:()=>h,defaultConverter:()=>y,getCompatibleStyle:()=>d,html:()=>s.dy,noChange:()=>s.Jb,notEqual:()=>m,nothing:()=>s.Ld,render:()=>s.sY,supportsAdoptingStyleSheets:()=>r,svg:()=>s.YP,unsafeCSS:()=>l});var s=i(816);const r=window.ShadowRoot&&(void 0===window.ShadyCSS||window.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,o=Symbol();class n{constructor(t,e){if(e!==o)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t}get styleSheet(){return r&&void 0===this.t&&(this.t=new CSSStyleSheet,this.t.replaceSync(this.cssText)),this.t}toString(){return this.cssText}}const l=t=>new n(t+"",o),a=new Map,h=(t,...e)=>{const i=e.reduce(((e,i,s)=>e+(t=>{if(t instanceof n)return t.cssText;if("number"==typeof t)return t;throw Error(`Value passed to 'css' function must be a 'css' function result: ${t}. Use 'unsafeCSS' to pass non-literal values, but\n take care to ensure page security.`)})(i)+t[s+1]),t[0]);let s=a.get(i);return void 0===s&&a.set(i,s=new n(i,o)),s},c=(t,e)=>{r?t.adoptedStyleSheets=e.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet)):e.forEach((e=>{const i=document.createElement("style");i.textContent=e.cssText,t.appendChild(i)}))},d=r?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return l(e)})(t):t;var u,p,v,f;const y={toAttribute(t,e){switch(e){case Boolean:t=t?"":null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let i=t;switch(e){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},m=(t,e)=>e!==t&&(e==e||t==t),g={attribute:!0,type:String,converter:y,reflect:!1,hasChanged:m};class b extends HTMLElement{constructor(){super(),this.Πi=new Map,this.Πo=void 0,this.Πl=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.Πh=null,this.u()}static addInitializer(t){var e;null!==(e=this.v)&&void 0!==e||(this.v=[]),this.v.push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach(((e,i)=>{const s=this.Πp(i,e);void 0!==s&&(this.Πm.set(s,i),t.push(s))})),t}static createProperty(t,e=g){if(e.state&&(e.attribute=!1),this.finalize(),this.elementProperties.set(t,e),!e.noAccessor&&!this.prototype.hasOwnProperty(t)){const i="symbol"==typeof t?Symbol():"__"+t,s=this.getPropertyDescriptor(t,i,e);void 0!==s&&Object.defineProperty(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){return{get(){return this[e]},set(s){const r=this[t];this[e]=s,this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||g}static finalize(){if(this.hasOwnProperty("finalized"))return!1;this.finalized=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),this.elementProperties=new Map(t.elementProperties),this.Πm=new Map,this.hasOwnProperty("properties")){const t=this.properties,e=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(const i of e)this.createProperty(i,t[i])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)e.unshift(d(t))}else void 0!==t&&e.push(d(t));return e}static Πp(t,e){const i=e.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}u(){var t;this.Πg=new Promise((t=>this.enableUpdating=t)),this.L=new Map,this.Π_(),this.requestUpdate(),null===(t=this.constructor.v)||void 0===t||t.forEach((t=>t(this)))}addController(t){var e,i;(null!==(e=this.ΠU)&&void 0!==e?e:this.ΠU=[]).push(t),void 0!==this.renderRoot&&this.isConnected&&(null===(i=t.hostConnected)||void 0===i||i.call(t))}removeController(t){var e;null===(e=this.ΠU)||void 0===e||e.splice(this.ΠU.indexOf(t)>>>0,1)}Π_(){this.constructor.elementProperties.forEach(((t,e)=>{this.hasOwnProperty(e)&&(this.Πi.set(e,this[e]),delete this[e])}))}createRenderRoot(){var t;const e=null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);return c(e,this.constructor.elementStyles),e}connectedCallback(){var t;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostConnected)||void 0===e?void 0:e.call(t)})),this.Πl&&(this.Πl(),this.Πo=this.Πl=void 0)}enableUpdating(t){}disconnectedCallback(){var t;null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostDisconnected)||void 0===e?void 0:e.call(t)})),this.Πo=new Promise((t=>this.Πl=t))}attributeChangedCallback(t,e,i){this.K(t,i)}Πj(t,e,i=g){var s,r;const o=this.constructor.Πp(t,i);if(void 0!==o&&!0===i.reflect){const n=(null!==(r=null===(s=i.converter)||void 0===s?void 0:s.toAttribute)&&void 0!==r?r:y.toAttribute)(e,i.type);this.Πh=t,null==n?this.removeAttribute(o):this.setAttribute(o,n),this.Πh=null}}K(t,e){var i,s,r;const o=this.constructor,n=o.Πm.get(t);if(void 0!==n&&this.Πh!==n){const t=o.getPropertyOptions(n),l=t.converter,a=null!==(r=null!==(s=null===(i=l)||void 0===i?void 0:i.fromAttribute)&&void 0!==s?s:"function"==typeof l?l:null)&&void 0!==r?r:y.fromAttribute;this.Πh=n,this[n]=a(e,t.type),this.Πh=null}}requestUpdate(t,e,i){let s=!0;void 0!==t&&(((i=i||this.constructor.getPropertyOptions(t)).hasChanged||m)(this[t],e)?(this.L.has(t)||this.L.set(t,e),!0===i.reflect&&this.Πh!==t&&(void 0===this.Πk&&(this.Πk=new Map),this.Πk.set(t,i))):s=!1),!this.isUpdatePending&&s&&(this.Πg=this.Πq())}async Πq(){this.isUpdatePending=!0;try{for(await this.Πg;this.Πo;)await this.Πo}catch(t){Promise.reject(t)}const t=this.performUpdate();return null!=t&&await t,!this.isUpdatePending}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this.Πi&&(this.Πi.forEach(((t,e)=>this[e]=t)),this.Πi=void 0);let e=!1;const i=this.L;try{e=this.shouldUpdate(i),e?(this.willUpdate(i),null===(t=this.ΠU)||void 0===t||t.forEach((t=>{var e;return null===(e=t.hostUpdate)||void 0===e?void 0:e.call(t)})),this.update(i)):this.Π$()}catch(t){throw e=!1,this.Π$(),t}e&&this.E(i)}willUpdate(t){}E(t){var e;null===(e=this.ΠU)||void 0===e||e.forEach((t=>{var e;return null===(e=t.hostUpdated)||void 0===e?void 0:e.call(t)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}Π$(){this.L=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.Πg}shouldUpdate(t){return!0}update(t){void 0!==this.Πk&&(this.Πk.forEach(((t,e)=>this.Πj(e,this[e],t))),this.Πk=void 0),this.Π$()}updated(t){}firstUpdated(t){}}var S,w,k,E,C,P;b.finalized=!0,b.shadowRootOptions={mode:"open"},null===(p=(u=globalThis).reactiveElementPlatformSupport)||void 0===p||p.call(u,{ReactiveElement:b}),(null!==(v=(f=globalThis).reactiveElementVersions)&&void 0!==v?v:f.reactiveElementVersions=[]).push("1.0.0-rc.1");const A=b;(null!==(S=(P=globalThis).litElementVersions)&&void 0!==S?S:P.litElementVersions=[]).push("3.0.0-rc.1");class x extends b{constructor(){super(...arguments),this.renderOptions={host:this},this.Φt=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const e=this.render();super.update(t),this.Φt=(0,s.sY)(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this.Φt)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this.Φt)||void 0===t||t.setConnected(!1)}render(){return s.Jb}}x.finalized=!0,x._$litElement$=!0,null===(k=(w=globalThis).litElementHydrateSupport)||void 0===k||k.call(w,{LitElement:x}),null===(C=(E=globalThis).litElementPlatformSupport)||void 0===C||C.call(E,{LitElement:x});const $={K:(t,e,i)=>{t.K(e,i)},L:t=>t.L}},409:function(t,e,i){var s=this&&this.__decorate||function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var l=t.length-1;l>=0;l--)(r=t[l])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};Object.defineProperty(e,"__esModule",{value:!0}),e.IconparkIconElement=void 0;const r=i(249),o=i(26),n=i(23),l={color:1,fill:1,stroke:1},a={STROKE:{trackAttr:"data-follow-stroke",rawAttr:"stroke"},FILL:{trackAttr:"data-follow-fill",rawAttr:"fill"}};class h extends r.LitElement{constructor(){super(...arguments),this.name="",this.identifyer="",this.size="1em"}get _width(){return this.width||this.size}get _height(){return this.height||this.size}get _stroke(){return this.stroke||this.color}get _fill(){return this.fill||this.color}get SVGConfig(){return(window.__iconpark__||{})[this.identifyer]||(window.__iconpark__||{})[this.name]||{viewBox:"0 0 0 0",content:""}}connectedCallback(){super.connectedCallback(),setTimeout((()=>{this.monkeyPatch("STROKE",!0),this.monkeyPatch("FILL",!0)}))}monkeyPatch(t,e){switch(t){case"STROKE":this.updateDOMByHand(this.strokeAppliedNodes,"STROKE",this._stroke,!!e);break;case"FILL":this.updateDOMByHand(this.fillAppliedNodes,"FILL",this._fill,!!e)}}updateDOMByHand(t,e,i,s){!i&&s||t&&t.forEach((t=>{i&&i===t.getAttribute(a[e].rawAttr)||t.setAttribute(a[e].rawAttr,i||t.getAttribute(a[e].trackAttr))}))}attributeChangedCallback(t,e,i){super.attributeChangedCallback(t,e,i),"name"===t||"identifyer"===t?setTimeout((()=>{this.monkeyPatch("STROKE"),this.monkeyPatch("FILL")})):l[t]&&(this.monkeyPatch("STROKE"),this.monkeyPatch("FILL"))}render(){return r.svg`${n.unsafeSVG(this.SVGConfig.content)}`}}h.styles=r.css`:host {display: inline-flex; align-items: center; justify-content: center;} :host([spin]) svg {animation: iconpark-spin 1s infinite linear;} :host([spin][rtl]) svg {animation: iconpark-spin-rtl 1s infinite linear;} :host([rtl]) svg {transform: scaleX(-1);} @keyframes iconpark-spin {0% { -webkit-transform: rotate(0); transform: rotate(0);} 100% {-webkit-transform: rotate(360deg); transform: rotate(360deg);}} @keyframes iconpark-spin-rtl {0% {-webkit-transform: scaleX(-1) rotate(0); transform: scaleX(-1) rotate(0);} 100% {-webkit-transform: scaleX(-1) rotate(360deg); transform: scaleX(-1) rotate(360deg);}}`,s([o.property({reflect:!0})],h.prototype,"name",void 0),s([o.property({reflect:!0,attribute:"icon-id"})],h.prototype,"identifyer",void 0),s([o.property({reflect:!0})],h.prototype,"color",void 0),s([o.property({reflect:!0})],h.prototype,"stroke",void 0),s([o.property({reflect:!0})],h.prototype,"fill",void 0),s([o.property({reflect:!0})],h.prototype,"size",void 0),s([o.property({reflect:!0})],h.prototype,"width",void 0),s([o.property({reflect:!0})],h.prototype,"height",void 0),s([o.queryAll(`[${a.STROKE.trackAttr}]`)],h.prototype,"strokeAppliedNodes",void 0),s([o.queryAll(`[${a.FILL.trackAttr}]`)],h.prototype,"fillAppliedNodes",void 0),e.IconparkIconElement=h,customElements.get("iconpark-icon")||customElements.define("iconpark-icon",h)}},e={};function i(s){var r=e[s];if(void 0!==r)return r.exports;var o=e[s]={exports:{}};return t[s].call(o.exports,o,o.exports,i),o.exports}i.d=(t,e)=>{for(var s in e)i.o(e,s)&&!i.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:e[s]})},i.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i(409)})(); \ No newline at end of file diff --git a/frontend/packages/businessEntry/public/vite.svg b/frontend/packages/businessEntry/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/frontend/packages/businessEntry/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/packages/businessEntry/src/App.tsx b/frontend/packages/businessEntry/src/App.tsx new file mode 100644 index 0000000..225862b --- /dev/null +++ b/frontend/packages/businessEntry/src/App.tsx @@ -0,0 +1,153 @@ +/* + * @Date: 2023-11-27 17:18:27 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-07-12 19:54:26 + * @FilePath: \frontend\packages\businessEntry\src\App.tsx + */ +import '@core/App.css' +import { ConfigProvider } from 'antd'; +import RenderRoutes from '@businessEntry/components/aoplatform/RenderRoutes'; +import {BreadcrumbProvider} from "@common/contexts/BreadcrumbContext.tsx"; +import { StyleProvider } from '@ant-design/cssinjs'; +import zhCN from 'antd/locale/zh_CN'; +import useInitializeMonaco from "@common/hooks/useInitializeMonaco"; + +const antdComponentThemeToken = { + token: { + // Seed Token,影响范围大 + colorPrimary: '#7371fc', + colorLink:'#7371fc', + colorBorder:'#ededed', + colorText:'#333', + borderRadius: 4, + // 派生变量,影响范围小 + colorBgContainer: '#fff', + colorPrimaryBg:'#EBEEF2', + colorTextQuaternary:'#BBB', + colorTextTertiary:'#999' + }, + components:{ + // 派生变量,影响范围小 + Input:{ + activeShadow:'none' + }, + Select:{ + activeShadow:'none' + }, + Checkbox:{ + activeShadow:'none' + }, + Cascader:{ + activeShadow:'none', + optionSelectedBg:'#EBEEF2', + optionHoverBg:'#EBEEF2' + }, + Layout: { + bodyBg: '#fff', + headerBg: '#fff', + headerColor: '#333', + headerHeight: 50, + headerPadding: '10 20px', + lightSiderBg: '#fff', + siderBg: '#fff', + }, + Breadcrumb:{ + itemColor:'#666', + linkColor:'#666', + lastItemColor:'#333', + }, + Table:{ + headerBorderRadius:0, + headerSplitColor:'#ededed', + borderColor:'#ededed', + cellPaddingBlockMD:'10px', + cellPaddingInlineMD:'12px', + cellPaddingBlockSM:'8px', + cellPaddingInlineSM:'12px', + headerFilterHoverBg:'#EBEEF2', + headerSortActiveBg:'#F7F8FA', + headerSortHoverBg:'#F7F8FA', + fixedHeaderSortActiveBg:'#F7F8FA', + headerBg:'#F7F8FA', + rowHoverBg:'#EBEEF2' + + }, + Segmented:{ + itemColor:'#333', + itemSelectedColor:'#333', + trackBg:'#f7f8fa', + trackPadding:0, + // itemHoverColor:'#EBEEF2', + itemActiveBg:'#EBEEF2', + itemHoverBg:'#EBEEF2', + itemSelectedBg:'#EBEEF2', + }, + Tree:{ + // titleHeight:30, + // fontSize:12, + directoryNodeSelectedBg:'#EBEEF2', + directoryNodeSelectedColor:'#333', + nodeSelectedBg:'#EBEEF2', + nodeHoverBg:'#EBEEF2' + }, + Collapse:{ + headerBg:'#f7f8fa', + headerPadding:"12px", + contentPadding:"0 10px 12px 10px" + }, + Button:{ + // paddingInline:8, + dangerShadow:'none', + defaultShadow:'none', + primaryShadow:'none' + }, + Tabs:{ + cardBg:'#EBEEF2', + cardHeight:42, + horizontalItemGutter:8, + horizontalItemPaddingSM:'12px 8px 8px 8px', + horizontalItemPadding:'12px 8px 8px 8px', + }, + Menu:{ + // itemBg:'#F7F8FA', + // subMenuItemBg:'#F7F8FA', + // itemMarginBlock:0, + // activeBarBorderWidth:0, + // itemSelectedColor:'#333', + // itemSelectedBg:'#EBEEF2', + // itemHoverBg:'#EBEEF2' + }, + List:{ + itemPadding:'8px 0' + }, + Form:{ + itemMarginBottom:10, + + }, + Alert:{ + defaultPadding:'12px 16px' + }, + Tag:{ + defaultBg:"#f7f8fa" + }, + } +} + +function App() { + useInitializeMonaco() + + return ( + + + + + + + + ); +} + +export default App diff --git a/frontend/packages/businessEntry/src/components/aoplatform/RenderRoutes.tsx b/frontend/packages/businessEntry/src/components/aoplatform/RenderRoutes.tsx new file mode 100644 index 0000000..01c1d6b --- /dev/null +++ b/frontend/packages/businessEntry/src/components/aoplatform/RenderRoutes.tsx @@ -0,0 +1,533 @@ +/* + * @Date: 2024-06-04 08:54:24 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-07-12 19:55:47 + * @FilePath: \frontend\packages\businessEntry\src\components\aoplatform\RenderRoutes.tsx + */ +import { BrowserRouter as Router, Routes, Route, Navigate, Outlet } from 'react-router-dom'; +import Login from "@core/pages/Login.tsx" +import BasicLayout from '@common/components/aoplatform/BasicLayout'; +import {createElement, ReactElement,ReactNode,Suspense} from 'react'; +import { v4 as uuidv4 } from 'uuid' +import {App, Skeleton} from "antd"; +import ApprovalPage from "@core/pages/approval/ApprovalPage.tsx"; +import {SystemProvider} from "@core/contexts/SystemContext.tsx"; +import {useGlobalContext} from "@common/contexts/GlobalStateContext.tsx"; +import {FC,lazy} from 'react'; +import { TeamProvider } from '@core/contexts/TeamContext.tsx'; +import SystemOutlet from '@core/pages/system/SystemOutlet.tsx'; +import { DashboardProvider } from '@core/contexts/DashboardContext.tsx'; +import { PartitionProvider } from '@core/contexts/PartitionContext.tsx'; +import { TenantManagementProvider } from '@market/contexts/TenantManagementContext.tsx'; + +type RouteConfig = { + path:string + component?:ReactElement + children?:(RouteConfig|false)[] + key:string + provider?:FC<{ children: ReactNode; }> + lazy?:unknown +} +const APP_MODE = import.meta.env.VITE_APP_MODE; +export type RouterParams = { + orgId:string + teamId:string + systemId:string + apiId:string + serviceId:string + partitionId:string + clusterId:string; + memberGroupId:string + userGroupId:string + pluginName:string + moduleId:string + accessType:'project'|'team'|'system' + categoryId:string + tagId:string + dashboardType:string + dashboardDetailId:string + topologyId:string + appId:string +} + +const PUBLIC_ROUTES:RouteConfig[] = [ + { + path:'/', + component:, + key: uuidv4(), + }, + { + path:'/login', + component:, + key: uuidv4() + }, + { + path:'/', + component:, + key: uuidv4(), + children:[ + { + path:'approval/*', + component:, + key:uuidv4() + }, + { + path:'organization/*', + component:, + key: uuidv4(), + children:[ + { + path:'list', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/organization/OrganizationList.tsx')) + } + ] + }, + { + path:'team/*', + component:, + key: uuidv4(), + provider: TeamProvider, + children:[ + { + path:'list', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamList.tsx')) + }, + { + path:'inside/:orgId/:teamId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsidePage.tsx')), + key: uuidv4(), + children:[ + { + path:'member', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsideMember.tsx')), + }, + { + path:'access', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsideAccess.tsx')), + }, + { + path:'setting', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamConfig.tsx')), + }, + ] + } + ] + }, + { + path:'system/*', + component:, + key: uuidv4(), + provider: SystemProvider, + children:[ + { + path:'list', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemList.tsx')), + }, + { + path:'list/:orgId/:teamId', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemList.tsx')), + }, + { + path:':orgId/:teamId', + component:, + key: uuidv4(), + children:[ + { + path:'inside/:systemId', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsidePage.tsx')), + children:[ + { + path:'api', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/api/SystemInsideApiList.tsx')), + }, + { + path:'upstream', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/upstream/SystemInsideUpstreamContent.tsx')), + }, + { + path:'myService', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/myService/SystemInsideMyService.tsx')), + }, + { + path:'subService', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/subSubscribe/SystemInsideSubService.tsx')), + children:[ + + ] + }, + { + path:'subscriber', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideSubscriber.tsx')), + children:[ + + ] + }, + { + path:'approval', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/approval/SystemInsideApproval.tsx')), + children:[ + { + path:'*', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/approval/SystemInsideApprovalList.tsx')), + } + ] + }, + { + path:'topology', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemTopology.tsx')), + key: uuidv4(), + children:[ + ] + }, + { + path:'authority', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/authority/SystemInsideAuthority.tsx')), + children:[ + + ] + }, + { + path:'publish', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/publish/SystemInsidePublish.tsx')), + children:[ + { + path:'*', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/publish/SystemInsidePublishList.tsx')), + } + ] + }, + { + path:'access', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideAccess.tsx')), + }, + { + path:'member', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideMember.tsx')), + }, + { + path:'setting', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemConfig.tsx')), + children:[ + + ] + }, + ] + } + ] + } + ] + }, + { + path:'partition/*', + component:, + key: uuidv4(), + children:[ + { + path:'list', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionList.tsx')), + }, + { + path:'inside/:partitionId', + key: uuidv4(), + provider:PartitionProvider, + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsidePage.tsx')), + children:[ + { + path:'cluster', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideCluster.tsx')), + }, + { + path:'cert', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideCert.tsx')), + }, + APP_MODE === 'pro' &&{ + path:'dashboard_setting', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideDashboardSetting.tsx')), + }, + { + path:'setting', + key: uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionConfig.tsx')), + }, + { + path:'template/:moduleId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + key:uuidv4() + } + ] + } + ] + }, + { + path:'serviceHub', + component:, + key:uuidv4(), + children:[ + { + path:'list', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/ServiceHubList.tsx')), + }, + { + path:'detail/:serviceId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/ServiceHubDetail.tsx')), + }] + }, + { + path:'servicecategories', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/serviceCategory/ServiceCategory.tsx')), + key:uuidv4(), + }, + { + path:'tenantManagement', + component:, + provider:TenantManagementProvider, + key:uuidv4(), + children:[ + { + path:':teamId/inside/:appId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsidePage.tsx')), + children:[ + { + path:'service/:partitionId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsideService.tsx')), + }, + { + path:'authorization', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsideAuth.tsx')), + }, + { + path:'setting', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementAppSetting.tsx')), + }, + ] + }, + { + path:'list', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ServiceHubManagement.tsx')), + }, + { + path:'list/:teamId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ServiceHubManagement.tsx')), + }, + ] + }, + { + path:'member/*', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberPage.tsx')), + children:[ + { + path:'list', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberList.tsx')), + }, + { + path:'list/:memberGroupId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberList.tsx')), + } + ] + }, + { + path:'user/*', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserPage.tsx')), + children:[ + { + path:'list', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserList.tsx')), + }, + { + path:'list/:userGroupId', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserList.tsx')), + } + ] + }, + { + path:'role/*', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/role/RoleList.tsx')), + }, + { + path:'access', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/access/AccessPage.tsx')), + children:[ + { + path:':accessType', + key:uuidv4(), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/access/AccessList.tsx')), + }, + ] + }, + APP_MODE === 'pro' &&{ + path:'openapi', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@openApi/pages/OpenApiList.tsx')), + key:uuidv4(), + }, + { + path:'logretrieval', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/logRetrieval/LogRetrieval.tsx')), + key:uuidv4(), + }, + { + path:'auditlog', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/auditLog/AuditLog.tsx')), + key:uuidv4(), + }, + { + path:'assets', + component:

设计中

, + key:uuidv4() + }, + APP_MODE === 'pro' &&{ + path:'dashboard', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@dashboard/pages/Dashboard.tsx')), + key:uuidv4(), + children:[ + { + path:':partitionId/:dashboardType', + component:, + key:uuidv4(), + provider:DashboardProvider, + children:[ + { + path:'list', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@dashboard/pages/DashboardList.tsx')), + key:uuidv4() + }, + { + path:'detail/:dashboardDetailId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@dashboard/pages/DashboardDetail.tsx')), + key:uuidv4() + }, + ] + }, + ] + }, + { + path:'systemrunning', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@systemRunning/pages/SystemRunning.tsx')), + key:uuidv4() + }, + { + path:'template/:moduleId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + key:uuidv4() + }, + { + path:'logsettings/*', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/logsettings/LogSettings.tsx')), + key: uuidv4(), + children:[{ + path:'template/:moduleId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + key:uuidv4() + }] + + }, + APP_MODE ==='pro' && { + path:'resourcesettings/*', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/resourcesettings/ResourceSettings.tsx')), + key: uuidv4(), + children:[{ + path:'template/:moduleId', + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + key:uuidv4() + }] + + } + ] + }, +] + +const RenderRoutes = ()=> { + return ( + + + + {generateRoutes(PUBLIC_ROUTES)} + + + + ) +} + +const generateRoutes = (routerConfig: RouteConfig[]) => { + return routerConfig?.map((route: RouteConfig) => { + let routeElement; + if (route.lazy) { + const LazyComponent = route.lazy as React.ExoticComponent; + + routeElement = ( + }> + {route.provider ? ( + createElement(route.provider, {}, ) + ) : ( + + )} + + ); + } else { + routeElement = route.provider ? ( + createElement(route.provider, {}, route.component) + ) : ( + route.component + ); + } + + return ( + + {route.children && generateRoutes(route.children as RouteConfig[])} + + ); + } + ) +} + +// 保护的路由组件 +function ProtectedRoute() { + const {state} = useGlobalContext() + return state.isAuthenticated? : ; + } + +export default RenderRoutes \ No newline at end of file diff --git a/frontend/packages/businessEntry/src/main.tsx b/frontend/packages/businessEntry/src/main.tsx new file mode 100644 index 0000000..dd6dede --- /dev/null +++ b/frontend/packages/businessEntry/src/main.tsx @@ -0,0 +1,33 @@ +/* + * @Date: 2023-11-27 17:18:27 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-05-29 18:26:15 + * @FilePath: \frontend\packages\core\src\main.tsx + */ +import {StrictMode} from 'react' +import ReactDOM from 'react-dom/client' +import App from './App.tsx' +import '@core/index.css' +import {GlobalProvider} from "@common/contexts/GlobalStateContext.tsx"; + +async function initializeApp() { + try { + // 初始化行为 + // await fetchInitialConfig(); // 示例:获取初始配置 + + // 异步操作完成后,渲染React应用 + ReactDOM.createRoot(document.getElementById('root')!).render( + + + + + , + ); + } catch (error) { + console.error('Initialization failed:', error); + // 处理初始化失败的情况,比如渲染一个错误界面 + } +} + +// 执行初始化 +initializeApp(); \ No newline at end of file diff --git a/frontend/packages/businessEntry/src/vite-env.d.ts b/frontend/packages/businessEntry/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/frontend/packages/businessEntry/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/frontend/packages/businessEntry/start-vite.js b/frontend/packages/businessEntry/start-vite.js new file mode 100644 index 0000000..f55d1cb --- /dev/null +++ b/frontend/packages/businessEntry/start-vite.js @@ -0,0 +1,22 @@ +/* + * @Date: 2024-06-05 09:35:25 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:50:12 + * @FilePath: \frontend\packages\core\start-vite.js + */ +// start-vite.js// start-vite.js +import { exec } from 'child_process'; + +const viteProcess = exec('pnpm run build'); + +viteProcess.stdout.on('data', (data) => { + console.log(data.toString()); +}); + +viteProcess.stderr.on('data', (data) => { + console.error(data.toString()); +}); + +viteProcess.on('close', (code) => { + console.log(`Vite process exited with code ${code}`); +}); diff --git a/frontend/packages/businessEntry/tailwind.config.js b/frontend/packages/businessEntry/tailwind.config.js new file mode 100644 index 0000000..75a018c --- /dev/null +++ b/frontend/packages/businessEntry/tailwind.config.js @@ -0,0 +1,87 @@ +/* + * @Date: 2023-11-27 17:31:44 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:36:46 + * @FilePath: \frontend\packages\core\tailwind.config.js + */ +/** @type {import('tailwindcss').Config} */ + +export default { + important:true, + content: [ + `./index.html`, + `../*/src/**/*.{js,ts,jsx,tsx}`, + + ], + theme: { + extend: { + width: { + INPUT_NORMAL: '100%', + // INPUT_NORMAL: '346px', + INPUT_LARGE: '508px', + GROUP: '240px', + SEARCH: '276px', + LOG: '254px' + }, + minHeight:{ + TEXTAREA:'68px' + }, + borderRadius: { + DEFAULT: 'var(--border-radius)', + SEARCH_RADIUS: '50px' + }, + boxShadow:{ + SCROLL: '0 2px 2px #0000000d', + SCROLL_TOP:' 0 -2px 2px -2px var(--border-color)' + }, + colors: { + DISABLE_BG: 'var(--disabled-background-color)', + MAIN_TEXT: 'var(--text-color)', + MAIN_HOVER_TEXT: 'var(--text-hover-color)', + SECOND_TEXT:'var(--disabled-text-color)', + MAIN_BG: 'var(--background-color)', + MENU_BG:'var(--MENU-BG-COLOR)', + 'bar-theme': 'var(--bar-background-color)', + BORDER: 'var(--border-color)', + NAVBAR_BTN_BG: 'var(--item-active-background-color)', + MAIN_DISABLED_BG: 'var(--disabled-background-color)', + theme: 'var(--primary-color)', + DESC_TEXT: 'var(--TITLE_TEXT)', + HOVER_BG: 'var(--item-hover-background-color)', + guide_cluster: '#ee6760', + guide_upstream: '#f9a429', + guide_api: '#71d24d', + guide_publishApi: '#5884ff', + guide_final: '#915bf9', + table_text: 'var(--table-text-color)', + status_success:'#138913', + status_fail:"#ff3b30", + status_update:"#03a9f4", + status_pending:"#ffa500", + status_offline:"#8f8e93", + A_HOVER:'var(--button-primary-hover-background-color)' + }, + spacing: { + mbase: 'var(--FORM_SPAN)', + label: '12px', // 选择器和label之间的间距,待删 + btnbase: 'var(--LAYOUT_MARGIN)', // x方向的间距 + btnybase: 'var(--LAYOUT_MARGIN)', // y轴方向的间距 + btnrbase: '20px', // 页面最右侧边距20px + formtop: 'var(--FORM_SPAN)', + icon: '5px', + blockbase: '40px', + DEFAULT_BORDER_RADIUS: 'var(--border-radius)', + TREE_TITLE:'var(--small-padding) var(--LAYOUT_PADDING);' + }, + borderColor: { + 'color-base': 'var(--border-color)' + } + } + }, + plugins: [], + corePlugins: { + preflight: false, + }, + } + + \ No newline at end of file diff --git a/frontend/packages/businessEntry/tsconfig.json b/frontend/packages/businessEntry/tsconfig.json new file mode 100644 index 0000000..6784501 --- /dev/null +++ b/frontend/packages/businessEntry/tsconfig.json @@ -0,0 +1,39 @@ +/* + * @Date: 2024-06-04 08:54:17 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-07-12 13:54:42 + * @FilePath: \frontend\packages\core\tsconfig.json + */ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "paths": { + "@core/*": ["../core/src/*"], + "@common/*": ["../common/src/*"], + "@market/*": ["../market/src/*"], + "@dashboard/*": ["../dashboard/src/*"], + "@openApi/*": ["../openApi/src/*"], + "@systemRunning/*": ["../systemRunning/src/*"], + "@businessEntry/*": ["./src/*"], + }, + }, + "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../common/src/components/aoplatform/ScrollableSection.tsx", "../common/src/utils/postcat.tsx", "../common/src/utils/curl.ts", "../common/src/components/aoplatform/ResetPsw.tsx", "../common/src/components/aoplatform/SubscribeApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePageForHub.tsx", "src/components/aoplatform/RenderRoutes.tsx", "../common/src/components/aoplatform/PublishApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePage.tsx", "../common/src/const/type.ts", "../common/src/components/aoplatform/intelligent-plugin", "../common/src/const/domain"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/frontend/packages/businessEntry/tsconfig.node.json b/frontend/packages/businessEntry/tsconfig.node.json new file mode 100644 index 0000000..42872c5 --- /dev/null +++ b/frontend/packages/businessEntry/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/packages/businessEntry/vite.config.ts b/frontend/packages/businessEntry/vite.config.ts new file mode 100644 index 0000000..665400c --- /dev/null +++ b/frontend/packages/businessEntry/vite.config.ts @@ -0,0 +1,86 @@ +/* + * @Date: 2024-01-31 15:00:39 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-07-12 19:53:09 + * @FilePath: \frontend\packages\businessEntry\vite.config.ts + */ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import path from 'path' +import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'; +import tailwindcss from 'tailwindcss'; +import autoprefixer from 'autoprefixer'; + +export default defineConfig({ + cacheDir: './node_modules/.vite', + build:{ + outDir:'../../dist', + sourcemap: false, + chunkSizeWarningLimit: 50000, + cacheDir: './node_modules/.vite', + output: { + manualChunks(id) { + if (id.includes('node_modules')) { + return id.toString().split('node_modules/')[1].split('/')[0].toString(); + } + // 针对 pnpm 和 Monorepo 特殊处理 + if (id.includes('.pnpm')) { + const segments = id.split(path.sep); + const packageName = segments[segments.indexOf('.pnpm') + 1].split('@')[0]; + return packageName; + } + } + }, + }, + css: { + postcss: { + plugins: [ + tailwindcss(path.resolve(__dirname, '../common/tailwind.config.js')), + autoprefixer + ], + }, + preprocessorOptions: { + less: { + javascriptEnabled: true, + }, + }, + modules:{ + localsConvention:"camelCase", + generateScopedName:"[local]_[hash:base64:2]" + } + }, + plugins: [react(), + dynamicImportVars({ + include:["src"], + exclude:[], + warnOnError:false + }), + ], + resolve: { + alias: [ + { find: /^~/, replacement: '' }, + { find: '@common', replacement: path.resolve(__dirname, '../common/src') }, + { find: '@market', replacement: path.resolve(__dirname, '../market/src') }, + { find: '@core', replacement: path.resolve(__dirname, '../core/src') }, + { find: '@dashboard', replacement: path.resolve(__dirname, '../dashboard/src') }, + { find: '@openApi', replacement: path.resolve(__dirname, '../openApi/src') }, + { find: '@systemRunning', replacement: path.resolve(__dirname, '../systemRunning/src') }, + { find: '@businessEntry', replacement: path.resolve(__dirname, './src') }, + ] + }, + server: { + proxy: { + '/api/v1': { + // target: 'http://uat.apikit.com:11204/mockApi/aoplatform/', + target: 'http://172.18.166.219:8288/', + changeOrigin: true, + }, + '/api2/v1': { + // target: 'http://uat.apikit.com:11204/mockApi/aoplatform/', + target: 'http://172.18.166.219:8288/', + changeOrigin: true, + } + } + }, + logLevel:'info' +}) diff --git a/frontend/packages/common/package.json b/frontend/packages/common/package.json index 1fef57d..619c752 100644 --- a/frontend/packages/common/package.json +++ b/frontend/packages/common/package.json @@ -15,7 +15,6 @@ "@mui/x-data-grid-pro": "6.18.1", "allotment": "^1.20.0", "echarts": "^5.5.0", - "echarts-for-react": "^3.0.2", "mockjs": "^1.1.0", "rc-picker": "^4.1.1", "react-dropzone": "^14.2.3", diff --git a/frontend/packages/common/src/assets/logo.png b/frontend/packages/common/src/assets/logo.png index e716b6b0b6c3e42cc58c1fb7e1e5ae0ff62489d1..a6895b8c91e3298fbc5109cb835fece6b48dabf9 100644 GIT binary patch literal 4240 zcmV;B5O42^P)m@)ECBDf#Gjz&FBBF5<0R;*aP6pYTsPPPwY7(4Krhc3Yh zuYE6uMuw((IQukizNfqJzCprNCk_X26BAAqCI|#DcIIOS2&V|qDI#(wfXe_pzZb^S zMjI_bkT7weQz(LdX50>7pc2auz@i^0aWZ3T#PoJ!#HxUI0N5RP4{fyZl0cAnlp+dR zBF2@(7$71r0Z}ZF1Y&^Fzl8MfX(0S@W4A--h-O(aZtOH|v{46wgeji*#g{qEbS7It z;&CBLKgWOLZHb^I>*x|9{A$&51ui0EShL}?R-{_@#M)>h2d#ATjy48;OyeReLJ%Xd z@KgoBZZrBFm|r3KGl;w==t>HK!N$P{5Mf$9hqtl+;A8-20C-Wq+gY{^z$aUI(J)~m z3fX-QNJ@#YSW_kOpZFXaI0?kAhIIpp1!Q9H?@R+Mhv44eyRkP!Gayo~=g>CxAG`&K zLk6SYNy)93kT8W=ra^$pqVbD>z$y1_2ttX4lGJjkzzLy`g#Jh%j{*qi;_Jh~0R92M zYclJ93}6v}vB2|P2jIO`ds`d!M_vQq{{Va&z+(ljcPfC-0C0I*d(58$_-D`l?*#Bs z0MiSMXFGtW0jve^UjQD_-(g=0L^<=$MtRr0-Rk;Y>! zj%DhtBD4gMzYD#gI$<^0NuK916To=@ZVNnLuXR}q?)xhM1^}D|paNi%YS7zsV*6l) zXaO)GnPw+@PtN{UhzBzXq_b;5|(>e1dOUebFFWBbkU_NrSv) zW5oE@IO&iuc;lZjPC}?~#m6NUkeIO)z^ht!>s8nZ`L-OzGDGS5P_1U_(B$^kJ9N^2 z3W!q*3v%`q6+9Q^8WYC1|70M2CcT;iydS_Zf#>+8LXa@^&1B5#Vaz-rSthMmAS{a* z>#V?7s}pI=MC1t31a?p3r$o4pX2Jz~A+h`>04LVi{#pRP-QqF$U<2rz0UR&|*Y?3$ zt2+Q3G}QxnsUk?2jySXvhaJ+1SG}?W3lHwVoZd*wg>nyB%ZyK1L5Un{JaViRXDD@! z+;wyj5gn5VSg~bH1`CENF{S}H-Rg-N`&f7F_nT11Sl0OHM*x1}ESqZ_V+HD*7S&K% zRk#trs?2z5RiXSEfU8?Dmi+=jT7Rr8C?~acu@KFh%U~9ajsaVD7?d*35G6s@-!sX1 zLO3?1#3i;$lEh4uQso4x#!nhc0WXKa<&fAyjZ8K^q6i1gIU6r*`43Pr&+HWd&MvUu zA^=ALc&f-rbMSKj*8_MW^W6KD_*kl?S6TcifX@RMZQ$BISmFLGfPYu_GKF<*j|A|p z9EzrC*wgibcNpLf5!^G`c!)|kc<#Aazh!w5VX`~?4uE+DZuJ$KyJ$q1M)dgad$!#N z;J=koJS?-#em_JlS~FoE`ZECj*R$;r0AE*T@XeWRC0+ML&vA!qj5(lg;XI8=OX@BR zs}Md7V7bPHd9becwdy@Ug>j849V<+KsMk75zt<~F*Qp1?VuJ26Fm3mVyy~y zR+ubanfY#?<&^*yt1Fm?>1qWQDua3|fcH7cRTp#ALb|Y)?F60tXE_$N-qQH1RVcI1 zVMqnpr}%Qw6kj|gA`X~N=!hu(o+&LV6XT=I*d8g97dd1@M4oaZ-HwEecr_E27A<8e zh~qqYCFlh5S-}ByDO!nDIqMH>@pbd?g5y%TaIJZVYWELJB1l>EXxibXob6?gYj2;! zGL0i$*EE!=gbLDi9zoioG4dUu`NgINw$|O7F`cnsUJ27WDa-af%}mSE9Fr?Jq(nr@ z^eOp}6vr~9`KJ$gG-AE5KjcN8`xkXzuJzE&cHiGqs<>6i<3|r};Wa0NZ=$;6v6KF5 z9^%62WE|BcZ(=Uav3@@E<)jP3GN6d((uXs7I;b1^F#ul;JYS5avqXt85zL;&=qODT zC<4C7L{Bhf@=G+%;PHgK)C7yuPlS(Hd27NjU!$%<7WZht`HW`&v#_q-5ly&$9`ZE% ziWXk87UpSyo`oAb+F$qq0H4tByVPZUzdq+4T@Fz!nhru$vO9oR~(d!ji2hcdXNdWNz~LEF}UO#f2Vi zW-?U=zUm877o*-b-dgU+d;q8AY#XfedXu46RX|Az8XtVF-_6Pnp0AeX7F9~AWm>Op z-S;xb*=Krm;JB^(c>#b!RViLn;26^T`Mf7~weI8%YOU%nn`)Ub83XjrWOR3BtP|nB zh;cV*?kUQ)W$1dJ3&@OaCR|SmeOoWAwmsLg{t0E&QhYOq7CkqhR49v72ur#|8k8TQ zF~=J`$L!RxwE`v2csi6pyaK=<=P5c2_k7QYCu>CiEs38G&vUw)B)X$q2WqwZLF1Iw($skTOe<< z-{V|U+=~GiP3Tqy%UUT(D8o2ACDaL)i(zmVC3%M`X!1z3H^(Y%S5tqqQ-^2NDhzqF z*;VQ;gjBWnD4iREZR$R?qNjv48NDd*IN!u0P3Btn`S>P{&jdn&KMdpspS|Z#wLb!0Y%+F%{@7v zIcc9wPM~cY@p~f-9VU=VC8=r-!Qvd6IntoC?6|(-WbU&#Phv?4S%svBo<`=M7LH%&PZ#| zx~Ex-!!Q*=*5jjnmPG*Q2p2WIU z>@T7RS3qDbI~r#&lIn=Kdlxj@7`aF!4$g~Yz!x={);>nh*{lh_N^91>qKwz3CY`rl zJP+V;0C#HBVqO94i8+<+H>mIpIV#R*3|KU;l*O(lHH?mAlC{&6i9Ei6YKqXd^~Aq6 zsg)pt$rh&?z$s|Gypj~(eNtaCX|>londoCeGQ%Yt#BCUKyKt)sT+zlty-w2Zei9%@ z>5o1c0kJeEXHqZh5Af~)VcM*HN-LZuJyIdsru6YhBR^&!%1WZ#oe_q0DmZ0LV%CaJ zqMVBRAF8z)_H1k9{)bTOk(5^`>*0No^UHBk~DLE^GJmTC+8gcq+=pJF8yR?G**RS{KTiX!iu ziH=dNlNGgLoybKn%hUFKvgSHg7dU=M6Ty!ayk4tet;CZ69%}GBK1Op_&idm#g}i$U zJCq=KSgrnVDKqQh0#z>Gs^6dGVLK5%M}+g4a0U_1VZsee z^du8T(ptQT+)i8?PwWzn_c={W@=i~-CEIrot?>m;OEd%TqN3FI{DRA0dM3zh&8-xE zgdxv+FQC!!RC1J&6`Bt!RsM1`eztoPyXCwMZa*X(*FhrX=2oQE|3G*!qd zj(^N489PeH9*i(y0#=P%C7ReF>#g9XHAFa11h>{WZG{Lo65&E3Y;-LU(|C2cyN*!3 z-cO0~6LN&GM0*rR{H~`u+^CjX6L9x&?Pa`jRf3XVxXfS%|V3Q<2;sAHJ-YA@#dF8ZeSrsuEVN`PVT4vdY$VW9K$cne4e5+gdX7yjo;E1`i%KP?!zFn&ccjq8X;^OW=4=r6~aR#@e4Yh zYQQfZB*x_o+%2Fb1bH(9FB4!3$N3BTl87va*)yqGie{i}COosX4YZl(VO4=2^v5AD z;-~|g1L@nJ>C$Q#Eg}1XQ!1Hd%zmyGelo1rr5-#Rs4!PHL$Of%A4Ip&Msv{qpSEqZ m(Im8msf{+8gkJ;z0RR8;YC*;~!6lUd0000|YLrgFKai-5P*^mQjvpjO zBFskgL1FIok9%k4&CI)R=Dm44JC*q*FS&C+&z-sFoqK=x+&d(tM7Ox~ynmk~gv?X~ zJ}U%P2`S$d0P(sS1Qee$fFWYY|KwkzJU{MjuGBM*~Vw}Q6Ux&X2*eU304AIW;8pI%at6XSIW0z<90++nv8F+rIl1|XEu2?7YT>4MeeyARLVPe;;=fUsyJ1z_5cyvmWY zrI7U=La-mHq@N;yKLD6<<%DbS<6e4n6zjlw%9`WAT^ls)e(w-sDg;LGRx-yERm>cCP6}~ zupmfsF?uAyEo20?B-YH|TX<>3k#0NF0k(CRFJ{rms3T`*B5Jn);IK#hnNU;Cn4z2v zrP%3+;${FMsut|4vE5b~i=t6$Sy43DioL z4-sJsz=aX@$q#D_xan31!!p#%rX#jc%aia(DrECk!Idus;4%QQY~EVeuHH6n zj>7+?vbQT`0svyVg(0s6aH@$em(UEk(1GfMnxYL4pFMxYp%+&?+^sw&==Db|K#_z+ zBeAeFc@Q{qcCVg-dQC5Fi$>y(oGmW2942J*Rw0vgHURM4=!6>B#pcLN(y^gt1DnzQ zyB`HGnMpc10Aty_Rrbl7fO#rj&;x(6gEl*Yei2N=`(*+E>1^IAhh8&Pad+M-Gto|O z5~9@swnj#{DRULRJ+WqfdAIWTz+{z5P;W*r^m6T#^GUONB!dz9jbAb(+szS~q_Yjc zQK;`Q7NDsV6a^m-P{!TvG?Wz$(xzX1aj2JwZOD?&=B*si1p(m(G45x^Z>v6fRlruG*+aQh_zWg&k3ybiw4uW%V4lv6_KGHNV*z8mkf8&V4Dn~WKj>-LB*MQ0Y$*CY zX!)(^j9}^rK@lnDT`dFvS_+TT32 zYn}3;(bJq7p5;WiJt~<1KvT;pLvqfMvt?}+3WhvA@rY>S^-$=A3>_eDh;Lykvw3R_ zjq9i)fH45;vU!WD4}c9YPqQxzE2u^p>bolhDWol;-x?{W``3W32?#fsu|tBsz>p^a zig;+D%Nu<6>P#P))Nx(H6&J3ZAAa)43e#dYC{jLYcQl0)9(kgs$xRqt;QG6Qp1Roq zi>0B~FKIW+=0-Me&18~J8Q$bZB4B$}l>FNCgI1(NFuyo**}Ub+u102=0N}32tbZ`! z+ivSbo|dY0E!E^5F*SVld{l~VvMe+1b&6J&k|FPcS|@FljBPk_wy==xw}T#FCh8tA zy!o?vtC-DOtJ)3fFoWI)WdOrn)EP>VfQT&<05D@xg1*dL2c)LQJD|&zg<1>3 z764P-$fD_R+mL*RAibW4+;Y0*f+Bi@FZ%A|bC&V+0;2yAV6yik?THl&w38MwOs zxKBM%VWLaV_P8Ow=%+|PlQK<>Ragilg^*VZiFHC?r4ab15b}kJzz=ubx8(75lHB>I z_4bxaom)Y4uOta3=*?TGja!#>YIB(IrVH23KltR4760n^YiNb(ZC^6H?Q>96uI-W5 zjVD41;fV|{rH>kMnD>y{!6;uQ>BOMEw^8(t-p?&iy={MonljzFU7SXQ9}!`g8ax$n zG7(lYW8m@0@JtAs{3Aug_3c{saEKeqZJpi_Z>AAK9 zaYJ&+qLFb!S{dFye9EGcu};q$MTFd9Px0EI2m@=Uy$^cr2wP~g+1m{!Gf8L0ul^wb zxci&pgG6|Sfzy>|0!BLioAlb_!!gZLi$$zhQ zQdjx!U3byi`F+1SvZ5HG^M0;F34~kRZUZnLqFfl{967ttZbaRn2(>mTHz#Nhg#R~> zavQ2o8%!Da-W_6y2oE#k^v2^6njCQL3u)5e1I%<_clwy|U>`Gmx|xLNKzd+bou!ge`NlW zU%s&7i2$8W1;`r&F^fi0j-1U!TyIf7kM@9q4}%i4d{EA)Wm87I*%>n=k7e`LUPHO= z@9B;fWq42br!z^%b2>RhgliZC0loJF07MY_0+gC}Hvks(fi8(A#?!}^3xV(5{J_$A z0QlCXx7RY!U6SOw+BC0)gs8_=!=8kMyM2;r06~;#A*t-m2)@Y8!TX3qvBzsL6N-T6 z6>Oyt%$RLz!=y-kh%{6`yezB@!*p+m2p{lROKA zpG(3%CcFxwcO}VHOt=U{!;&OxYgQu|Oos`Z>2iIT@U#G5hRM^r=*Zc1omQe9T#v$A zF}Gsj&lnxAC>!DvnWU3y_Gfb)m*@*L$(IK396Frt4H4lr0Pj~;i9mX~2j~Hf*1PZA z!~qyN3GCjJTl!az2EViI^0(G7=ynPDIo3P1rUQgNckjK?$rqvN@R%Vv(0+|0XUi6i z%)op7wHP${ae-{!Dr)y2+aq~8lXSMC?z5LbA3O18^HwR7bSBW@bdQPf8~2p1%G$YE zy_$0>HQY2*A;#ui_bo|}-|wkN0D!%ZEPIIwmoQ)&yxL}2(+6P{!WzW>8aH!$OQ(&wBS4ilR0-ebJTL=SdQy&r>@ z3o5G%ChHXI^Q*WP8^h>)|0oSbyZ0sZ{T8NiU_)8izdmuUo3;k%59p~-+!YmO z538@y@@HqcUGh9Bu~AB#D+E?bDPI>7&kBKuGPm*XqH6f-qt1{JxUwR!NeKA~A+WL{ v
diff --git a/frontend/packages/common/src/components/aoplatform/Navigation.tsx b/frontend/packages/common/src/components/aoplatform/Navigation.tsx index 4fa8f96..e7c952f 100644 --- a/frontend/packages/common/src/components/aoplatform/Navigation.tsx +++ b/frontend/packages/common/src/components/aoplatform/Navigation.tsx @@ -17,6 +17,7 @@ export type MenuItem = Required['items'][number]; // access:string [], // children: NavigationItemType[] // } +const APP_MODE = import.meta.env.VITE_APP_MODE; const routerKeyMap = new Map([ ['assets','/assets'], @@ -35,13 +36,14 @@ const routerKeyMap = new Map([ ['logsettings','/logsettings'], ['resourcesettings','/resourcesettings']]) + const TOTAL_MENU_ITEMS: MenuProps['items'] = [ - getItem('仪表盘', 'mainPage', ,[ + APP_MODE === 'pro' ? getItem('仪表盘', 'mainPage', ,[ // getItem(资产视图, 'assets',null,undefined,undefined,''), getItem(运行视图, 'dashboard',null,undefined,undefined,''), getItem(系统拓扑图, 'systemrunning',null,undefined,undefined,''), // getItem((审批), 'approval', null), - ]), + ]):null, getItem('数据服务资产', 'dataAssets',, [ getItem(内部数据服务, 'system',null,undefined,undefined,''), @@ -60,9 +62,9 @@ const TOTAL_MENU_ITEMS: MenuProps['items'] = [ getItem('运维与集成', 'maintenanceCenter', , [ getItem(部署管理, 'partition',null,undefined,undefined,'system.partition.self.view'), getItem(日志配置, 'logsettings',null,undefined,undefined,'system.partition.self.view'), - getItem(资源配置, 'resourcesettings',null,undefined,undefined,'system.partition.self.view'), + APP_MODE === 'pro' ? getItem(资源配置, 'resourcesettings',null,undefined,undefined,'system.partition.self.view'):null, // getItem(邮箱设置, 'email'), - getItem(Open API, 'openapi',null,undefined,undefined,'system.openapi.self.view'), + APP_MODE === 'pro' ? getItem(Open API, 'openapi',null,undefined,undefined,'system.openapi.self.view'):null, // getItem(Webhook, 'webhook'), // getItem(HTTP 日志配置, 'httplog'), // getItem(日志检索, 'logretrieval',null,undefined,undefined,'system.logRetrieval.self.view'), @@ -126,10 +128,9 @@ const Navigation: FC = () => { const menuData = useMemo(()=>{ const filterMenu = (menu:Array<{[k:string]:unknown}>)=>{ - return menu.filter(x=>x.access ? checkPermission(x.access as keyof typeof PERMISSION_DEFINITION[0]): true) + return menu.filter(x=> x && (x.access ? checkPermission(x.access as keyof typeof PERMISSION_DEFINITION[0]): true)) } - - return TOTAL_MENU_ITEMS!.map((x)=> ( x.children ? {...x, children:filterMenu(x.children)} : x))?.filter(x=> x.key === 'system' || (x.children && x.children?.length > 0)) + return TOTAL_MENU_ITEMS!.filter(x=>x).map((x)=> ( x.children ? {...x, children:filterMenu(x.children)} : x))?.filter(x=> x.key === 'system' || (x.children && x.children?.length > 0)) },[accessData]) useEffect(() => { diff --git a/frontend/packages/common/src/components/aoplatform/PublishApprovalModalContent.tsx b/frontend/packages/common/src/components/aoplatform/PublishApprovalModalContent.tsx index 3d7a856..99d65ad 100644 --- a/frontend/packages/common/src/components/aoplatform/PublishApprovalModalContent.tsx +++ b/frontend/packages/common/src/components/aoplatform/PublishApprovalModalContent.tsx @@ -57,7 +57,7 @@ const apiColumns = [ const upstreamColumns = [ { - title:'分区', + title:'环境', dataIndex:['partition','name'], copyable: true, ellipsis:true diff --git a/frontend/packages/common/src/components/aoplatform/SubscribeApprovalModalContent.tsx b/frontend/packages/common/src/components/aoplatform/SubscribeApprovalModalContent.tsx index e100060..68cca34 100644 --- a/frontend/packages/common/src/components/aoplatform/SubscribeApprovalModalContent.tsx +++ b/frontend/packages/common/src/components/aoplatform/SubscribeApprovalModalContent.tsx @@ -112,7 +112,7 @@ export const SubscribeApprovalModalContent = forwardRef - label="申请的分区" + label="申请的环境" name="partition" rules={[{ required: true, message: '必填项' }]} > diff --git a/frontend/packages/common/src/components/aoplatform/TreeWithMore.tsx b/frontend/packages/common/src/components/aoplatform/TreeWithMore.tsx index b5604b5..971c8a5 100644 --- a/frontend/packages/common/src/components/aoplatform/TreeWithMore.tsx +++ b/frontend/packages/common/src/components/aoplatform/TreeWithMore.tsx @@ -17,9 +17,10 @@ export type TreeWithMoreProp = { editKey?:string entity?:{id:string,[k:string]:unknown | string} onBlur?:()=>void + stopClick?:boolean } -const TreeWithMore = ({children,dropdownMenu,editable,editingId,entity,editKey='name',afterEdit,onBlur}:TreeWithMoreProp)=>{ +const TreeWithMore = ({children,dropdownMenu,editable,editingId,entity,editKey='name',afterEdit,onBlur,stopClick=true}:TreeWithMoreProp)=>{ const [editValue, setEditValue] = useState(entity?.[editKey] as string) const [submitting, setSubmitting] = useState(false) const inputRef = useRef(null) @@ -34,12 +35,12 @@ const TreeWithMore = ({children,dropdownMenu,editable,editingId,entity,editKey=' return (<> { - editable && editingId && entity?.id && editingId === entity.id ? {setEditValue(e.target.value)}} onBlur={()=>{onBlur?.()}} onClick={(e)=>e?.stopPropagation()} onPressEnter={()=>{handleSubmit(editValue)}} suffix={submitting ? :{handleSubmit(editValue)}}/>} />: + editable && editingId && entity?.id && editingId === entity.id ? {setEditValue(e.target.value)}} onBlur={()=>{onBlur?.()}} onClick={(e)=>stopClick&&e?.stopPropagation()} onPressEnter={()=>{handleSubmit(editValue)}} suffix={submitting ? :{handleSubmit(editValue)}}/>} />:
{children} - { e.stopPropagation();}}> + { stopClick && e.stopPropagation();}}> - { e.stopPropagation();}} /> + { stopClick && e.stopPropagation(); }} />
diff --git a/frontend/packages/common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx b/frontend/packages/common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx index e26ca9a..be6f968 100644 --- a/frontend/packages/common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx +++ b/frontend/packages/common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx @@ -76,7 +76,7 @@ export default function IntelligentPluginList(){ const { modal,message } = App.useApp() const [searchWord, setSearchWord] = useState('') const { moduleId } = useParams(); - const [pluginName,setPluginName] = useState() + const [pluginName,setPluginName] = useState('-') const [partitionOptions, setPartitionOption] = useState([]) const { setBreadcrumb } = useBreadcrumb() // const [confirmLoading, setConfirmLoading] = useState(false); @@ -373,7 +373,7 @@ export default function IntelligentPluginList(){ }) } - // 渲染配置页时需要用到分区数据,在此合并数据 + // 渲染配置页时需要用到环境数据,在此合并数据 const getFinalRender = ()=>{ Promise.all([getRender(),getPartitionList()]).then(([render, partitions])=>{ if(!partitions || partitions.length === 0) return @@ -414,7 +414,7 @@ export default function IntelligentPluginList(){ mode="multiple" allowClear style={{ width: '100%' }} - placeholder="所有分区" + placeholder="所有环境" value={partition} onChange={handleClusterChange} options={partitionOptions} @@ -427,7 +427,7 @@ export default function IntelligentPluginList(){ onSearchWordChange={(e)=>{setSearchWord(e.target.value);setTableHttpReload(true);setTableHttpReload(true)}} /> - {setCurDetail(undefined);setDrawerOpen(false)}} onSubmit={()=>drawerFormRef.current?.save()?.then((res)=>{res && manualReloadTable();return res})} submitAccess='system.partition.self.edit'> + {setCurDetail(undefined);setDrawerOpen(false)}} onSubmit={()=>drawerFormRef.current?.save()?.then((res)=>{res && manualReloadTable();return res})} submitAccess='system.partition.self.edit'> } spinning={drawerLoading}> (false) const apiColumns = [ { - title:'分区', + title:'环境', dataIndex:'title', copyable: true, ellipsis:true @@ -54,7 +54,7 @@ export const IntelligentPluginPublish = forwardRefsetBody($body);\r\n\r\n' + `$request->getBody()->${langTmp.paramsStr}\r\n\r\n` + '$request->setHeaders(array(\r\n' + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + ' "Content-Type":"multipart/form-data"\r\n' + '));\r\n\r\n' + '$client->enqueue($request)->send();\r\n' + @@ -548,7 +554,7 @@ export function generateCode( '$request->setBody($body);\r\n\r\n' + `${langTmp.queryStr ? `${langTmp.queryStr}\r\n\r\n` : ''}` + '$request->setHeaders(array(\r\n' + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + '));\r\n\r\n' + '$client->enqueue($request)->send();\r\n' + '$response = $client->getResponse();\r\n\r\n' + @@ -610,7 +616,7 @@ export function generateCode( ` CURLOPT_CUSTOMREQUEST => "${method}",\r\n` + ` CURLOPT_POSTFIELDS => ${langTmp.paramsStr},\r\n` + ' CURLOPT_HTTPHEADER => array(\r\n' + - `${langTmp.headerStr},\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr},\r\n` : ''}` + ' "Content-Type:multipart/form-data"' + '\r\n ),\r\n' + '));\r\n\r\n' + @@ -843,7 +849,7 @@ export function generateCode( `request = Net::HTTP::${method.toLowerCase().replace(/^\S/, (s: string) => { return s?.toUpperCase() })}.new(url)\r\n` + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + `request.body = ${langTmp.paramsStr}\r\n\r\n` + 'response = http.request(request)\r\n' + 'puts response.read_body' @@ -1020,7 +1026,7 @@ export function generateCode( ' if err != nil {\r\n' + ' return nil, err\r\n' + ' }\r\n' + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + ' req.Header.Add("Content-Type", writer.FormDataContentType())\r\n\r\n' + ' client := &http.Client{}\r\n' + ' resp, err := client.Do(req)\r\n' + @@ -1112,7 +1118,7 @@ export function generateCode( map: stringifyHeaders }) let mediaType = 'application/octet-stream' - switch (requestType || 'FORMDATA') { + switch ( (requestType || 'FORMDATA').toUpperCase()) { case 'FORMDATA': { if (multipart) { mediaType = 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' @@ -1158,10 +1164,10 @@ export function generateCode( `RequestBody fileBody = RequestBody.create(MediaType.parse("${langTmp.fileType}"), file); \r\n\r\n` + 'MultipartBody.Builder builder = new MultipartBody.Builder()\r\n' + ' .setType(MultipartBody.FORM)\r\n' + - `${langTmp.paramsStr} \r\n` + + `${langTmp.paramsStr ? `${langTmp.paramsStr}\r\n` : ''}` + 'Request request = new Request.Builder()\r\n' + ` .url("${urlObj.href}")\r\n` + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + ' .post(builder.build())\r\n' + ' .build();\r\n\r\n' + 'Response response = client.newCall(request).execute();\r\n' + @@ -1179,7 +1185,7 @@ export function generateCode( 'Request request = new Request.Builder()\r\n' + ` .url("${urlObj.href}")\r\n` + ` .method("${method}",${method === 'GET' ? 'null' : 'body'})\r\n` + - `${langTmp.headerStr}\r\n` + + `${langTmp.headerStr ? `${langTmp.headerStr}\r\n` : ''}` + ' .build();\r\n\r\n' + 'Response response = client.newCall(request).execute();\r\n' + 'System.out.println(response.body().string());\r\n' diff --git a/frontend/packages/common/src/components/apispace/code-snippet/index.tsx b/frontend/packages/common/src/components/apispace/code-snippet/index.tsx index 008171d..2a043ca 100644 --- a/frontend/packages/common/src/components/apispace/code-snippet/index.tsx +++ b/frontend/packages/common/src/components/apispace/code-snippet/index.tsx @@ -88,10 +88,10 @@ type CodeSnippetCompoType = { }) result.params = [] - + console.log('检查请求参数类型',result.requestParams?.bodyParams?.[0]?.contentType) //为请求参数 中的header、reset、body、query 添加 value 和 valueQuery 的值 switch (result.requestParams?.bodyParams?.[0]?.contentType) { - case 'FORMDATA': { + case 0: { result.requestParams?.bodyParams?.forEach((body: unknown, key: unknown) => { if ((body.checkbox || !body.hasOwnProperty('checkbox')) && body.name) { if (paramsJsonType[body.dataType] == 'string' && body.paramAttr.example) { @@ -119,11 +119,11 @@ type CodeSnippetCompoType = { } break } - case 'RAW': { + case 1: { result.params = apiDoc.requestParams?.bodyParams break } - case 'JSON': { + case 2: { result.params = apiDoc.requestParams?.bodyParams if (!alreadyHadContentType) { result.headers.push({ @@ -134,7 +134,7 @@ type CodeSnippetCompoType = { } break } - case 'XML': { + case 3: { result.params = apiDoc.requestParams?.bodyParams if (!alreadyHadContentType) { result.headers.push({ @@ -146,7 +146,8 @@ type CodeSnippetCompoType = { break } } - + + result.requestType = result.requestParams?.bodyParams?.[0]?.contentType || 0 return result } @@ -160,6 +161,7 @@ type CodeSnippetCompoType = { setCode(tempCode) return } + console.log(cloneDeep(api)) tempCode = generateCode( language.toString(), isMultipart, diff --git a/frontend/packages/common/src/const/approval/const.tsx b/frontend/packages/common/src/const/approval/const.tsx index d976c60..9e0ba33 100644 --- a/frontend/packages/common/src/const/approval/const.tsx +++ b/frontend/packages/common/src/const/approval/const.tsx @@ -10,7 +10,7 @@ export const SUBSCRIBE_APPROVAL_TABLE_COLUMN : ProColumns title: '申请时间', dataIndex: 'applyTime', ellipsis:true, - width:176, + width:182, fixed:'left', sorter: (a,b)=> { return a.applyTime.localeCompare(b.applyTime) @@ -62,7 +62,7 @@ export const SUBSCRIBE_APPROVAL_TABLE_COLUMN : ProColumns dataIndex: 'approvalTime', ellipsis: true, // sorter: true,, - width:176, + width:182, sorter: (a,b)=> { return a.approvalTime.localeCompare(b.approvalTime) }, @@ -76,7 +76,7 @@ export const SUBSCRIBE_APPROVAL_INNER_TODO_TABLE_COLUMN : ProColumns { return a.applyTime.localeCompare(b.applyTime) @@ -114,7 +114,7 @@ export const SUBSCRIBE_APPROVAL_INNER_DONE_TABLE_COLUMN : ProColumns { return a.applyTime.localeCompare(b.applyTime) @@ -169,7 +169,7 @@ export const SUBSCRIBE_APPROVAL_INNER_DONE_TABLE_COLUMN : ProColumns { return a.approvalTime.localeCompare(b.approvalTime) }, @@ -290,7 +290,7 @@ export const PUBLISH_APPROVAL_RECORD_INNER_TABLE_COLUMN : ProColumns[] dataIndex: 'applyTime', copyable: true, ellipsis:true, - width:176, + width:182, fixed:'left', sorter: (a,b)=> { return a.applyTime.localeCompare(b.applyTime) @@ -414,7 +414,7 @@ export const PUBLISH_APPROVAL_TABLE_COLUMN : ProColumns[] // sorter: true, ellipsis:true, hideInSearch: true, - width:176, + width:182, sorter: (a,b)=> { return a.approvalTime.localeCompare(b.approvalTime) }, diff --git a/frontend/packages/common/src/const/const.ts b/frontend/packages/common/src/const/const.ts index b4ceff6..50d77c6 100644 --- a/frontend/packages/common/src/const/const.ts +++ b/frontend/packages/common/src/const/const.ts @@ -20,4 +20,4 @@ export const STATUS_CODE = { export const STATUS_COLOR = { 'done':'text-[#03a9f4]', 'error':'text-[#ff3b30]' -} \ No newline at end of file +} diff --git a/frontend/packages/common/src/const/permissions.ts b/frontend/packages/common/src/const/permissions.ts index c5c03e8..cdbb690 100644 --- a/frontend/packages/common/src/const/permissions.ts +++ b/frontend/packages/common/src/const/permissions.ts @@ -19,6 +19,11 @@ export const PERMISSION_DEFINITION = [ "anyOf": [{ "backend": ["system.user_manager"] }] } }, + "system.member.member.remove": { + "granted": { + "anyOf": [{ "backend": ["system.user_manager"] }] + } + }, "system.member.member.delete": { "granted": { "anyOf": [{ "backend": ["system.user_manager"] }] diff --git a/frontend/packages/common/src/const/type.ts b/frontend/packages/common/src/const/type.ts index ef809b2..c1971df 100644 --- a/frontend/packages/common/src/const/type.ts +++ b/frontend/packages/common/src/const/type.ts @@ -99,3 +99,13 @@ export type DynamicMenuItem = { } export type AccessDataType = keyof typeof PERMISSION_DEFINITION[0] + + + +export type SimpleMemberItem = { + id:string + name:string + email:string + department:string + avatar:string +} \ No newline at end of file diff --git a/frontend/packages/common/src/contexts/GlobalStateContext.tsx b/frontend/packages/common/src/contexts/GlobalStateContext.tsx index 5d53535..1680f62 100644 --- a/frontend/packages/common/src/contexts/GlobalStateContext.tsx +++ b/frontend/packages/common/src/contexts/GlobalStateContext.tsx @@ -105,7 +105,7 @@ export const GlobalProvider: FC<{children:ReactNode}> = ({ children }) => { userData: null, version: '1.0.0', updateDate: '2024-07-01', - powered:'Powered by https://eolink.com', + powered:'Powered by https://apipark.com', mainPage:'/system/list' }); const [accessData,setAccessData] = useState>(new Map()) diff --git a/frontend/packages/common/src/utils/dataTransfer.ts b/frontend/packages/common/src/utils/dataTransfer.ts index c05f438..59f966d 100644 --- a/frontend/packages/common/src/utils/dataTransfer.ts +++ b/frontend/packages/common/src/utils/dataTransfer.ts @@ -1,11 +1,12 @@ /* * @Date: 2024-03-06 16:58:39 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 10:30:55 + * @LastEditTime: 2024-07-12 09:54:18 * @FilePath: \frontend\packages\common\src\utils\dataTransfer.ts */ import { ColumnFilterItem } from 'antd/es/table/interface' import {DepartmentListItem} from '@core/const/member/type' +import { RcFile } from 'antd/es/upload'; export const handleDepartmentListToFilter:(departmentList:DepartmentListItem[])=>ColumnFilterItem[] = (departmentList:DepartmentListItem[])=>{ return departmentList?.map((x:DepartmentListItem)=>( @@ -21,4 +22,9 @@ export const getImgBase64 = (img: RcFile, callback: (url: string) => void) => { const reader = new FileReader(); reader.addEventListener('load', () => callback(reader.result as string)); reader.readAsDataURL(img); -}; \ No newline at end of file +}; + + +export const frontendTimeSorter = (a:{[k:string]:string},b: { [k: string]: string }, field:string) =>{ + return (new Date((a)[field])).getTime() - (new Date((b)[field])).getTime() +} \ No newline at end of file diff --git a/frontend/packages/common/src/utils/permission.ts b/frontend/packages/common/src/utils/permission.ts index 8c792ab..195ba24 100644 --- a/frontend/packages/common/src/utils/permission.ts +++ b/frontend/packages/common/src/utils/permission.ts @@ -1,7 +1,7 @@ /* * @Date: 2024-03-11 15:12:43 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 11:22:49 + * @LastEditTime: 2024-07-29 16:27:56 * @FilePath: \frontend\packages\common\src\utils\permission.ts */ import { PERMISSION_DEFINITION } from "@common/const/permissions" @@ -9,6 +9,8 @@ import { AccessDataType } from "@common/const/type" export const checkAccess:(access:AccessDataType, accessData:Map)=>boolean = (access, accessData)=>{ + // TODO 暂时隐藏权限 + return true if(!access){ return true } diff --git a/frontend/packages/core/.env b/frontend/packages/core/.env new file mode 100644 index 0000000..de1f4be --- /dev/null +++ b/frontend/packages/core/.env @@ -0,0 +1 @@ +VITE_APP_MODE=openSource \ No newline at end of file diff --git a/frontend/packages/core/package.json b/frontend/packages/core/package.json index 8008369..25f04f2 100644 --- a/frontend/packages/core/package.json +++ b/frontend/packages/core/package.json @@ -4,8 +4,10 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": " vite --port 5000 --strictPort", - "build": "vite build", + "dev": " vite --mode open --port 5000 --strictPort", + "dev:pro": " vite --config ./vite.pro.config.ts --mode pro --port 5000 --strictPort ", + "build": "vite build --mode open", + "build:pro": "vite --config ./vite.pro.config.ts build --mode pro", "postinstall": "node scripts/moveTinymce.js", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview --port 5000 --strictPort", @@ -14,7 +16,6 @@ "dependencies": { "@tinymce/tinymce-react": "^4.3.2", "tinymce": "^6.8.1", - "copy-to-clipboard": "^3.3.3", "highlight.js": "^11.9.0", "fs-extra": "^11.2.0" }, diff --git a/frontend/packages/core/src/components/aoplatform/RenderRoutes.tsx b/frontend/packages/core/src/components/aoplatform/RenderRoutes.tsx index a072f57..201bcc1 100644 --- a/frontend/packages/core/src/components/aoplatform/RenderRoutes.tsx +++ b/frontend/packages/core/src/components/aoplatform/RenderRoutes.tsx @@ -1,7 +1,7 @@ /* * @Date: 2024-06-04 08:54:24 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 11:02:38 + * @LastEditTime: 2024-07-12 20:08:54 * @FilePath: \frontend\packages\core\src\components\aoplatform\RenderRoutes.tsx */ import { BrowserRouter as Router, Routes, Route, Navigate, Outlet } from 'react-router-dom'; @@ -12,7 +12,7 @@ import { v4 as uuidv4 } from 'uuid' import {App, Skeleton} from "antd"; import ApprovalPage from "@core/pages/approval/ApprovalPage.tsx"; import {SystemProvider} from "@core/contexts/SystemContext.tsx"; -import {GlobalProvider, useGlobalContext} from "@common/contexts/GlobalStateContext.tsx"; +import {useGlobalContext} from "@common/contexts/GlobalStateContext.tsx"; import {FC,lazy} from 'react'; import { TeamProvider } from '@core/contexts/TeamContext.tsx'; import SystemOutlet from '@core/pages/system/SystemOutlet.tsx'; @@ -23,11 +23,12 @@ import { TenantManagementProvider } from '@market/contexts/TenantManagementConte type RouteConfig = { path:string component?:ReactElement - children?:RouteConfig[] + children?:(RouteConfig|false)[] key:string provider?:FC<{ children: ReactNode; }> lazy?:unknown } +const APP_MODE = import.meta.env.VITE_APP_MODE; export type RouterParams = { orgId:string @@ -55,7 +56,6 @@ const PUBLIC_ROUTES:RouteConfig[] = [ path:'/', component:, key: uuidv4(), - }, { path:'/login', @@ -79,7 +79,6 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:'list', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/organization/OrganizationList.tsx')) } @@ -98,25 +97,21 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'inside/:orgId/:teamId', - // component:, lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsidePage.tsx')), key: uuidv4(), children:[ { path:'member', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsideMember.tsx')), }, { path:'access', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamInsideAccess.tsx')), }, { path:'setting', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/team/TeamConfig.tsx')), }, @@ -132,13 +127,11 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:'list', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemList.tsx')), }, { path:'list/:orgId/:teamId', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemList.tsx')), }, @@ -149,31 +142,26 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:'inside/:systemId', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsidePage.tsx')), children:[ { path:'api', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/api/SystemInsideApiList.tsx')), }, { path:'upstream', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/upstream/SystemInsideUpstreamContent.tsx')), }, { path:'myService', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/myService/SystemInsideMyService.tsx')), }, { path:'subService', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/subSubscribe/SystemInsideSubService.tsx')), children:[ @@ -182,7 +170,6 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'subscriber', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideSubscriber.tsx')), children:[ @@ -191,13 +178,11 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'approval', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/approval/SystemInsideApproval.tsx')), children:[ { path:'*', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/approval/SystemInsideApprovalList.tsx')), } @@ -212,7 +197,6 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'authority', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/authority/SystemInsideAuthority.tsx')), children:[ @@ -221,13 +205,11 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'publish', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/publish/SystemInsidePublish.tsx')), children:[ { path:'*', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/publish/SystemInsidePublishList.tsx')), } @@ -235,19 +217,16 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'access', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideAccess.tsx')), }, { path:'member', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemInsideMember.tsx')), }, { path:'setting', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/system/SystemConfig.tsx')), children:[ @@ -267,45 +246,38 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:'list', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionList.tsx')), }, { path:'inside/:partitionId', - // component:, key: uuidv4(), provider:PartitionProvider, lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsidePage.tsx')), children:[ { path:'cluster', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideCluster.tsx')), }, { path:'cert', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideCert.tsx')), }, - { + APP_MODE === 'pro' &&{ path:'dashboard_setting', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionInsideDashboardSetting.tsx')), }, { path:'setting', - // component:, key: uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/partitions/PartitionConfig.tsx')), }, { path:'template/:moduleId', - // component:, - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@common/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), key:uuidv4() } ] @@ -319,13 +291,11 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:'list', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/ServiceHubList.tsx')), }, { path:'detail/:serviceId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/ServiceHubDetail.tsx')), }] @@ -343,25 +313,21 @@ const PUBLIC_ROUTES:RouteConfig[] = [ children:[ { path:':teamId/inside/:appId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsidePage.tsx')), children:[ { path:'service/:partitionId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsideService.tsx')), }, { path:'authorization', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementInsideAuth.tsx')), }, { path:'setting', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ManagementAppSetting.tsx')), }, @@ -369,13 +335,11 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'list', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ServiceHubManagement.tsx')), }, { path:'list/:teamId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@market/pages/serviceHub/management/ServiceHubManagement.tsx')), }, @@ -383,19 +347,16 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'member/*', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberPage.tsx')), children:[ { path:'list', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberList.tsx')), }, { path:'list/:memberGroupId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/member/MemberList.tsx')), } @@ -403,19 +364,16 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'user/*', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserPage.tsx')), children:[ { path:'list', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserList.tsx')), }, { path:'list/:userGroupId', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/user/UserList.tsx')), } @@ -423,52 +381,28 @@ const PUBLIC_ROUTES:RouteConfig[] = [ }, { path:'role/*', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/role/RoleList.tsx')), }, { path:'access', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/access/AccessPage.tsx')), - // lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../pages/access/AccessList.tsx')), children:[ { path:':accessType', - // component:, key:uuidv4(), lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/access/AccessList.tsx')), }, ] }, - // { - // path:'email', - // // component:, - // lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../pages/email/Email.tsx')), - // key:uuidv4(), - // }, - { - path:'openapi', - // component:, - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/openApi/OpenApiList.tsx')), - key:uuidv4(), - }, - // { - // path:'webhook', - // // component:, - // lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../pages/webhook/Webhook.tsx')), - // key:uuidv4(), - // }, { path:'logretrieval', - // component:, lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/logRetrieval/LogRetrieval.tsx')), key:uuidv4(), }, { path:'auditlog', - // component:, lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/auditLog/AuditLog.tsx')), key:uuidv4(), }, @@ -477,41 +411,9 @@ const PUBLIC_ROUTES:RouteConfig[] = [ component:

设计中

, key:uuidv4() }, - { - path:'dashboard', - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/dashboard/Dashboard.tsx')), - key:uuidv4(), - children:[ - - { - path:':partitionId/:dashboardType', - component:, - key:uuidv4(), - provider:DashboardProvider, - children:[ - { - path:'list', - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/dashboard/DashboardList.tsx')), - key:uuidv4() - }, - { - path:'detail/:dashboardDetailId', - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/dashboard/DashboardDetail.tsx')), - key:uuidv4() - }, - ] - }, - ] - }, - { - path:'systemrunning', - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/systemRunning/SystemRunning.tsx')), - key:uuidv4() - }, { path:'template/:moduleId', - // component:, - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@common/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), key:uuidv4() }, { @@ -520,20 +422,18 @@ const PUBLIC_ROUTES:RouteConfig[] = [ key: uuidv4(), children:[{ path:'template/:moduleId', - // component:, - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@common/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), key:uuidv4() }] }, - { + APP_MODE ==='pro' && { path:'resourcesettings/*', lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@core/pages/resourcesettings/ResourceSettings.tsx')), key: uuidv4(), children:[{ path:'template/:moduleId', - // component:, - lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '../../../../common/src/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), + lazy:lazy(() => import(/* webpackChunkName: "[request]" */ '@common/components/aoplatform/intelligent-plugin/IntelligentPluginList.tsx')), key:uuidv4() }] @@ -583,7 +483,7 @@ const generateRoutes = (routerConfig: RouteConfig[]) => { path={route.path} element={routeElement} > - {route.children && generateRoutes(route.children)} + {route.children && generateRoutes(route.children as RouteConfig[])} ); } diff --git a/frontend/packages/core/src/const/organization/const.tsx b/frontend/packages/core/src/const/organization/const.tsx index 73c51b1..0063bd6 100644 --- a/frontend/packages/core/src/const/organization/const.tsx +++ b/frontend/packages/core/src/const/organization/const.tsx @@ -35,7 +35,7 @@ export const ORGANIZATION_TABLE_COLUMNS: ProColumns[] ellipsis:true }, { - title: '分区权限', + title: '环境权限', dataIndex: 'partition', ellipsis:true, renderText:(_,entity:OrganizationTableListItem)=>(entity.partition?.map(x=>x.name).join(',') || '-') @@ -55,7 +55,7 @@ export const ORGANIZATION_TABLE_COLUMNS: ProColumns[] key: 'createTime', dataIndex: 'createTime', ellipsis: true, - width:176, + width:182, sorter: (a,b)=> { return a.createTime.localeCompare(b.createTime) }, diff --git a/frontend/packages/core/src/const/partitions/const.tsx b/frontend/packages/core/src/const/partitions/const.tsx index 9165258..9586d34 100644 --- a/frontend/packages/core/src/const/partitions/const.tsx +++ b/frontend/packages/core/src/const/partitions/const.tsx @@ -1,25 +1,19 @@ -import { getItem, getTabItem } from "@common/utils/navigation"; +import { getItem } from "@common/utils/navigation"; import { ProColumns } from "@ant-design/pro-components"; import { PartitionCertTableListItem, PartitionClusterNodeModalTableListItem, PartitionClusterNodeTableListItem, PartitionClusterTableListItem, PartitionTableListItem } from "./types"; import { ColumnType } from "antd/es/table"; import CopyAddrList from "@common/components/aoplatform/CopyAddrList"; -import { MenuProps, TabsProps } from "antd"; +import { MenuProps } from "antd"; import { Link } from "react-router-dom"; -// export const PARTITIONS_INNER_MENU: TabsProps['items'] = [ -// getTabItem(集群, 'cluster',undefined,undefined,'system.partition.cluster.view'), -// getTabItem(证书管理, 'cert',undefined,undefined,'system.partition.cert.view'), -// getTabItem(监控配置, 'dashboard_setting',undefined,undefined,'system.partition.self.view'), -// getTabItem(分区设置, 'setting',undefined,undefined,'system.partition.self.view'), -// ] as TabsProps['items'] - +const APP_MODE = import.meta.env.VITE_APP_MODE; export const PARTITIONS_INNER_MENU: MenuProps['items'] = [ getItem('管理', 'grp', null, [getItem(集群, 'cluster',undefined,undefined,undefined,'system.partition.cluster.view'), getItem(证书管理, 'cert',undefined,undefined,undefined,'system.partition.cert.view'), - getItem(监控配置, 'dashboard_setting',undefined,undefined,undefined,'system.partition.self.view'), - getItem(分区设置, 'setting',undefined,undefined,undefined,'system.partition.self.view')], + APP_MODE ==='pro' ? getItem(监控配置, 'dashboard_setting',undefined,undefined,undefined,'system.partition.self.view'):null, + getItem(环境设置, 'setting',undefined,undefined,undefined,'system.partition.self.view')], 'group'), ]; @@ -68,7 +62,7 @@ export const PARTITION_CERT_TABLE_COLUMNS: ProColumns { return a.updateTime.localeCompare(b.updateTime) }, @@ -176,11 +170,10 @@ export const NODE_MODAL_COLUMNS:ColumnType[] = [ { - title: '分区名称', + title: '环境名称', dataIndex: 'name', copyable: true, ellipsis:true, - width:160, fixed:'left', sorter: (a,b)=> { return a.name.localeCompare(b.name) @@ -193,19 +186,20 @@ export const PARTITION_LIST_COLUMNS: ProColumns[] = [ ellipsis:true, width:140, }, - { - title: '集群数量', - dataIndex: 'clusterNum', - sorter: (a,b)=> { - return a.clusterNum - b.clusterNum - }, - }, + // { + // title: '集群数量', + // dataIndex: 'clusterNum', + // sorter: (a,b)=> { + // return a.clusterNum - b.clusterNum + // }, + // }, { title: '更新者', dataIndex: ['updater','name'], ellipsis: true, filters: true, onFilter: true, + width:100, valueType: 'select', filterSearch: true }, @@ -213,7 +207,7 @@ export const PARTITION_LIST_COLUMNS: ProColumns[] = [ title: '更新时间', dataIndex: 'updateTime', ellipsis:true, - width:176, + width:182, sorter: (a,b)=> { return a.updateTime.localeCompare(b.updateTime) }, diff --git a/frontend/packages/core/src/const/system/const.tsx b/frontend/packages/core/src/const/system/const.tsx index 5420e4b..4a1966e 100644 --- a/frontend/packages/core/src/const/system/const.tsx +++ b/frontend/packages/core/src/const/system/const.tsx @@ -5,9 +5,8 @@ import { ColumnsType } from "antd/es/table"; import { getItem } from "@common/utils/navigation"; import { MatchItem, MemberItem } from "@common/const/type"; import { ConfigField } from "@common/components/aoplatform/EditableTableWithModal"; -import { frontendTimeSorter } from "../../pages/openApi/OpenApiList"; +import { frontendTimeSorter } from "@common/utils/dataTransfer"; import moment from "moment"; -import { CheckboxOptionType } from "antd/lib/checkbox"; import { STATUS_COLOR } from "@common/const/const"; import { LoadingOutlined } from "@ant-design/icons"; import { SystemInsidePublishOnlineItems } from "../../pages/system/publish/SystemInsidePublishOnline"; @@ -154,7 +153,7 @@ export const SYSTEM_TABLE_COLUMNS: ProColumns[] = [ { title: '创建时间', dataIndex: 'createTime', - width:176, + width:182, ellipsis:true, sorter: (a,b)=>frontendTimeSorter(a,b,'createTime') } @@ -180,7 +179,7 @@ export const SYSTEM_SUBSERVICE_TABLE_COLUMNS: ProColumns(entity.partition?.map((x)=>x.name).join(',')||'-') @@ -241,7 +240,7 @@ export const SYSTEM_SUBSERVICE_TABLE_COLUMNS: ProColumns { return a.createTime.localeCompare(b.createTime) }, @@ -269,7 +268,7 @@ export const SYSTEM_SUBSCRIBER_TABLE_COLUMNS: ProColumns(entity.partition?.map((x)=>x.name).join(',')||'-') @@ -322,7 +321,7 @@ export const SYSTEM_SUBSCRIBER_TABLE_COLUMNS: ProColumns { return a.applyTime.localeCompare(b.applyTime) }, @@ -460,7 +459,7 @@ export const SYSTEM_API_TABLE_COLUMNS: ProColumns[] = [ dataIndex: 'updateTime', ellipsis:true, hideInSearch: true, - width:176, + width:182, sorter: (a,b)=>frontendTimeSorter(a,b,'updateTime') }, ]; @@ -509,7 +508,7 @@ export const SYSTEM_UPSTREAM_TABLE_COLUMNS: ProColumns { return a.createTime.localeCompare(b.createTime) @@ -518,7 +517,7 @@ export const SYSTEM_UPSTREAM_TABLE_COLUMNS: ProColumns { return a.updateTime.localeCompare(b.updateTime) @@ -709,7 +708,7 @@ export const SYSTEM_AUTHORITY_TABLE_COLUMNS: ProColumns ( 0 ? 'text-status_fail' : ''}>{entity.expireTime === 0 ? '永不过期' :moment(entity.expireTime * 1000).format('YYYY-MM-DD hh:mm:ss')} ), @@ -731,7 +730,7 @@ export const SYSTEM_AUTHORITY_TABLE_COLUMNS: ProColumns { return a.createTime.localeCompare(b.createTime) @@ -811,7 +810,7 @@ export const SYSTEM_MYSERVICE_TABLE_COLUMNS: ProColumns[ key: 'updateTime', dataIndex: 'updateTime', ellipsis:true, - width:176, + width:182, sorter: (a,b)=> { return a.updateTime.localeCompare(b.updateTime) }, @@ -820,7 +819,7 @@ export const SYSTEM_MYSERVICE_TABLE_COLUMNS: ProColumns[ title: '创建时间', key: 'createTime', dataIndex: 'createTime', - width:176, + width:182, ellipsis:true, sorter: (a,b)=> { return a.createTime.localeCompare(b.createTime) @@ -907,7 +906,7 @@ export const SYSTEM_SUBSCRIBE_APPROVAL_DETAIL_LIST = [ title:'申请状态',key:'status',renderText:()=>{} }, { - title:'可用分区',key:'partition',dataType:'checkbox' + title:'可用环境',key:'partition',dataType:'checkbox' }, { title:'申请人',key:'applier',nested:'name' @@ -959,7 +958,7 @@ export const SYSTEM_TOPOLOGY_NODE_TYPE_COLOR_MAP = { export const SYSTEM_PUBLISH_ONLINE_COLUMNS = [ { - title: '分区', + title: '环境', dataIndex: ['partition','name'], copyable: true, ellipsis:true, @@ -990,6 +989,9 @@ export const SYSTEM_TOPOLOGY_NODE_TYPE_COLOR_MAP = { }, ] +const APP_MODE = import.meta.env.VITE_APP_MODE; + + export const SYSTEM_PAGE_MENU_ITEMS: MenuProps['items'] = [ getItem('内部数据服务', 'assets', null, [ @@ -1013,7 +1015,7 @@ export const SYSTEM_TOPOLOGY_NODE_TYPE_COLOR_MAP = { // 'group'), getItem('管理', 'mng', null, [ - getItem(调用拓扑图, 'topology',undefined,undefined,undefined,'project.mySystem.topology.view'), + APP_MODE === 'pro' ? getItem(调用拓扑图, 'topology',undefined,undefined,undefined,'project.mySystem.topology.view'):null, getItem(成员, 'member',undefined,undefined,undefined,'project.mySystem.member.view'), getItem(权限, 'access',undefined,undefined,undefined,'project.mySystem.access.view'), getItem(设置, 'setting',undefined,undefined,undefined,'team.mySystem.self.edit')], diff --git a/frontend/packages/core/src/const/system/type.ts b/frontend/packages/core/src/const/system/type.ts index fab9807..085ef22 100644 --- a/frontend/packages/core/src/const/system/type.ts +++ b/frontend/packages/core/src/const/system/type.ts @@ -1,7 +1,7 @@ /* * @Date: 2024-02-04 16:37:27 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 11:18:44 + * @LastEditTime: 2024-07-12 10:15:37 * @FilePath: \frontend\packages\core\src\const\system\type.ts */ import { FormInstance, UploadFile } from "antd"; @@ -45,13 +45,6 @@ export type SystemSubServiceTableListItem = { }; -export type SimpleMemberItem = { - id:string - name:string - email:string - department:string - avatar:string -} export type SystemSubscriberTableListItem = { id:string @@ -155,6 +148,19 @@ export type SystemApiProxyFieldType = { proxy:SystemApiProxyType }; +export type SystemApiSimpleFieldType = { + id: string + name: string + description: string + method: string + path: string + match: MatchItem[] + creator: string + updater: string + create_time: string + update_time: string +} + export type SystemInsideApiCreateProps = { type?:'copy' entity?:SystemApiProxyFieldType &{systemId:string} diff --git a/frontend/packages/core/src/const/team/const.tsx b/frontend/packages/core/src/const/team/const.tsx index cfdba66..f555a52 100644 --- a/frontend/packages/core/src/const/team/const.tsx +++ b/frontend/packages/core/src/const/team/const.tsx @@ -60,7 +60,7 @@ export const TEAM_TABLE_COLUMNS: ProColumns[] = [ title: '创建时间', dataIndex: 'createTime', ellipsis:true, - width:176, + width:182, sorter: (a,b)=> { return a.createTime.localeCompare(b.createTime) }, diff --git a/frontend/packages/core/src/pages/Login.tsx b/frontend/packages/core/src/pages/Login.tsx index 855b809..7b06f5e 100644 --- a/frontend/packages/core/src/pages/Login.tsx +++ b/frontend/packages/core/src/pages/Login.tsx @@ -71,7 +71,6 @@ const Login:FC = ()=> { } }else{ dispatch({type:'LOGOUT'}) - //console.log(msg) message.error(msg) } @@ -100,14 +99,14 @@ const Login:FC = ()=> { -
+
登录
-
{
), }, - { + entity.id !== '-1' && { key: 'rename', label: ( */} {/* */} - + } label="描述" @@ -231,9 +232,9 @@ const PartitionConfig = forwardRef((
-

删除分区:删除操作不可恢复,请谨慎操作!

+

删除环境:删除操作不可恢复,请谨慎操作!

- +
} diff --git a/frontend/packages/core/src/pages/partitions/PartitionInsideCert.tsx b/frontend/packages/core/src/pages/partitions/PartitionInsideCert.tsx index af99005..b4fb704 100644 --- a/frontend/packages/core/src/pages/partitions/PartitionInsideCert.tsx +++ b/frontend/packages/core/src/pages/partitions/PartitionInsideCert.tsx @@ -11,7 +11,7 @@ import { Base64 } from 'js-base64'; import { PARTITION_CERT_TABLE_COLUMNS } from "../../const/partitions/const.tsx"; import { PartitionCertConfigHandle, PartitionCertConfigProps, PartitionCertTableListItem } from "../../const/partitions/types.ts"; import WithPermission from "@common/components/aoplatform/WithPermission.tsx"; -import { SimpleMemberItem } from "../../const/system/type.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; import { checkAccess } from "@common/utils/permission.ts"; diff --git a/frontend/packages/core/src/pages/partitions/PartitionInsideDashboardSetting.tsx b/frontend/packages/core/src/pages/partitions/PartitionInsideDashboardSetting.tsx index 314fd75..a041661 100644 --- a/frontend/packages/core/src/pages/partitions/PartitionInsideDashboardSetting.tsx +++ b/frontend/packages/core/src/pages/partitions/PartitionInsideDashboardSetting.tsx @@ -86,11 +86,11 @@ export default function PartitionInsideDashboardSetting(){ autoComplete="off" > {/* - label="分区名称" + label="环境名称" name="name" rules={[{ required: true, message: '必填项' }]} > - + */}
diff --git a/frontend/packages/core/src/pages/partitions/PartitionInsidePage.tsx b/frontend/packages/core/src/pages/partitions/PartitionInsidePage.tsx index c2cc536..e745dcc 100644 --- a/frontend/packages/core/src/pages/partitions/PartitionInsidePage.tsx +++ b/frontend/packages/core/src/pages/partitions/PartitionInsidePage.tsx @@ -58,7 +58,7 @@ const PartitionInsidePage = ()=> { 分区 ID:{partitionId || '-'} + 环境 ID:{partitionId || '-'} }]} backUrl="/partition/list">
@@ -66,7 +66,7 @@ const PartitionInsidePage = ()=> { className="h-full overflow-y-auto" selectedKeys={[activeMenu || '']} onClick={onMenuClick} - style={{ width: 176 }} + style={{ width: 182 }} mode="inline" items={PARTITIONS_INNER_MENU} /> diff --git a/frontend/packages/core/src/pages/partitions/PartitionList.tsx b/frontend/packages/core/src/pages/partitions/PartitionList.tsx index 887a6c4..af268ec 100644 --- a/frontend/packages/core/src/pages/partitions/PartitionList.tsx +++ b/frontend/packages/core/src/pages/partitions/PartitionList.tsx @@ -1,7 +1,7 @@ /* * @Date: 2024-01-31 15:00:11 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-06 17:54:34 + * @LastEditTime: 2024-07-12 09:57:09 * @FilePath: \frontend\packages\core\src\pages\partitions\PartitionList.tsx */ import PageList from "@common/components/aoplatform/PageList.tsx" @@ -14,7 +14,7 @@ import {useFetch} from "@common/hooks/http.ts"; import {App, Button, Modal} from "antd"; import { PARTITION_LIST_COLUMNS } from "../../const/partitions/const.tsx"; import { PartitionTableListItem } from "../../const/partitions/types.ts"; -import { SimpleMemberItem } from "../../const/system/type.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import PartitionConfig, { PartitionConfigHandle } from "./PartitionConfig.tsx"; import WithPermission from "@common/components/aoplatform/WithPermission.tsx"; @@ -77,7 +77,7 @@ const PartitionList:FC = ()=>{ setModalVisible(true) setAddClusterStep('config') // modal.confirm({ - // title:'添加分区', + // title:'添加环境', // content:, // onOk:()=> { // return addPartitionRef.current?.save().then((res)=>{if(res === true) manualReloadTable()}) @@ -119,9 +119,9 @@ const PartitionList:FC = ()=>{ ref={pageListRef} columns = {[...columns,...operation]} request={()=>getPartitionList()} - addNewBtnTitle="添加分区" + addNewBtnTitle="添加环境" showPagination={false} - searchPlaceholder="输入名称、ID 查找分区" + searchPlaceholder="输入名称、ID 查找环境" onAddNewBtnClick={()=>{openModal()}} addNewBtnAccess="system.partition.self.add" onSearchWordChange={(e)=>{setSearchWord(e.target.value)}} @@ -129,7 +129,7 @@ const PartitionList:FC = ()=>{ tableClickAccess="system.partition.self.view" /> { className="h-full overflow-y-auto" selectedKeys={[activeMenu || '']} onClick={onMenuClick} - style={{ width: 176 }} + style={{ width: 182 }} mode="inline" items={menuItems} /> diff --git a/frontend/packages/core/src/pages/resourcesettings/ResourceSettingsInstruction.tsx b/frontend/packages/core/src/pages/resourcesettings/ResourceSettingsInstruction.tsx index baa4e5f..897c064 100644 --- a/frontend/packages/core/src/pages/resourcesettings/ResourceSettingsInstruction.tsx +++ b/frontend/packages/core/src/pages/resourcesettings/ResourceSettingsInstruction.tsx @@ -21,16 +21,16 @@ export default function ResourceSettingsInstruction() { return (
-

分区配置并开启资源插件

-

资源插件用于增强网关的功能和性能。在启用资源类插件之前,请确保已经配置了分区。例如,Redis插件可以提高缓存和速率限制的性能,配置完成后,可以使用Redis作为缓存数据库。

+

环境配置并开启资源插件

+

资源插件用于增强网关的功能和性能。在启用资源类插件之前,请确保已经配置了环境。例如,Redis插件可以提高缓存和速率限制的性能,配置完成后,可以使用Redis作为缓存数据库。

{/*

更多配置及关联问题,请点击帮助中心 {/* 查看更多

*/}
-

分区配置

-

新增分区的名称、描述和其他相关属性,并设置该分区内的集群地址,以确保插件能够正确识别和连接到这些集群

-

添加分区/配置已有分区的集群地址

+

环境配置

+

新增环境的名称、描述和其他相关属性,并设置该环境内的集群地址,以确保插件能够正确识别和连接到这些集群

+

添加环境/配置已有环境的集群地址

diff --git a/frontend/packages/core/src/pages/serviceCategory/ServiceCategory.tsx b/frontend/packages/core/src/pages/serviceCategory/ServiceCategory.tsx index b3e1d0e..eceb61c 100644 --- a/frontend/packages/core/src/pages/serviceCategory/ServiceCategory.tsx +++ b/frontend/packages/core/src/pages/serviceCategory/ServiceCategory.tsx @@ -119,6 +119,7 @@ export default function ServiceCategory(){ setExpandedKeys(prev=>[...prev,item.id]) return { title: {item.name} , key: item.id, children: loop(item.children) }; @@ -126,6 +127,7 @@ export default function ServiceCategory(){ return { title: {item.name}, key: item.id, }; diff --git a/frontend/packages/core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx b/frontend/packages/core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx index d57d07a..cc76fe4 100644 --- a/frontend/packages/core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx +++ b/frontend/packages/core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx @@ -49,7 +49,6 @@ export const ServiceHubCategoryConfig = forwardRef { - //console.log(type,entity) switch(type){ case 'addCate': diff --git a/frontend/packages/core/src/pages/system/SystemConfig.tsx b/frontend/packages/core/src/pages/system/SystemConfig.tsx index 0303171..d174fb9 100644 --- a/frontend/packages/core/src/pages/system/SystemConfig.tsx +++ b/frontend/packages/core/src/pages/system/SystemConfig.tsx @@ -257,11 +257,11 @@ const SystemConfig = forwardRef((_,ref) => { - label="分区权限" + label="环境权限" name="partition" rules={[{ required: true, message: '必填项' }]} > - {partitionOption.length === 0 && 暂无可选分区,请检查所属团队可用分区} + {partitionOption.length === 0 && 暂无可选环境,请检查所属团队可用环境} {onEdit && <> x.user.id) || []) setTableListDataSource(data.members) setInit((prev) => prev ? false : prev) - // tableHttpReload && data.apps.sort((a:SystemMemberTableListItem,b:SystemMemberTableListItem)=>frontendTimeSorter(a,b,'updateTime')) setTableHttpReload(false) return {data: data.members, success: true} } else { diff --git a/frontend/packages/core/src/pages/system/SystemInsidePage.tsx b/frontend/packages/core/src/pages/system/SystemInsidePage.tsx index 5359bfe..7163d04 100644 --- a/frontend/packages/core/src/pages/system/SystemInsidePage.tsx +++ b/frontend/packages/core/src/pages/system/SystemInsidePage.tsx @@ -1,7 +1,7 @@ /* * @Date: 2024-01-31 15:00:11 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 19:10:58 + * @LastEditTime: 2024-07-12 20:58:39 * @FilePath: \frontend\packages\core\src\pages\system\SystemInsidePage.tsx */ import {FC, useEffect, useMemo, useState} from "react"; @@ -63,9 +63,9 @@ const SystemInsidePage:FC = ()=> { return newMenu!.filter((m:MenuItemGroupType )=>{ if(m.children && m.children.length > 0){ m.children = m.children.filter( - (c)=>(c as MenuItemType&{access:string} ).access ? + (c)=>(c&&(c as MenuItemType&{access:string} ).access ? checkPermission((c as MenuItemType&{access:string} ).access as keyof typeof PERMISSION_DEFINITION[0]): - true) + true)) } return m.children && m.children.length > 0 }) @@ -122,7 +122,7 @@ const SystemInsidePage:FC = ()=> { [] } diff --git a/frontend/packages/core/src/pages/system/SystemInsideSubscriber.tsx b/frontend/packages/core/src/pages/system/SystemInsideSubscriber.tsx index c368c02..ae10bb5 100644 --- a/frontend/packages/core/src/pages/system/SystemInsideSubscriber.tsx +++ b/frontend/packages/core/src/pages/system/SystemInsideSubscriber.tsx @@ -10,8 +10,8 @@ import PageList from "@common/components/aoplatform/PageList.tsx"; import {useSystemContext} from "../../contexts/SystemContext.tsx"; import {DefaultOptionType} from "antd/es/cascader"; import { SYSTEM_SUBSCRIBER_TABLE_COLUMNS } from "../../const/system/const.tsx"; -import { SystemSubscriberTableListItem, SimpleMemberItem, SystemSubscriberConfigFieldType, SystemSubscriberConfigHandle, SystemSubscriberConfigProps, SimpleSystemItem } from "../../const/system/type.ts"; -import { EntityItem, SimpleTeamItem } from "@common/const/type.ts"; +import { SystemSubscriberTableListItem, SystemSubscriberConfigFieldType, SystemSubscriberConfigHandle, SystemSubscriberConfigProps, SimpleSystemItem } from "../../const/system/type.ts"; +import { EntityItem, SimpleMemberItem } from "@common/const/type.ts"; import WithPermission from "@common/components/aoplatform/WithPermission.tsx"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; @@ -337,7 +337,7 @@ export const SystemSubscriberConfig = forwardRef diff --git a/frontend/packages/core/src/pages/system/SystemList.tsx b/frontend/packages/core/src/pages/system/SystemList.tsx index f1e7a5d..bcfb449 100644 --- a/frontend/packages/core/src/pages/system/SystemList.tsx +++ b/frontend/packages/core/src/pages/system/SystemList.tsx @@ -7,8 +7,8 @@ import {RouterParams} from "@core/components/aoplatform/RenderRoutes.tsx"; import {useBreadcrumb} from "@common/contexts/BreadcrumbContext.tsx"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; import {useFetch} from "@common/hooks/http.ts"; -import { SimpleTeamItem } from "@common/const/type.ts"; -import { SimpleMemberItem, SystemConfigHandle, SystemTableListItem } from "../../const/system/type.ts"; +import { SimpleTeamItem ,SimpleMemberItem} from "@common/const/type.ts"; +import { SystemConfigHandle, SystemTableListItem } from "../../const/system/type.ts"; import { SYSTEM_TABLE_COLUMNS } from "../../const/system/const.tsx"; import { DrawerWithFooter } from "@common/components/aoplatform/DrawerWithFooter.tsx"; import SystemConfig from "./SystemConfig.tsx"; diff --git a/frontend/packages/core/src/pages/system/SystemTopology.tsx b/frontend/packages/core/src/pages/system/SystemTopology.tsx index 991c1df..93baabb 100644 --- a/frontend/packages/core/src/pages/system/SystemTopology.tsx +++ b/frontend/packages/core/src/pages/system/SystemTopology.tsx @@ -1,7 +1,7 @@ /* * @Date: 2024-03-27 16:26:36 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-06 15:11:37 + * @LastEditTime: 2024-07-12 14:56:02 * @FilePath: \frontend\packages\core\src\pages\system\SystemTopology.tsx */ @@ -133,6 +133,7 @@ export default function SystemTopology() { graphRef.current = graph; graph.fitCenter(); + handleWindowResize() // 添加窗口大小变化的监听器 window.addEventListener('resize', handleWindowResize); diff --git a/frontend/packages/core/src/pages/system/api/SystemInsideApiList.tsx b/frontend/packages/core/src/pages/system/api/SystemInsideApiList.tsx index fffc85b..c8c197e 100644 --- a/frontend/packages/core/src/pages/system/api/SystemInsideApiList.tsx +++ b/frontend/packages/core/src/pages/system/api/SystemInsideApiList.tsx @@ -5,13 +5,13 @@ import {Link, useParams} from "react-router-dom"; import {useBreadcrumb} from "@common/contexts/BreadcrumbContext.tsx"; import {App, Divider} from "antd"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; +import { SimpleMemberItem} from '@common/const/type.ts' import {useFetch} from "@common/hooks/http.ts"; import {RouterParams} from "@core/components/aoplatform/RenderRoutes.tsx"; -import {OpenApiConfigFieldType} from "../../openApi/OpenApiConfig.tsx"; import SystemInsideApiCreate from "./SystemInsideApiCreate.tsx"; import {useSystemContext} from "../../../contexts/SystemContext.tsx"; import { SYSTEM_API_TABLE_COLUMNS } from "../../../const/system/const.tsx"; -import { SimpleMemberItem, SystemApiTableListItem, SystemInsideApiCreateHandle, SystemInsideApiDocumentHandle } from "../../../const/system/type.ts"; +import { SystemApiSimpleFieldType, SystemApiTableListItem, SystemInsideApiCreateHandle, SystemInsideApiDocumentHandle } from "../../../const/system/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; import { checkAccess } from "@common/utils/permission.ts"; @@ -89,7 +89,7 @@ const SystemInsideApiList:FC = ()=>{ case 'copy':{ title='复制 API' message.loading('正在加载数据') - const {code,data,msg} = await fetchData>('project/api/detail/simple',{method:'GET',eoParams:{project:systemId, api:entity!.id}}) + const {code,data,msg} = await fetchData>('project/api/detail/simple',{method:'GET',eoParams:{project:systemId, api:entity!.id}}) message.destroy() if(code === STATUS_CODE.SUCCESS){ content= @@ -112,21 +112,6 @@ const SystemInsideApiList:FC = ()=>{ case 'copy': return copyRef.current?.copy().then(()=> { manualReloadTable() - // modal.confirm({ - // title: '操作', - // content: '当前 API 已经创建成功。请问是否跳转到新的 API 页面?', - // onOk: () => { - // navigate!(`/system/${orgId}/${teamId}/inside/${systemId}/api/${res}/proxy`) - // }, - // onCancel: () => { - // manualReloadTable() - // }, - // width: 600, - // okText: '确认', - // cancelText: '取消', - // closable: true, - // icon: <> - // }) }) case 'delete': return deleteApi(entity).then((res)=>{if(res === true) manualReloadTable()}) @@ -232,7 +217,6 @@ const SystemInsideApiList:FC = ()=>{ request={()=>getApiList()} dataSource={tableListDataSource} addNewBtnTitle="添加 API" - // afterNewBtn = {[]} searchPlaceholder="输入名称、URL 查找 API" onAddNewBtnClick={()=>{openDrawer('add')}} addNewBtnAccess="project.mySystem.api.add" diff --git a/frontend/packages/core/src/pages/system/approval/SystemInsideApprovalList.tsx b/frontend/packages/core/src/pages/system/approval/SystemInsideApprovalList.tsx index 6d67b9f..b99e894 100644 --- a/frontend/packages/core/src/pages/system/approval/SystemInsideApprovalList.tsx +++ b/frontend/packages/core/src/pages/system/approval/SystemInsideApprovalList.tsx @@ -24,8 +24,7 @@ import { } from "@common/components/aoplatform/SubscribeApprovalModalContent.tsx"; import {useSystemContext} from "../../../contexts/SystemContext.tsx"; import WithPermission from "@common/components/aoplatform/WithPermission.tsx"; -import { EntityItem } from "@common/const/type.ts"; -import { SimpleMemberItem } from "../../../const/system/type.ts"; +import { EntityItem,SimpleMemberItem } from "@common/const/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; import { checkAccess } from "@common/utils/permission.ts"; diff --git a/frontend/packages/core/src/pages/system/authority/SystemInsideAuthority.tsx b/frontend/packages/core/src/pages/system/authority/SystemInsideAuthority.tsx index 55f6e54..d56ceeb 100644 --- a/frontend/packages/core/src/pages/system/authority/SystemInsideAuthority.tsx +++ b/frontend/packages/core/src/pages/system/authority/SystemInsideAuthority.tsx @@ -5,6 +5,7 @@ import {Link, useParams} from "react-router-dom"; import {useBreadcrumb} from "@common/contexts/BreadcrumbContext.tsx"; import { App, Divider } from "antd"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import {useFetch} from "@common/hooks/http.ts"; import {RouterParams} from "@core/components/aoplatform/RenderRoutes.tsx"; import {SystemAuthorityView} from "./SystemAuthorityView.tsx"; @@ -12,7 +13,7 @@ import { SystemAuthorityConfig, } from "./SystemAuthorityConfig.tsx"; import { SYSTEM_AUTHORITY_TABLE_COLUMNS } from "../../../const/system/const.tsx"; -import { SystemAuthorityTableListItem, SystemAuthorityConfigHandle, EditAuthFieldType, SimpleMemberItem } from "../../../const/system/type.ts"; +import { SystemAuthorityTableListItem, SystemAuthorityConfigHandle, EditAuthFieldType} from "../../../const/system/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { checkAccess } from "@common/utils/permission.ts"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; diff --git a/frontend/packages/core/src/pages/system/myService/MyServiceInsideConfig.tsx b/frontend/packages/core/src/pages/system/myService/MyServiceInsideConfig.tsx index fe78e53..c549dff 100644 --- a/frontend/packages/core/src/pages/system/myService/MyServiceInsideConfig.tsx +++ b/frontend/packages/core/src/pages/system/myService/MyServiceInsideConfig.tsx @@ -401,7 +401,7 @@ const normFile = (e: unknown) => { - label="可访问分区" + label="可访问环境" name="partition" rules={[{required: true, message: '必填项'}]} > diff --git a/frontend/packages/core/src/pages/system/myService/MyServiceInsideMenu.tsx b/frontend/packages/core/src/pages/system/myService/MyServiceInsideMenu.tsx index a0a0349..af103c4 100644 --- a/frontend/packages/core/src/pages/system/myService/MyServiceInsideMenu.tsx +++ b/frontend/packages/core/src/pages/system/myService/MyServiceInsideMenu.tsx @@ -37,7 +37,7 @@ const MyServiceInsideMenu:FC = ()=> { diff --git a/frontend/packages/core/src/pages/system/myService/SystemInsideMyService.tsx b/frontend/packages/core/src/pages/system/myService/SystemInsideMyService.tsx index 798d6b9..3e1c119 100644 --- a/frontend/packages/core/src/pages/system/myService/SystemInsideMyService.tsx +++ b/frontend/packages/core/src/pages/system/myService/SystemInsideMyService.tsx @@ -77,7 +77,6 @@ const SystemInsideMyService:FC = ()=>{ setOriginTableListDataSource(data.services) setTableListDataSource(selectedPartition.length > 0 ? data.services.filter((x:MyServiceTableListItem)=>x.partition.filter((x:EntityItem)=>selectedPartition.includes(x.id)).length > 0):data.services) setInit((prev)=>prev ? false : prev) - // tableHttpReload && data.apps.sort((a:MyServiceTableListItem,b:MyServiceTableListItem)=>frontendTimeSorter(a,b,'updateTime')) setTableHttpReload(false) return {data:data.services, success: true} }else{ diff --git a/frontend/packages/core/src/pages/system/publish/SystemInsidePublishList.tsx b/frontend/packages/core/src/pages/system/publish/SystemInsidePublishList.tsx index 7a9f1c1..6d431c2 100644 --- a/frontend/packages/core/src/pages/system/publish/SystemInsidePublishList.tsx +++ b/frontend/packages/core/src/pages/system/publish/SystemInsidePublishList.tsx @@ -7,11 +7,12 @@ import { PublishApprovalModalHandle, PublishApprovalModalContent } from "@common import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { PUBLISH_APPROVAL_RECORD_INNER_TABLE_COLUMN, PUBLISH_APPROVAL_VERSION_INNER_TABLE_COLUMN } from "@common/const/approval/const"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; +import { SimpleMemberItem } from "@common/const/type.ts"; import { MemberTableListItem } from "../../../const/member/type"; import { useBreadcrumb } from "@common/contexts/BreadcrumbContext"; import { useFetch } from "@common/hooks/http"; import WithPermission from "@common/components/aoplatform/WithPermission"; -import { SimpleMemberItem, SystemPublishReleaseItem } from "../../../const/system/type"; +import { SystemPublishReleaseItem } from "../../../const/system/type"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission"; import { useGlobalContext } from "@common/contexts/GlobalStateContext"; import { PERMISSION_DEFINITION } from "@common/const/permissions"; @@ -192,7 +193,7 @@ const SystemInsidePublicList:FC = ()=>{ message.loading('正在加载数据'); const { code, data, msg } = await fetchData>( 'project/publish/check', - { method: 'GET', eoParams:{project:systemId}} + { method: 'GET', eoParams:{project:systemId, ...(type === 'publish' ?{ release:entity?.id }:{})},eoTransformKeys:['version_remark'] } ); message.destroy(); if (code === STATUS_CODE.SUCCESS) { diff --git a/frontend/packages/core/src/pages/system/subSubscribe/SystemInsideSubService.tsx b/frontend/packages/core/src/pages/system/subSubscribe/SystemInsideSubService.tsx index babbedb..f750eae 100644 --- a/frontend/packages/core/src/pages/system/subSubscribe/SystemInsideSubService.tsx +++ b/frontend/packages/core/src/pages/system/subSubscribe/SystemInsideSubService.tsx @@ -5,9 +5,10 @@ import {Link, useNavigate, useParams} from "react-router-dom"; import {useBreadcrumb} from "@common/contexts/BreadcrumbContext.tsx"; import {App, Divider, Drawer} from "antd"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import {useFetch} from "@common/hooks/http.ts"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes.tsx"; -import { SimpleMemberItem, SubSubscribeApprovalModalHandle, SystemSubServiceTableListItem } from "../../../const/system/type.ts"; +import { SubSubscribeApprovalModalHandle, SystemSubServiceTableListItem } from "../../../const/system/type.ts"; import { SYSTEM_SUBSERVICE_TABLE_COLUMNS } from "../../../const/system/const.tsx"; import { SubSubscribeApprovalModalContent } from "./SubSubscribeApprovalDetailModalContent.tsx"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; diff --git a/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamConfig.tsx b/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamConfig.tsx index adea5de..ce78877 100644 --- a/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamConfig.tsx +++ b/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamConfig.tsx @@ -138,7 +138,7 @@ const globalConfigNodesRule: FormItemProps['rules'] = [ > - label="分区 ID" + label="环境 ID" name="partition" hidden rules={[{ required: true, message: '必填项',whitespace:true }]} diff --git a/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamList.tsx b/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamList.tsx index 956e910..544fe43 100644 --- a/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamList.tsx +++ b/frontend/packages/core/src/pages/system/upstream/SystemInsideUpstreamList.tsx @@ -5,9 +5,10 @@ import PageList from "@common/components/aoplatform/PageList.tsx"; import {useBreadcrumb} from "@common/contexts/BreadcrumbContext.tsx"; import {App, Divider} from "antd"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import {useFetch} from "@common/hooks/http.ts"; import {RouterParams} from "@core/components/aoplatform/RenderRoutes.tsx"; -import { SimpleMemberItem, SystemInsideUpstreamContentHandle, SystemUpstreamTableListItem } from "../../../const/system/type.ts"; +import { SystemInsideUpstreamContentHandle, SystemUpstreamTableListItem } from "../../../const/system/type.ts"; import { SYSTEM_UPSTREAM_TABLE_COLUMNS } from "../../../const/system/const.tsx"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; import { useGlobalContext } from "@common/contexts/GlobalStateContext.tsx"; diff --git a/frontend/packages/core/src/pages/systemRunning/SystemRunning3.tsx b/frontend/packages/core/src/pages/systemRunning/SystemRunning3.tsx deleted file mode 100644 index bfa0214..0000000 --- a/frontend/packages/core/src/pages/systemRunning/SystemRunning3.tsx +++ /dev/null @@ -1,550 +0,0 @@ -/* - * @Date: 2024-03-15 10:53:52 - * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 19:03:23 - * @FilePath: \frontend\packages\core\src\pages\systemRunning\SystemRunning3.tsx - */ - -import { useRef, useState, useEffect, useCallback } from "react"; -import { useFetch } from "@common/hooks/http.ts"; -import { useParams } from "react-router-dom"; -import { RouterParams } from "@core/components/aoplatform/RenderRoutes.tsx"; -import { App, Button, Spin, Tooltip } from "antd"; -import { debounce } from "lodash-es"; -import { LoadingOutlined, ZoomInOutlined, ZoomOutOutlined } from "@ant-design/icons"; -import G6, { Graph, registerEdge, Item } from "@antv/g6"; -import { PictureTypeEnum, NodeClickItem, GraphData } from "../../const/system-running/type.ts"; -import { UnionFind, edgesFormatter, getNodeSpacing, nodesFormatter } from "@common/utils/systemRunning.ts"; -import { EDGE_STYLE, END_ARROW_STYLE, OUT_SPACE_CONTENT_EDGE_COLOR, RELATIVE_PICTURE_NODE_FONTSIZE, SELF_SPACE_CONTENT_EDGE_COLOR, SYSTEM_TUNNING_CONFIG } from "../../const/system-running/const.ts"; -import ReactDOM from "react-dom"; -import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; -import SystemRunningInstruction from "./SystemRunningInstruction.tsx"; -import { useBreadcrumb } from "@common/contexts/BreadcrumbContext.tsx"; - -export type TopologyItem = { - projects:TopologyProjectItem[] - services:TopologyServiceItem[] -} - -export type TopologyProjectItem = { - id:string, - name:string, - invokeServices:string[], - clusters?:string -} - -export type TopologyServiceItem = { - id:string, - name:string, - project:string -} - -enum EdgeEvent { - Mouseenter = 'mouseenter', - Mouseleave = 'mouseleave' -} - -type nodeAny = unknown -const subjectColors = [ - '#5F95FF', // blue - '#61DDAA', - '#65789B', - '#F6BD16', - '#7262FD', - '#78D3F8', - '#9661BC', - '#F6903D', - '#008685', - '#F08BB4', -]; -const backColor = '#fff'; -const theme = 'default'; -const disableColor = '#777'; -const colorSets = G6.Util.getColorSetsBySubjectColors( - subjectColors, - backColor, - theme, - disableColor, -); - - -// cache the initial node and combo info -const itemMap :Record= {}; - -export default function SystemRunning(){ - const {message} = App.useApp() - const graphRef = useRef(null); - const graphContainerRef = useRef(null); - const {partitionId,topologyId} = useParams() - const [graph, setGraph] = useState(null); - const [graphData, setGraphData] = useState(); - const [currentNode, setCurrentNode] = useState() - const [showEdgeTooltip, setShowEdgeTooltip] = useState(false) - const [edgeTooltipX, setEdgeTooltipX] = useState(0) - const [edgeTooltipY, setEdgeTooltipY] = useState(0) - const [edgeTooltipContent, setEdgeTooltipContent] = useState() - const [pictureType, setPictureType] = useState(PictureTypeEnum.Global) - const { fetchData } = useFetch() - const textColor:string = '#666' - const [showGraph, setShowGraph] = useState(false) - const { setBreadcrumb } = useBreadcrumb() - const [zoomNum, setZoomNum] = useState(1) - const [loading, setLoading ] = useState(true) - const [categories, setCategories] = useState(undefined) - - /** - * @description 关联关系转化器,将接口数据转为 g6 渲染需要的格式 - */ - const relativeFormatter = (data: TopologyItem) => { - const { projects, services } = data - const serviceMap:Map = new Map() - services.forEach((s:TopologyServiceItem)=>{ - serviceMap.set(s.id,s) - }) - // Map> - const tmpProjectConnectMap:Map> = new Map() - projects.forEach((p:TopologyProjectItem) => { - const invokedMap = new Map() - p.invokeServices?.forEach((s:string) => { - const invokedProject = serviceMap.get(s) - if(invokedProject){ - invokedMap.has(invokedProject.project) ? invokedMap.get(invokedProject.project)?.push(invokedProject) : invokedMap.set(invokedProject.project, [invokedProject]) - }else{ - console.warn('存在无所属系统的服务:', s) - } - }) - tmpProjectConnectMap.set(p.id, invokedMap) - }) - const newNodes = nodesFormatter(projects) - const newEdges = edgesFormatter(tmpProjectConnectMap) - - // 从 edges 中提取所有唯一的节点 - // const allNodeIds = tmpProjectConnectMap.map(({ source, target }) => source || []).concat(tmpProjectConnectMap.map(({ source, target }) => target || [])).filter(Boolean); - // const nodes: Node[] = allNodeIds.map(id => ({ id })); - // 从 edges 中提取所有唯一的节点,并将 Set 转换为数组 - const allNodeIds:string[] = Array.from(new Set(newEdges.flatMap(edge => [edge.source, edge.target]))) as string[]; - - // 初始化 UnionFind,并处理所有的边 - const unionFind = new UnionFind(allNodeIds); - newEdges.forEach(({ source, target }) => { - unionFind.union(source, target); - }); - - // 预设的颜色数组 - const colors: string[] = [ - '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', - // ... 根据需要添加更多颜色 - ]; - - - // 使用 Union-Find 算法处理所有的边 - tmpProjectConnectMap.forEach(({ source, target }) => { - unionFind.union(source, target); - }); - - // 为每个连通分量分配颜色,并更新 nodes 数组 - const clusterToColor: Record = {}; - const categories: Record = {}; - const newCom = [] - - - newNodes.forEach(node => { - const root = unionFind.find(node.id); - categories[root] = categories[root] || []; - categories[root].push(node.id); - if (!clusterToColor[root]) { - // 分配颜色,确保同一连通分量的节点颜色相同 - clusterToColor[root] = colors[Math.max(0, Object.keys(clusterToColor).length) % colors.length]; - } - node.cluster = root || 'none'; - node.comboId = `${root || 'none'}-combo`; - // node.color = clusterToColor[root]; - }); - - - let i:number = 0 - - for(const c in categories){ - const color = colorSets[i % colorSets.length]; - const comboStyle = { - stroke: color.mainStroke, - fill: color.mainFill, - opacity: 0.8} - const comboId = `${c === 'undefined' ? 'none' : (c||'none') }-combo` - newCom.push(comboId === 'none-combo' ?{id:comboId,style:{ - fill:'transparent', - stroke:'transparent', - fillOpacity: 0, - strokeOpacity: 0, - active: { - // 设置激活状态下的透明度 - fill: 'transparent', - stroke: 'transparent', - fillOpacity: 0, - strokeOpacity: 0, - }, - inactive: { - fill: 'transparent', - stroke: 'transparent', - // 设置非激活状态下的透明度 - fillOpacity: 0, - strokeOpacity: 0, - }, - highlight: { - fill: 'transparent', - stroke: 'transparent', - // 设置高亮状态下的透明度 - fillOpacity: 0, - strokeOpacity: 0, - } - }}:{ - id:comboId, - style:comboStyle - }) - itemMap[comboId] = {style : { ...comboStyle }} - i++ - } - - - - newNodes.forEach(node => { - const parentCombo = itemMap[node.comboId]; - if (parentCombo) { - node.style = { - stroke: parentCombo.style.stroke, - fill: parentCombo.style.fill - } - } - // node.color = clusterToColor[root]; - }); - - - return { - nodes: newNodes, - edges: newEdges, - combos:newCom - } - } - - - - const getNodeData = ()=>{ - setLoading(true) - fetchData>('topology',{method:'GET',eoParams:{id:partitionId},eoTransformKeys:['invoke_services']},).then(response=>{ - const {code,data,msg} = response - if(code === STATUS_CODE.SUCCESS){ - const newGraphData = relativeFormatter(data) - setGraphData(newGraphData) - setShowGraph(newGraphData?.nodes?.length > 0) - - }else{ - message.error(msg || '操作失败') - } - }).finally(()=>setLoading(false)) - } - - const handleWindowResize = useCallback(debounce(() => { - if (graphContainerRef.current && graphRef.current && !graphRef.current?.get('destroyed')) { - graphRef.current.changeSize( - graphContainerRef.current.offsetWidth, - graphContainerRef.current.offsetHeight, - ); - graphRef.current?.fitCenter() - graphRef.current?.fitView() - } - }, 400), []); - - - /** - * @description 点击节点的回调 - */ - const clickNode = (item: NodeClickItem) => { - // console.log(item) - // router.navigate(['/', 'home', 'api-relative', item.id]) - } - - const updateSelected = ()=> { - if (!currentNode) return - // 设置节点状态 - graph?.setItemState(currentNode, 'selected', true) - } - - /** - * @description 更新缩放比例 - */ - const updateZoomTo = (increase:boolean) =>{ - if((increase && zoomNum*10 >= 20 )||(!increase && zoomNum*10 <= 2)) return - setZoomNum(increase ?( zoomNum*10 + 2)/10 : (zoomNum*10 - 2)/10) - graph?.zoomTo(increase ? ( zoomNum*10 + 2)/10 : (zoomNum*10 - 2)/10) - } - - const initGraph = () => { - return new G6.Graph({ - container: ReactDOM.findDOMNode(graphContainerRef.current) as HTMLDivElement, - groupByTypes: false, - // plugins: [tooltip], - fitCenter:true, - fitView:true, - layout: { - type: 'comboForce', - // 稳定系数,初始动画的加载时长(稳定性)=节点数量/稳定系数 - alphaDecay: 0.08, - // // 因为有分组的存在,整体布局需要往左偏移一点 - // // center: [(graphContainerRef.current?.scrollWidth || 300) / 2 - 150,( graphContainerRef.current?.scrollHeight || 0) / 2], - preventOverlap: true, - preventNodeOverlap:true, - preventComboOverlap:true, - comboCollideStrength:0.9, - nodeSize:24, - padding:[20,20,20,20], - nodeStrength: -10, - edgeStrength: 0.1, - comboPadding:30, - clustering:true, - clusterNodeStrength: 1000, - clusterEdgeDistance: 50, - clusterNodeSize: 100, - }, - modes: { - default: ['drag-combo','drag-canvas', 'drag-node', 'zoom-canvas','activate-relations' - ] - }, - defaultNode: { - size: [24, 24], - style: { - radius: 5, - stroke: '#69c0ff', - lineWidth: 1, - fillOpacity: 1 - }, - labelCfg: { - style: { - fontSize: RELATIVE_PICTURE_NODE_FONTSIZE, - fill: textColor - }, - position: 'bottom', - offset: 12 - } - }, - defaultEdge: { - // type: 'quadratic', - label: '调用服务', - labelCfg: { - style: { - fill: '5B8FF9', - opacity: 0 // 将透明度设置为0,隐藏提示信息,hover 才出现 - } - } - }, - defaultCombo: { - labelCfg: { - style: { - fill: '#666', // combo 的文本颜色 - }, - }, - }, - }) - } - - const updateEdgeLabel = (type: EdgeEvent, edge: Item) => { - - if (type === EdgeEvent.Mouseenter) { - // hover 边的时候出提示 - edge.update({ - labelCfg: { - style: { - opacity: 1, - fill: '#5B8FF9', - // @ts-expect-error g6 内部没定义好类型 - cursor: 'pointer', - } - } - }) - return - } - // 移出边时需要隐藏提示 - edge.update({ - labelCfg: { - style: { - opacity: 0, - // @ts-ignore g6 内部没定义好类型 - cursor: 'pointer' - } - } - }) - } - - const refreshDragNodePosition = (e: unknown)=> { - const model = e.item.get('model') - model.fx = e.x - model.fy = e.y - } - - const initGraphEvent = (graph:Graph, opts: { - onClickEdge?: (model: { target: string; source: string }) => void - onClickNode?: (item: NodeClickItem) => void - }) => { - - graph.on('node:mouseenter', (e) => { - const node = e.item - if (!node) return - // hover 出文本 - const element = node.getKeyShape() - element.attr('cursor', 'pointer') - }) - - graph.on('node:mouseleave', (e) => { - const node = e.item - if (!node) return - const element = node.getKeyShape() - element.attr('cursor', 'default') - }) - - // 目前只找到这种性能较低的方法 - graph.edge((edge) => { - const sourceNode = graph.findById(edge.source as string) - const theme = sourceNode?._cfg?.model?.isSelfSpace ? SELF_SPACE_CONTENT_EDGE_COLOR : OUT_SPACE_CONTENT_EDGE_COLOR - return { - id: edge.id, - ...EDGE_STYLE, - style: { - stroke: theme, - endArrow: { - ...END_ARROW_STYLE, - fill: theme - } - } - } - }) - - graph.on('edge:mouseenter', (evt) => { - if(evt.item){ - graph.setItemState(evt.item, 'running', true) - } - const edge = evt.item - if (edge) { - updateEdgeLabel(EdgeEvent.Mouseenter, edge) - const model = edge.getModel() - const { endPoint,startPoint } = model - // y=endPoint.y - height / 2,在同一水平线上,x值=endPoint.x - width - 10 - const y = (endPoint.y + startPoint.y) /2 - const x = (endPoint.x + startPoint.x )/2 - const point = graph.getCanvasByPoint(x, y) - setEdgeTooltipX(point.x + 194) // 加上页面左侧导航菜单宽度 - setEdgeTooltipY(point.y + 50) // 加上页面顶部导航与按钮高度 - setShowEdgeTooltip(true) - setEdgeTooltipContent(model?._projectInfo) - } - }) - - graph.on('edge:mouseleave', (evt) => { - const { item } = evt - if (item) { - graph.clearItemStates(item, ['running']) - updateEdgeLabel(EdgeEvent.Mouseleave, item) - } - setEdgeTooltipContent(undefined) - setShowEdgeTooltip(false) - }) - } - - const getGraph = ( - opts: { - onClickEdge?: (model: { target: string; source: string }) => void - onClickNode?: (item: NodeClickItem) => void - } - ) => { - const graph = initGraph() - graph.setMaxZoom(3) - graph.setMinZoom(0.2) - initGraphEvent(graph, opts) - return graph - } - - useEffect(()=>{ - if(topologyId !== undefined){ - setPictureType(PictureTypeEnum.Part) - setCurrentNode(topologyId) - return - } - setPictureType(PictureTypeEnum.Global) - },[topologyId]) - - useEffect(() => { - if (graphContainerRef.current) { - registerEdge('line-running',SYSTEM_TUNNING_CONFIG,'quadratic') - const graph = getGraph({ - onClickNode: (item: NodeClickItem) => { - clickNode(item) - }}) - - graph.on('beforelayout', async () => { - updateSelected() - }) - - setGraph(graph) - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-expect-error - graphRef.current = graph; - - // 添加窗口大小变化的监听器 - window.addEventListener('resize', handleWindowResize); - - // 组件卸载时清理资源 - return () => { - window.removeEventListener('resize', handleWindowResize); - if (graphRef.current) { - graphRef.current.destroy(); - } - }; - } - }, [handleWindowResize,showGraph,loading]); - - useEffect(()=>{ - if (!graph || !graphData || !showGraph || loading) return; - graph.clear() - graph.data(graphData) - - setTimeout(()=>{ - const { nodes } = graphData as GraphData - - if (nodes?.length) { - graph.updateLayout({ - nodeSpacing: getNodeSpacing(nodes.length,nodes), - comboSpacing: getNodeSpacing(nodes.length) - }) - } - - graph.render() - },200) - },[graph,graphData,showGraph,loading]) - - - useEffect(() => { - setBreadcrumb([{title:'系统拓扑图'}]) - getNodeData() - }, []); - - return (<> - { - showGraph ? -
-
-
-
-
-
-
-
-
-
- - -
-
- :} spinning={loading}>{!loading && } - }) - } - \ No newline at end of file diff --git a/frontend/packages/core/src/pages/team/TeamInsideMember.tsx b/frontend/packages/core/src/pages/team/TeamInsideMember.tsx index 4783693..f53d048 100644 --- a/frontend/packages/core/src/pages/team/TeamInsideMember.tsx +++ b/frontend/packages/core/src/pages/team/TeamInsideMember.tsx @@ -101,22 +101,12 @@ const TeamInsideMember:FC = ()=>{ } const getMemberList = ()=>{ - // if(!tableHttpReload){ - // setTableHttpReload(true) - // return Promise.resolve({ - // data: tableListDataSource, - // success: true, - // }); - // } return fetchData>('team/members',{method:'GET',eoParams:{keyword:searchWord, team:teamId},eoTransformKeys:['user_group','attach_time','user_id','can_delete']}).then(response=>{ const {code,data,msg} = response if(code === STATUS_CODE.SUCCESS){ if(!searchWord){ setAllMemberIds(data.members?.map((x:TeamMemberTableListItem)=>x.userId) || []) } - // setTableListDataSource(data.apps) - // tableHttpReload && data.apps.sort((a:TableListItem,b:TableListItem)=>frontendTimeSorter(a,b,'updateTime')) - // setTableHttpReload(false) return {data:data.members, success: true} }else{ message.error(msg || '操作失败') diff --git a/frontend/packages/core/src/pages/team/TeamInsidePage.tsx b/frontend/packages/core/src/pages/team/TeamInsidePage.tsx index fa897dd..2e7857d 100644 --- a/frontend/packages/core/src/pages/team/TeamInsidePage.tsx +++ b/frontend/packages/core/src/pages/team/TeamInsidePage.tsx @@ -101,7 +101,7 @@ const TeamInsidePage:FC = ()=> { backUrl="/team/list">
[] = [ title: '更新时间', dataIndex: 'updateTime', ellipsis:true, - width:176, + width:182, }, ]; diff --git a/frontend/packages/core/tsconfig.json b/frontend/packages/core/tsconfig.json index ebe2a9f..2fb368c 100644 --- a/frontend/packages/core/tsconfig.json +++ b/frontend/packages/core/tsconfig.json @@ -1,7 +1,7 @@ /* * @Date: 2024-06-04 08:54:17 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-05 10:26:57 + * @LastEditTime: 2024-07-12 13:54:42 * @FilePath: \frontend\packages\core\tsconfig.json */ { @@ -27,9 +27,9 @@ "paths": { "@core/*": ["./src/*"], "@common/*": ["../common/src/*"], - "@market/*": ["../market/src/*"] + "@market/*": ["../market/src/*"], }, }, - "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../common/src/components/aoplatform/ScrollableSection.tsx", "../common/src/utils/postcat.tsx", "../common/src/utils/curl.ts", "../common/src/const/dashboard", "../common/src/components/aoplatform/ResetPsw.tsx", "../common/src/components/aoplatform/SubscribeApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePageForHub.tsx", "src/components/aoplatform/RenderRoutes.tsx", "../common/src/components/aoplatform/PublishApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePage.tsx", "../common/src/const/type.ts", "../common/src/components/aoplatform/intelligent-plugin", "../common/src/const/domain"], + "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../common/src/components/aoplatform/ScrollableSection.tsx", "../common/src/utils/postcat.tsx", "../common/src/utils/curl.ts", "../common/src/components/aoplatform/ResetPsw.tsx", "../common/src/components/aoplatform/SubscribeApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePageForHub.tsx", "src/components/aoplatform/RenderRoutes.tsx", "../common/src/components/aoplatform/PublishApprovalModalContent.tsx", "../common/src/components/aoplatform/InsidePage.tsx", "../common/src/const/type.ts", "../common/src/components/aoplatform/intelligent-plugin", "../common/src/const/domain"], "references": [{ "path": "./tsconfig.node.json" }] } diff --git a/frontend/packages/core/vite.config.ts b/frontend/packages/core/vite.config.ts index 91c66bf..54b8adb 100644 --- a/frontend/packages/core/vite.config.ts +++ b/frontend/packages/core/vite.config.ts @@ -1,7 +1,7 @@ /* * @Date: 2024-01-31 15:00:39 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 17:04:41 + * @LastEditTime: 2024-07-12 19:44:49 * @FilePath: \frontend\packages\core\vite.config.ts */ import { defineConfig } from 'vite' @@ -10,8 +10,6 @@ import path from 'path' import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'; import tailwindcss from 'tailwindcss'; import autoprefixer from 'autoprefixer'; -// import {visualizer} from 'rollup-plugin-visualizer'; -// import MillionLint from '@million/lint' export default defineConfig({ cacheDir: './node_modules/.vite', @@ -57,15 +55,6 @@ export default defineConfig({ exclude:[], warnOnError:false }), - // MillionLint.vite() - // visualizer({ - // filename: 'stats.html', // 生成的可视化报告文件名 - // sourcemap: true, // 使用 sourcemap,以便更准确地显示原始源文件 - // // gzip: true, // 显示 gzip 压缩后的大小 - // brotliSize: false, // 显示 brotli 压缩后的大小 - // open: true, // 自动生成报告后自动打开浏览器 - // // 其他可视化选项... - // }), ], resolve: { alias: [ diff --git a/frontend/packages/core/vite.config.ts.timestamp-1720797741902-0827b2d7ab219.mjs b/frontend/packages/core/vite.config.ts.timestamp-1720797741902-0827b2d7ab219.mjs deleted file mode 100644 index cce4310..0000000 --- a/frontend/packages/core/vite.config.ts.timestamp-1720797741902-0827b2d7ab219.mjs +++ /dev/null @@ -1,90 +0,0 @@ -// vite.config.ts -import { defineConfig } from "file:///Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/node_modules/.pnpm/vite@5.0.12_@types+node@20.11.10_less@4.2.0/node_modules/vite/dist/node/index.js"; -import react from "file:///Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/node_modules/.pnpm/@vitejs+plugin-react@4.2.1_vite@5.0.12/node_modules/@vitejs/plugin-react/dist/index.mjs"; -import path from "path"; -import dynamicImportVars from "file:///Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/node_modules/.pnpm/@rollup+plugin-dynamic-import-vars@2.1.2/node_modules/@rollup/plugin-dynamic-import-vars/dist/es/index.js"; -import tailwindcss from "file:///Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/node_modules/.pnpm/tailwindcss@3.4.1/node_modules/tailwindcss/lib/index.js"; -import autoprefixer from "file:///Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/node_modules/.pnpm/autoprefixer@10.4.17_postcss@8.4.33/node_modules/autoprefixer/lib/autoprefixer.js"; -var __vite_injected_original_dirname = "/Users/liujian/work/golang/src/github.com/eolinker/apipark/frontend/packages/core"; -var vite_config_default = defineConfig({ - cacheDir: "./node_modules/.vite", - build: { - outDir: "../../dist", - sourcemap: false, - chunkSizeWarningLimit: 5e4, - cacheDir: "./node_modules/.vite", - output: { - manualChunks(id) { - if (id.includes("node_modules")) { - return id.toString().split("node_modules/")[1].split("/")[0].toString(); - } - if (id.includes(".pnpm")) { - const segments = id.split(path.sep); - const packageName = segments[segments.indexOf(".pnpm") + 1].split("@")[0]; - return packageName; - } - } - } - }, - css: { - postcss: { - plugins: [ - tailwindcss(path.resolve(__vite_injected_original_dirname, "../common/tailwind.config.js")), - autoprefixer - ] - }, - preprocessorOptions: { - less: { - javascriptEnabled: true - } - }, - modules: { - localsConvention: "camelCase", - generateScopedName: "[local]_[hash:base64:2]" - } - }, - plugins: [ - react(), - dynamicImportVars({ - include: ["src"], - exclude: [], - warnOnError: false - }) - // MillionLint.vite() - // visualizer({ - // filename: 'stats.html', // 生成的可视化报告文件名 - // sourcemap: true, // 使用 sourcemap,以便更准确地显示原始源文件 - // // gzip: true, // 显示 gzip 压缩后的大小 - // brotliSize: false, // 显示 brotli 压缩后的大小 - // open: true, // 自动生成报告后自动打开浏览器 - // // 其他可视化选项... - // }), - ], - resolve: { - alias: [ - { find: /^~/, replacement: "" }, - { find: "@common", replacement: path.resolve(__vite_injected_original_dirname, "../common/src") }, - { find: "@market", replacement: path.resolve(__vite_injected_original_dirname, "../market/src") }, - { find: "@core", replacement: path.resolve(__vite_injected_original_dirname, "./src") } - ] - }, - server: { - proxy: { - "/api/v1": { - // target: 'http://uat.apikit.com:11204/mockApi/aoplatform/', - target: "http://172.18.166.219:8288/", - changeOrigin: true - }, - "/api2/v1": { - // target: 'http://uat.apikit.com:11204/mockApi/aoplatform/', - target: "http://172.18.166.219:8288/", - changeOrigin: true - } - } - }, - logLevel: "info" -}); -export { - vite_config_default as default -}; -//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvbGl1amlhbi93b3JrL2dvbGFuZy9zcmMvZ2l0aHViLmNvbS9lb2xpbmtlci9hcGlwYXJrL2Zyb250ZW5kL3BhY2thZ2VzL2NvcmVcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9saXVqaWFuL3dvcmsvZ29sYW5nL3NyYy9naXRodWIuY29tL2VvbGlua2VyL2FwaXBhcmsvZnJvbnRlbmQvcGFja2FnZXMvY29yZS92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvbGl1amlhbi93b3JrL2dvbGFuZy9zcmMvZ2l0aHViLmNvbS9lb2xpbmtlci9hcGlwYXJrL2Zyb250ZW5kL3BhY2thZ2VzL2NvcmUvdml0ZS5jb25maWcudHNcIjsvKlxuICogQERhdGU6IDIwMjQtMDEtMzEgMTU6MDA6MzlcbiAqIEBMYXN0RWRpdG9yczogbWFnZ2lleXl5XG4gKiBATGFzdEVkaXRUaW1lOiAyMDI0LTA2LTA3IDE3OjA0OjQxXG4gKiBARmlsZVBhdGg6IFxcZnJvbnRlbmRcXHBhY2thZ2VzXFxjb3JlXFx2aXRlLmNvbmZpZy50c1xuICovXG5pbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tICd2aXRlJ1xuaW1wb3J0IHJlYWN0IGZyb20gJ0B2aXRlanMvcGx1Z2luLXJlYWN0J1xuaW1wb3J0IHBhdGggZnJvbSAncGF0aCdcbmltcG9ydCBkeW5hbWljSW1wb3J0VmFycyBmcm9tICdAcm9sbHVwL3BsdWdpbi1keW5hbWljLWltcG9ydC12YXJzJztcbmltcG9ydCB0YWlsd2luZGNzcyBmcm9tICd0YWlsd2luZGNzcyc7XG5pbXBvcnQgYXV0b3ByZWZpeGVyIGZyb20gJ2F1dG9wcmVmaXhlcic7XG4vLyBpbXBvcnQge3Zpc3VhbGl6ZXJ9IGZyb20gJ3JvbGx1cC1wbHVnaW4tdmlzdWFsaXplcic7XG4vLyBpbXBvcnQgTWlsbGlvbkxpbnQgZnJvbSAnQG1pbGxpb24vbGludCdcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgY2FjaGVEaXI6ICcuL25vZGVfbW9kdWxlcy8udml0ZScsXG4gIGJ1aWxkOntcbiAgICBvdXREaXI6Jy4uLy4uL2Rpc3QnLFxuICAgIHNvdXJjZW1hcDogZmFsc2UsXG4gICAgY2h1bmtTaXplV2FybmluZ0xpbWl0OiA1MDAwMCxcbiAgICBjYWNoZURpcjogJy4vbm9kZV9tb2R1bGVzLy52aXRlJywgXG4gICAgICBvdXRwdXQ6IHtcbiAgICAgICAgbWFudWFsQ2h1bmtzKGlkKSB7XG4gICAgICAgICAgaWYgKGlkLmluY2x1ZGVzKCdub2RlX21vZHVsZXMnKSkge1xuICAgICAgICAgICAgcmV0dXJuIGlkLnRvU3RyaW5nKCkuc3BsaXQoJ25vZGVfbW9kdWxlcy8nKVsxXS5zcGxpdCgnLycpWzBdLnRvU3RyaW5nKCk7XG4gICAgICAgICAgfVxuICAgICAgICAgIC8vIFx1OTQ4OFx1NUJGOSBwbnBtIFx1NTQ4QyBNb25vcmVwbyBcdTcyNzlcdTZCOEFcdTU5MDRcdTc0MDZcbiAgICAgICAgICBpZiAoaWQuaW5jbHVkZXMoJy5wbnBtJykpIHtcbiAgICAgICAgICAgIGNvbnN0IHNlZ21lbnRzID0gaWQuc3BsaXQocGF0aC5zZXApO1xuICAgICAgICAgICAgY29uc3QgcGFja2FnZU5hbWUgPSBzZWdtZW50c1tzZWdtZW50cy5pbmRleE9mKCcucG5wbScpICsgMV0uc3BsaXQoJ0AnKVswXTtcbiAgICAgICAgICAgIHJldHVybiBwYWNrYWdlTmFtZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH0sXG4gICAgfSxcbiAgY3NzOiB7XG4gICAgcG9zdGNzczoge1xuICAgICAgcGx1Z2luczogW1xuICAgICAgICB0YWlsd2luZGNzcyhwYXRoLnJlc29sdmUoX19kaXJuYW1lLCAnLi4vY29tbW9uL3RhaWx3aW5kLmNvbmZpZy5qcycpKSwgXG4gICAgICAgIGF1dG9wcmVmaXhlclxuICAgICAgXSxcbiAgICB9LFxuICAgIHByZXByb2Nlc3Nvck9wdGlvbnM6IHtcbiAgICAgIGxlc3M6IHtcbiAgICAgICAgamF2YXNjcmlwdEVuYWJsZWQ6IHRydWUsXG4gICAgICB9LFxuICAgIH0sXG4gICAgbW9kdWxlczp7XG4gICAgICBsb2NhbHNDb252ZW50aW9uOlwiY2FtZWxDYXNlXCIsXG4gICAgICBnZW5lcmF0ZVNjb3BlZE5hbWU6XCJbbG9jYWxdX1toYXNoOmJhc2U2NDoyXVwiXG4gICAgfVxuICB9LFxuICBwbHVnaW5zOiBbcmVhY3QoKSxcbiAgICAgIGR5bmFtaWNJbXBvcnRWYXJzKHtcbiAgICAgICAgaW5jbHVkZTpbXCJzcmNcIl0sXG4gICAgICAgIGV4Y2x1ZGU6W10sXG4gICAgICAgIHdhcm5PbkVycm9yOmZhbHNlXG4gICAgICAgfSksXG4gICAgICAvLyAgTWlsbGlvbkxpbnQudml0ZSgpXG4gICAgICAvLyAgdmlzdWFsaXplcih7XG4gICAgICAvLyAgICBmaWxlbmFtZTogJ3N0YXRzLmh0bWwnLCAvLyBcdTc1MUZcdTYyMTBcdTc2ODRcdTUzRUZcdTg5QzZcdTUzMTZcdTYyQTVcdTU0NEFcdTY1ODdcdTRFRjZcdTU0MERcbiAgICAgIC8vICAgIHNvdXJjZW1hcDogdHJ1ZSwgLy8gXHU0RjdGXHU3NTI4IHNvdXJjZW1hcFx1RkYwQ1x1NEVFNVx1NEZCRlx1NjZGNFx1NTFDNlx1Nzg2RVx1NTczMFx1NjYzRVx1NzkzQVx1NTM5Rlx1NTlDQlx1NkU5MFx1NjU4N1x1NEVGNlxuICAgICAgLy8gICAvLyAgZ3ppcDogdHJ1ZSwgLy8gXHU2NjNFXHU3OTNBIGd6aXAgXHU1MzhCXHU3RjI5XHU1NDBFXHU3Njg0XHU1OTI3XHU1QzBGXG4gICAgICAvLyAgICBicm90bGlTaXplOiBmYWxzZSwgLy8gXHU2NjNFXHU3OTNBIGJyb3RsaSBcdTUzOEJcdTdGMjlcdTU0MEVcdTc2ODRcdTU5MjdcdTVDMEZcbiAgICAgIC8vICAgIG9wZW46IHRydWUsIC8vIFx1ODFFQVx1NTJBOFx1NzUxRlx1NjIxMFx1NjJBNVx1NTQ0QVx1NTQwRVx1ODFFQVx1NTJBOFx1NjI1M1x1NUYwMFx1NkQ0Rlx1ODlDOFx1NTY2OFxuICAgICAgLy8gICAgLy8gXHU1MTc2XHU0RUQ2XHU1M0VGXHU4OUM2XHU1MzE2XHU5MDA5XHU5ODc5Li4uXG4gICAgICAvLyAgfSksXG4gICAgXSxcbiAgcmVzb2x2ZToge1xuICAgIGFsaWFzOiBbXG4gICAgICB7IGZpbmQ6IC9efi8sIHJlcGxhY2VtZW50OiAnJyB9LFxuICAgICAgeyBmaW5kOiAnQGNvbW1vbicsIHJlcGxhY2VtZW50OiBwYXRoLnJlc29sdmUoX19kaXJuYW1lLCAnLi4vY29tbW9uL3NyYycpIH0sXG4gICAgICB7IGZpbmQ6ICdAbWFya2V0JywgcmVwbGFjZW1lbnQ6IHBhdGgucmVzb2x2ZShfX2Rpcm5hbWUsICcuLi9tYXJrZXQvc3JjJykgfSxcbiAgICAgIHsgZmluZDogJ0Bjb3JlJywgcmVwbGFjZW1lbnQ6IHBhdGgucmVzb2x2ZShfX2Rpcm5hbWUsICcuL3NyYycpIH0sXG4gICAgXVxuICB9LFxuICBzZXJ2ZXI6IHtcbiAgICBwcm94eToge1xuICAgICAgJy9hcGkvdjEnOiB7XG4gICAgICAgIC8vIHRhcmdldDogJ2h0dHA6Ly91YXQuYXBpa2l0LmNvbToxMTIwNC9tb2NrQXBpL2FvcGxhdGZvcm0vJyxcbiAgICAgICAgdGFyZ2V0OiAnaHR0cDovLzE3Mi4xOC4xNjYuMjE5OjgyODgvJyxcbiAgICAgICAgY2hhbmdlT3JpZ2luOiB0cnVlLFxuICAgICAgfSxcbiAgICAgICcvYXBpMi92MSc6IHtcbiAgICAgICAgLy8gdGFyZ2V0OiAnaHR0cDovL3VhdC5hcGlraXQuY29tOjExMjA0L21vY2tBcGkvYW9wbGF0Zm9ybS8nLFxuICAgICAgICB0YXJnZXQ6ICdodHRwOi8vMTcyLjE4LjE2Ni4yMTk6ODI4OC8nLFxuICAgICAgICBjaGFuZ2VPcmlnaW46IHRydWUsXG4gICAgICB9XG4gICAgfVxuICB9LFxuICBsb2dMZXZlbDonaW5mbydcbn0pXG4iXSwKICAibWFwcGluZ3MiOiAiO0FBTUEsU0FBUyxvQkFBb0I7QUFDN0IsT0FBTyxXQUFXO0FBQ2xCLE9BQU8sVUFBVTtBQUNqQixPQUFPLHVCQUF1QjtBQUM5QixPQUFPLGlCQUFpQjtBQUN4QixPQUFPLGtCQUFrQjtBQVh6QixJQUFNLG1DQUFtQztBQWV6QyxJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixVQUFVO0FBQUEsRUFDVixPQUFNO0FBQUEsSUFDSixRQUFPO0FBQUEsSUFDUCxXQUFXO0FBQUEsSUFDWCx1QkFBdUI7QUFBQSxJQUN2QixVQUFVO0FBQUEsSUFDUixRQUFRO0FBQUEsTUFDTixhQUFhLElBQUk7QUFDZixZQUFJLEdBQUcsU0FBUyxjQUFjLEdBQUc7QUFDL0IsaUJBQU8sR0FBRyxTQUFTLEVBQUUsTUFBTSxlQUFlLEVBQUUsQ0FBQyxFQUFFLE1BQU0sR0FBRyxFQUFFLENBQUMsRUFBRSxTQUFTO0FBQUEsUUFDeEU7QUFFQSxZQUFJLEdBQUcsU0FBUyxPQUFPLEdBQUc7QUFDeEIsZ0JBQU0sV0FBVyxHQUFHLE1BQU0sS0FBSyxHQUFHO0FBQ2xDLGdCQUFNLGNBQWMsU0FBUyxTQUFTLFFBQVEsT0FBTyxJQUFJLENBQUMsRUFBRSxNQUFNLEdBQUcsRUFBRSxDQUFDO0FBQ3hFLGlCQUFPO0FBQUEsUUFDVDtBQUFBLE1BQ0Y7QUFBQSxJQUNGO0FBQUEsRUFDRjtBQUFBLEVBQ0YsS0FBSztBQUFBLElBQ0gsU0FBUztBQUFBLE1BQ1AsU0FBUztBQUFBLFFBQ1AsWUFBWSxLQUFLLFFBQVEsa0NBQVcsOEJBQThCLENBQUM7QUFBQSxRQUNuRTtBQUFBLE1BQ0Y7QUFBQSxJQUNGO0FBQUEsSUFDQSxxQkFBcUI7QUFBQSxNQUNuQixNQUFNO0FBQUEsUUFDSixtQkFBbUI7QUFBQSxNQUNyQjtBQUFBLElBQ0Y7QUFBQSxJQUNBLFNBQVE7QUFBQSxNQUNOLGtCQUFpQjtBQUFBLE1BQ2pCLG9CQUFtQjtBQUFBLElBQ3JCO0FBQUEsRUFDRjtBQUFBLEVBQ0EsU0FBUztBQUFBLElBQUMsTUFBTTtBQUFBLElBQ1osa0JBQWtCO0FBQUEsTUFDaEIsU0FBUSxDQUFDLEtBQUs7QUFBQSxNQUNkLFNBQVEsQ0FBQztBQUFBLE1BQ1QsYUFBWTtBQUFBLElBQ2IsQ0FBQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLEVBVUo7QUFBQSxFQUNGLFNBQVM7QUFBQSxJQUNQLE9BQU87QUFBQSxNQUNMLEVBQUUsTUFBTSxNQUFNLGFBQWEsR0FBRztBQUFBLE1BQzlCLEVBQUUsTUFBTSxXQUFXLGFBQWEsS0FBSyxRQUFRLGtDQUFXLGVBQWUsRUFBRTtBQUFBLE1BQ3pFLEVBQUUsTUFBTSxXQUFXLGFBQWEsS0FBSyxRQUFRLGtDQUFXLGVBQWUsRUFBRTtBQUFBLE1BQ3pFLEVBQUUsTUFBTSxTQUFTLGFBQWEsS0FBSyxRQUFRLGtDQUFXLE9BQU8sRUFBRTtBQUFBLElBQ2pFO0FBQUEsRUFDRjtBQUFBLEVBQ0EsUUFBUTtBQUFBLElBQ04sT0FBTztBQUFBLE1BQ0wsV0FBVztBQUFBO0FBQUEsUUFFVCxRQUFRO0FBQUEsUUFDUixjQUFjO0FBQUEsTUFDaEI7QUFBQSxNQUNBLFlBQVk7QUFBQTtBQUFBLFFBRVYsUUFBUTtBQUFBLFFBQ1IsY0FBYztBQUFBLE1BQ2hCO0FBQUEsSUFDRjtBQUFBLEVBQ0Y7QUFBQSxFQUNBLFVBQVM7QUFDWCxDQUFDOyIsCiAgIm5hbWVzIjogW10KfQo= diff --git a/frontend/packages/dashboard/README.md b/frontend/packages/dashboard/README.md new file mode 100644 index 0000000..12dcb52 --- /dev/null +++ b/frontend/packages/dashboard/README.md @@ -0,0 +1,11 @@ +# `dashboard` + +> TODO: description + +## Usage + +``` +const dashboard = require('dashboard'); + +// TODO: DEMONSTRATE API +``` diff --git a/frontend/packages/dashboard/__tests__/dashboard.test.js b/frontend/packages/dashboard/__tests__/dashboard.test.js new file mode 100644 index 0000000..875278c --- /dev/null +++ b/frontend/packages/dashboard/__tests__/dashboard.test.js @@ -0,0 +1,7 @@ +'use strict'; + +const dashboard = require('..'); +const assert = require('assert').strict; + +assert.strictEqual(dashboard(), 'Hello from dashboard'); +console.info('dashboard tests passed'); diff --git a/frontend/packages/dashboard/package.json b/frontend/packages/dashboard/package.json new file mode 100644 index 0000000..bb61312 --- /dev/null +++ b/frontend/packages/dashboard/package.json @@ -0,0 +1,11 @@ +{ + "name": "dashboard", + "version": "0.0.0", + "description": "dashboard for AO Platform", + "author": "maggieyyy ", + "homepage": "", + "license": "ISC", + "dependencies": { + "echarts-for-react": "^3.0.2" + } +} diff --git a/frontend/packages/dashboard/postcss.config.js b/frontend/packages/dashboard/postcss.config.js new file mode 100644 index 0000000..8039309 --- /dev/null +++ b/frontend/packages/dashboard/postcss.config.js @@ -0,0 +1,15 @@ +/* + * @Date: 2023-11-27 17:31:54 + * @LastEditors: maggieyyy + * @LastEditTime: 2023-11-29 15:49:05 + * @FilePath: \applatform\frontend\packages\core\postcss.config.js + */ +export default { + plugins: { + 'postcss-import': {}, + 'tailwindcss/nesting': {}, + tailwindcss: {}, + autoprefixer: {} + }, + } + \ No newline at end of file diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorApiPage.tsx b/frontend/packages/dashboard/src/component/MonitorApiPage.tsx similarity index 98% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorApiPage.tsx rename to frontend/packages/dashboard/src/component/MonitorApiPage.tsx index 4f53d31..430edd6 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorApiPage.tsx +++ b/frontend/packages/dashboard/src/component/MonitorApiPage.tsx @@ -2,8 +2,8 @@ import { CloseOutlined, ExpandOutlined, SearchOutlined } from "@ant-design/icons import { Select, Input, Button, App, Drawer } from "antd"; import { debounce } from "lodash-es"; import { useState, useEffect, useRef } from "react"; -import { MonitorApiData, SearchBody } from "@common/const/dashboard/type"; -import { getTime } from "@common/utils/dashboard"; +import { MonitorApiData, SearchBody } from "@dashboard/const/type"; +import { getTime } from "../utils/dashboard"; import ScrollableSection from "@common/components/aoplatform/ScrollableSection"; import TimeRangeSelector, { RangeValue, TimeRange, TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; import MonitorTable, { MonitorTableHandler } from "./MonitorTable"; @@ -12,7 +12,7 @@ import { DefaultOptionType } from "antd/es/select"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { useExcelExport } from "@common/hooks/excel"; -import { API_TABLE_GLOBAL_COLUMNS_CONFIG } from "@common/const/dashboard/const"; +import { API_TABLE_GLOBAL_COLUMNS_CONFIG } from "@dashboard/const/const"; import { useFetch } from "@common/hooks/http"; import { EntityItem } from "@common/const/type"; export type MonitorApiPageProps = { diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorAppPage.tsx b/frontend/packages/dashboard/src/component/MonitorAppPage.tsx similarity index 97% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorAppPage.tsx rename to frontend/packages/dashboard/src/component/MonitorAppPage.tsx index e69b8f4..a70b6e8 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorAppPage.tsx +++ b/frontend/packages/dashboard/src/component/MonitorAppPage.tsx @@ -1,16 +1,16 @@ import { Select, Button, App, Radio, Drawer } from "antd"; import { useEffect, useRef, useState } from "react"; -import { MonitorSubscriberData, SearchBody } from "@common/const/dashboard/type"; +import { MonitorSubscriberData, SearchBody } from "@dashboard/const/type"; import { EntityItem } from "@common/const/type"; import TimeRangeSelector, { RangeValue, TimeRange, TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; import MonitorTable, { MonitorTableHandler } from "./MonitorTable"; import { DefaultOptionType } from "antd/es/select"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { getTime } from "@common/utils/dashboard"; +import { getTime } from "../utils/dashboard"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { useExcelExport } from "@common/hooks/excel"; -import { APPLICATION_TABLE_GLOBAL_COLUMNS_CONFIG } from "@common/const/dashboard/const"; +import { APPLICATION_TABLE_GLOBAL_COLUMNS_CONFIG } from "@dashboard/const/const"; import { CloseOutlined, ExpandOutlined } from "@ant-design/icons"; import { useFetch } from "@common/hooks/http"; import { MonitorSubQueryData } from "./MonitorSubPage"; diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorDetailPage.tsx b/frontend/packages/dashboard/src/component/MonitorDetailPage.tsx similarity index 97% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorDetailPage.tsx rename to frontend/packages/dashboard/src/component/MonitorDetailPage.tsx index acd08a9..b88bce3 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorDetailPage.tsx +++ b/frontend/packages/dashboard/src/component/MonitorDetailPage.tsx @@ -1,12 +1,12 @@ import { Button, Modal, Empty, message, Checkbox, Radio } from "antd"; import { useState, useEffect, useRef } from "react"; -import { InvokeData, MonitorApiData, MonitorSubscriberData, SearchBody } from "@common/const/dashboard/type"; +import { InvokeData, MonitorApiData, MonitorSubscriberData, SearchBody } from "@dashboard/const/type"; import TimeRangeSelector, { RangeValue, TimeRange, TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; import MonitorLineGraph from "./MonitorLineGraph"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { getTime, getTimeUnit } from "@common/utils/dashboard"; +import { getTime, getTimeUnit } from "../utils/dashboard"; import MonitorTable, { MonitorTableHandler } from "./MonitorTable"; -import { DashboardDetailInvokeType } from "@core/pages/dashboard/DashboardDetail"; +import { DashboardDetailInvokeType } from "@dashboard/pages/DashboardDetail"; import { MonitorApiQueryData } from "./MonitorApiPage"; import { MonitorSubQueryData } from "./MonitorSubPage"; import dayjs from "dayjs"; diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorLineGraph.tsx b/frontend/packages/dashboard/src/component/MonitorLineGraph.tsx similarity index 98% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorLineGraph.tsx rename to frontend/packages/dashboard/src/component/MonitorLineGraph.tsx index 0da2546..0d90fbe 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorLineGraph.tsx +++ b/frontend/packages/dashboard/src/component/MonitorLineGraph.tsx @@ -1,14 +1,14 @@ /* * @Date: 2024-02-27 15:43:18 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 10:27:27 - * @FilePath: \frontend\packages\core\src\components\dashboard\MonitorLineGraph.tsx + * @LastEditTime: 2024-07-12 10:42:39 + * @FilePath: \frontend\packages\dashboard\src\component\MonitorLineGraph.tsx */ import { FC, useEffect, useMemo, useRef, useState } from 'react'; import ECharts, { EChartsOption } from 'echarts-for-react'; -import { InvokeData, LineGraphType, MessageData } from '@common/const/dashboard/type'; -import { MONITOR_LINE_CHART_BASIC_INVOKE_SELECTED, MONITOR_LINE_CHART_BASIC_MESSAGE_SELECTED, MONITOR_LINE_CHART_OPTION_CONFIG, MONITOR_NAME_MAP } from '@common/const/dashboard/const'; -import { yUnitFormatter } from '@common/utils/dashboard'; +import { InvokeData, LineGraphType, MessageData } from '@dashboard/const/type'; +import { MONITOR_LINE_CHART_BASIC_INVOKE_SELECTED, MONITOR_LINE_CHART_BASIC_MESSAGE_SELECTED, MONITOR_LINE_CHART_OPTION_CONFIG, MONITOR_NAME_MAP } from '@dashboard/const/const'; +import { yUnitFormatter } from '../utils/dashboard'; type LineGraphProps = { className?:string diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorPieGraph.tsx b/frontend/packages/dashboard/src/component/MonitorPieGraph.tsx similarity index 98% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorPieGraph.tsx rename to frontend/packages/dashboard/src/component/MonitorPieGraph.tsx index 293c7f2..34df6b7 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorPieGraph.tsx +++ b/frontend/packages/dashboard/src/component/MonitorPieGraph.tsx @@ -1,6 +1,6 @@ import {FC} from 'react'; import ECharts,{EChartsOption} from 'echarts-for-react'; -import { changeNumberUnit } from '@common/utils/dashboard'; +import { changeNumberUnit } from '../utils/dashboard'; type PieGraphProps = { className?:string, diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorSubPage.tsx b/frontend/packages/dashboard/src/component/MonitorSubPage.tsx similarity index 97% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorSubPage.tsx rename to frontend/packages/dashboard/src/component/MonitorSubPage.tsx index 916f921..02a59b5 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorSubPage.tsx +++ b/frontend/packages/dashboard/src/component/MonitorSubPage.tsx @@ -1,16 +1,16 @@ import { Select, Button, App, Radio, Drawer } from "antd"; import { useEffect, useRef, useState } from "react"; -import { MonitorSubscriberData, SearchBody } from "@common/const/dashboard/type"; +import { MonitorSubscriberData, SearchBody } from "@dashboard/const/type"; import { EntityItem } from "@common/const/type"; import TimeRangeSelector, { RangeValue, TimeRange, TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; import MonitorTable, { MonitorTableHandler } from "./MonitorTable"; import { DefaultOptionType } from "antd/es/select"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { getTime } from "@common/utils/dashboard"; +import { getTime } from "../utils/dashboard"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { useExcelExport } from "@common/hooks/excel"; -import { SERVICE_TABLE_GLOBAL_COLUMNS_CONFIG } from "@common/const/dashboard/const"; +import { SERVICE_TABLE_GLOBAL_COLUMNS_CONFIG } from "@dashboard/const/const"; import { CloseOutlined, ExpandOutlined } from "@ant-design/icons"; import { useFetch } from "@common/hooks/http"; diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorTable.tsx b/frontend/packages/dashboard/src/component/MonitorTable.tsx similarity index 94% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorTable.tsx rename to frontend/packages/dashboard/src/component/MonitorTable.tsx index e1568a6..ce53b0e 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorTable.tsx +++ b/frontend/packages/dashboard/src/component/MonitorTable.tsx @@ -1,14 +1,14 @@ /* * @Date: 2024-03-18 12:03:42 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 09:15:24 - * @FilePath: \frontend\packages\common\src\components\aoplatform\dashboard\MonitorTable.tsx + * @LastEditTime: 2024-07-12 10:34:38 + * @FilePath: \frontend\packages\dashboard\src\component\MonitorTable.tsx */ import { ActionType, ProColumns } from "@ant-design/pro-components" import { useImperativeHandle, useRef, useState } from "react" import PageList from "@common/components/aoplatform/PageList" import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission" -import { API_TABLE_GLOBAL_COLUMNS_CONFIG,SERVICE_TABLE_GLOBAL_COLUMNS_CONFIG, APPLICATION_TABLE_GLOBAL_COLUMNS_CONFIG } from "@common/const/dashboard/const" +import { API_TABLE_GLOBAL_COLUMNS_CONFIG,SERVICE_TABLE_GLOBAL_COLUMNS_CONFIG, APPLICATION_TABLE_GLOBAL_COLUMNS_CONFIG } from "@dashboard/const/const" import {forwardRef} from "react" const TableType = { diff --git a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorTotalPage.tsx b/frontend/packages/dashboard/src/component/MonitorTotalPage.tsx similarity index 97% rename from frontend/packages/common/src/components/aoplatform/dashboard/MonitorTotalPage.tsx rename to frontend/packages/dashboard/src/component/MonitorTotalPage.tsx index 22ea711..3cdd9e6 100644 --- a/frontend/packages/common/src/components/aoplatform/dashboard/MonitorTotalPage.tsx +++ b/frontend/packages/dashboard/src/component/MonitorTotalPage.tsx @@ -1,8 +1,8 @@ /* * @Date: 2024-02-27 11:51:23 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 17:13:07 - * @FilePath: \frontend\packages\common\src\components\aoplatform\dashboard\MonitorTotalPage.tsx + * @LastEditTime: 2024-07-12 10:41:59 + * @FilePath: \frontend\packages\dashboard\src\component\MonitorTotalPage.tsx */ import { App, Select, Button, Tabs, TabsProps, Empty, Drawer, Spin } from "antd"; @@ -11,18 +11,17 @@ import customParseFormat from "dayjs/plugin/customParseFormat"; import { useState, useEffect, useRef, useReducer } from "react"; import { useParams } from "react-router-dom"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { SummaryPieData, SearchBody, PieData, MonitorApiData, MonitorSubscriberData, InvokeData, MessageData } from "@common/const/dashboard/type"; -import { getTime, getTimeUnit, changeNumberUnit } from "@common/utils/dashboard"; +import { SummaryPieData, SearchBody, PieData, MonitorApiData, MonitorSubscriberData, InvokeData, MessageData } from "@dashboard/const/type"; +import { getTime, getTimeUnit, changeNumberUnit } from "../utils/dashboard"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import ScrollableSection from "@common/components/aoplatform/ScrollableSection"; import { RangeValue, TimeRange } from "@common/components/aoplatform/TimeRangeSelector"; import TimeRangeSelector from "@common/components/aoplatform/TimeRangeSelector"; import MonitorLineGraph from "./MonitorLineGraph"; import MonitorPieGraph from "./MonitorPieGraph"; -import { DefaultOptionType } from "antd/es/select"; import MonitorTable, { MonitorTableHandler } from "./MonitorTable"; import { CloseOutlined, ExpandOutlined, LoadingOutlined } from "@ant-design/icons"; -import DashboardDetail from "@core/pages/dashboard/DashboardDetail"; +import DashboardDetail from "@dashboard/pages/DashboardDetail"; dayjs.extend(customParseFormat); diff --git a/frontend/packages/common/src/const/dashboard/const.tsx b/frontend/packages/dashboard/src/const/const.tsx similarity index 100% rename from frontend/packages/common/src/const/dashboard/const.tsx rename to frontend/packages/dashboard/src/const/const.tsx diff --git a/frontend/packages/common/src/const/dashboard/type.ts b/frontend/packages/dashboard/src/const/type.ts similarity index 100% rename from frontend/packages/common/src/const/dashboard/type.ts rename to frontend/packages/dashboard/src/const/type.ts diff --git a/frontend/packages/core/src/pages/dashboard/Dashboard.tsx b/frontend/packages/dashboard/src/pages/Dashboard.tsx similarity index 100% rename from frontend/packages/core/src/pages/dashboard/Dashboard.tsx rename to frontend/packages/dashboard/src/pages/Dashboard.tsx diff --git a/frontend/packages/core/src/pages/dashboard/DashboardApiList.tsx b/frontend/packages/dashboard/src/pages/DashboardApiList.tsx similarity index 87% rename from frontend/packages/core/src/pages/dashboard/DashboardApiList.tsx rename to frontend/packages/dashboard/src/pages/DashboardApiList.tsx index bf3ea99..2f76f2b 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardApiList.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardApiList.tsx @@ -1,15 +1,15 @@ /* * @Date: 2024-03-14 10:55:47 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 19:07:23 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardApiList.tsx + * @LastEditTime: 2024-07-12 10:34:57 + * @FilePath: \frontend\packages\dashboard\src\pages\DashboardApiList.tsx */ import { useState } from "react"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; -import MonitorApiPage, { MonitorApiQueryData } from "@common/components/aoplatform/dashboard/MonitorApiPage"; +import MonitorApiPage, { MonitorApiQueryData } from "@dashboard/component/MonitorApiPage"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { SearchBody, MonitorApiData } from "@common/const/dashboard/type"; +import { SearchBody, MonitorApiData } from "@dashboard/const/type"; import { useFetch } from "@common/hooks/http"; import DashboardDetail from "./DashboardDetail"; import { TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; diff --git a/frontend/packages/core/src/pages/dashboard/DashboardApplicationList.tsx b/frontend/packages/dashboard/src/pages/DashboardApplicationList.tsx similarity index 80% rename from frontend/packages/core/src/pages/dashboard/DashboardApplicationList.tsx rename to frontend/packages/dashboard/src/pages/DashboardApplicationList.tsx index b5a9886..30b0c38 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardApplicationList.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardApplicationList.tsx @@ -1,23 +1,17 @@ /* * @Date: 2024-06-04 16:01:08 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 09:18:06 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardApplicationList.tsx - */ -/* - * @Date: 2024-06-04 08:54:16 - * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 14:52:44 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardProjectList.tsx + * @LastEditTime: 2024-07-12 10:35:02 + * @FilePath: \frontend\packages\dashboard\src\pages\DashboardApplicationList.tsx */ import { useState } from "react"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { SearchBody, MonitorSubscriberData } from "@common/const/dashboard/type"; +import { SearchBody, MonitorSubscriberData } from "@dashboard/const/type"; import { useFetch } from "@common/hooks/http"; -import { MonitorSubQueryData } from "@common/components/aoplatform/dashboard/MonitorSubPage"; -import MonitorAppPage from '@common/components/aoplatform/dashboard/MonitorAppPage' +import { MonitorSubQueryData } from "@dashboard/component/MonitorSubPage"; +import MonitorAppPage from '@dashboard/component/MonitorAppPage' import DashboardDetail from "./DashboardDetail"; import { TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; diff --git a/frontend/packages/core/src/pages/dashboard/DashboardDetail.tsx b/frontend/packages/dashboard/src/pages/DashboardDetail.tsx similarity index 91% rename from frontend/packages/core/src/pages/dashboard/DashboardDetail.tsx rename to frontend/packages/dashboard/src/pages/DashboardDetail.tsx index 82f049a..fda4681 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardDetail.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardDetail.tsx @@ -4,12 +4,12 @@ * @LastEditTime: 2024-06-04 10:31:47 * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardDetail.tsx */ -import MonitorDetailPage from "@common/components/aoplatform/dashboard/MonitorDetailPage" +import MonitorDetailPage from "../component/MonitorDetailPage" import { BasicResponse } from "@common/const/const" -import { SearchBody, MonitorApiData, InvokeData, MonitorSubscriberData } from "@common/const/dashboard/type" +import { SearchBody, MonitorApiData, InvokeData, MonitorSubscriberData } from "@dashboard/const/type" import { useFetch } from "@common/hooks/http" -import { MonitorApiQueryData } from "@common/components/aoplatform/dashboard/MonitorApiPage" -import { MonitorSubQueryData } from "@common/components/aoplatform/dashboard/MonitorSubPage" +import { MonitorApiQueryData } from "@dashboard/component/MonitorApiPage" +import { MonitorSubQueryData } from "@dashboard/component/MonitorSubPage" import { TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector" export type DashboardDetailInvokeType = { diff --git a/frontend/packages/core/src/pages/dashboard/DashboardInstruction.tsx b/frontend/packages/dashboard/src/pages/DashboardInstruction.tsx similarity index 80% rename from frontend/packages/core/src/pages/dashboard/DashboardInstruction.tsx rename to frontend/packages/dashboard/src/pages/DashboardInstruction.tsx index bf47856..16d5c5b 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardInstruction.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardInstruction.tsx @@ -10,16 +10,16 @@ export default function DashboardInstruction() { return (
-

分区配置并开启监控

-

监控功能用于辅助管理分区内信息,请选择或创建分区,设置监控信息后查看当前分区监控情况;

+

环境配置并开启监控

+

监控功能用于辅助管理环境内信息,请选择或创建环境,设置监控信息后查看当前环境监控情况;

{/*

更多配置问题,请点击帮助中心 {/* 查看更多 *

*/}
-

分区配置

-

新增分区的名称、描述和其他相关属性,并设置该分区内的集群地址,以确保监控系统能够正确识别和连接到这些集群

-

添加分区信息

+

环境配置

+

新增环境的名称、描述和其他相关属性,并设置该环境内的集群地址,以确保监控系统能够正确识别和连接到这些集群

+

添加环境信息

监控设置

diff --git a/frontend/packages/core/src/pages/dashboard/DashboardList.tsx b/frontend/packages/dashboard/src/pages/DashboardList.tsx similarity index 100% rename from frontend/packages/core/src/pages/dashboard/DashboardList.tsx rename to frontend/packages/dashboard/src/pages/DashboardList.tsx diff --git a/frontend/packages/core/src/pages/dashboard/DashboardProjectList.tsx b/frontend/packages/dashboard/src/pages/DashboardProjectList.tsx similarity index 82% rename from frontend/packages/core/src/pages/dashboard/DashboardProjectList.tsx rename to frontend/packages/dashboard/src/pages/DashboardProjectList.tsx index 7713c12..f7d664b 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardProjectList.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardProjectList.tsx @@ -1,22 +1,16 @@ /* * @Date: 2024-06-04 16:01:08 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 19:07:12 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardProjectList.tsx - */ -/* - * @Date: 2024-06-04 08:54:16 - * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-04 14:52:44 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardProjectList.tsx + * @LastEditTime: 2024-07-12 10:35:00 + * @FilePath: \frontend\packages\dashboard\src\pages\DashboardProjectList.tsx */ import { useState } from "react"; import { useParams } from "react-router-dom"; import { RouterParams } from "@core/components/aoplatform/RenderRoutes"; import { BasicResponse, STATUS_CODE } from "@common/const/const"; -import { SearchBody, MonitorSubscriberData } from "@common/const/dashboard/type"; +import { SearchBody, MonitorSubscriberData } from "@dashboard/const/type"; import { useFetch } from "@common/hooks/http"; -import MonitorSubPage, { MonitorSubQueryData } from "@common/components/aoplatform/dashboard/MonitorSubPage"; +import MonitorSubPage, { MonitorSubQueryData } from "@dashboard/component/MonitorSubPage"; import DashboardDetail from "./DashboardDetail"; import { TimeRangeButton } from "@common/components/aoplatform/TimeRangeSelector"; diff --git a/frontend/packages/core/src/pages/dashboard/DashboardTabPage.tsx b/frontend/packages/dashboard/src/pages/DashboardTabPage.tsx similarity index 100% rename from frontend/packages/core/src/pages/dashboard/DashboardTabPage.tsx rename to frontend/packages/dashboard/src/pages/DashboardTabPage.tsx diff --git a/frontend/packages/core/src/pages/dashboard/DashboardTotal.tsx b/frontend/packages/dashboard/src/pages/DashboardTotal.tsx similarity index 91% rename from frontend/packages/core/src/pages/dashboard/DashboardTotal.tsx rename to frontend/packages/dashboard/src/pages/DashboardTotal.tsx index d446402..dc86a28 100644 --- a/frontend/packages/core/src/pages/dashboard/DashboardTotal.tsx +++ b/frontend/packages/dashboard/src/pages/DashboardTotal.tsx @@ -1,15 +1,15 @@ /* * @Date: 2024-02-27 11:51:23 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-07 10:10:40 - * @FilePath: \frontend\packages\core\src\pages\dashboard\DashboardTotal.tsx + * @LastEditTime: 2024-07-12 10:35:05 + * @FilePath: \frontend\packages\dashboard\src\pages\DashboardTotal.tsx */ import { useNavigate, useParams } from "react-router-dom" import { RouterParams } from "@core/components/aoplatform/RenderRoutes" -import MonitorTotalPage from "@common/components/aoplatform/dashboard/MonitorTotalPage" +import MonitorTotalPage from "@dashboard/component/MonitorTotalPage" import { BasicResponse } from "@common/const/const" -import { InvokeData, MessageData, MonitorApiData, MonitorSubscriberData, PieData, SearchBody } from "@common/const/dashboard/type" +import { InvokeData, MessageData, MonitorApiData, MonitorSubscriberData, PieData, SearchBody } from "@dashboard/const/type" import { useFetch } from "@common/hooks/http" import { objectToSearchParameters } from "@common/utils/router" import { useEffect } from "react" diff --git a/frontend/packages/common/src/utils/dashboard.ts b/frontend/packages/dashboard/src/utils/dashboard.ts similarity index 100% rename from frontend/packages/common/src/utils/dashboard.ts rename to frontend/packages/dashboard/src/utils/dashboard.ts diff --git a/frontend/packages/dashboard/tailwind.config.js b/frontend/packages/dashboard/tailwind.config.js new file mode 100644 index 0000000..e53065a --- /dev/null +++ b/frontend/packages/dashboard/tailwind.config.js @@ -0,0 +1,86 @@ +/* + * @Date: 2023-11-27 17:31:44 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:36:11 + * @FilePath: \frontend\packages\market\tailwind.config.js + */ +/** @type {import('tailwindcss').Config} */ + +export default { + important:true, + content: [ + `./index.html`, + `../*/src/**/*.{js,ts,jsx,tsx}`, + ], + theme: { + extend: { + width: { + INPUT_NORMAL: '100%', + // INPUT_NORMAL: '346px', + INPUT_LARGE: '508px', + GROUP: '240px', + SEARCH: '276px', + LOG: '254px' + }, + minHeight:{ + TEXTAREA:'68px' + }, + borderRadius: { + DEFAULT: 'var(--border-radius)', + SEARCH_RADIUS: '50px' + }, + boxShadow:{ + SCROLL: '0 2px 2px #0000000d', + SCROLL_TOP:' 0 -2px 2px -2px var(--border-color)' + }, + colors: { + DISABLE_BG: 'var(--disabled-background-color)', + MAIN_TEXT: 'var(--text-color)', + MAIN_HOVER_TEXT: 'var(--text-hover-color)', + SECOND_TEXT:'var(--disabled-text-color)', + MAIN_BG: 'var(--background-color)', + MENU_BG:'var(--MENU-BG-COLOR)', + 'bar-theme': 'var(--bar-background-color)', + BORDER: 'var(--border-color)', + NAVBAR_BTN_BG: 'var(--item-active-background-color)', + MAIN_DISABLED_BG: 'var(--disabled-background-color)', + theme: 'var(--primary-color)', + DESC_TEXT: 'var(--TITLE_TEXT)', + HOVER_BG: 'var(--item-hover-background-color)', + guide_cluster: '#ee6760', + guide_upstream: '#f9a429', + guide_api: '#71d24d', + guide_publishApi: '#5884ff', + guide_final: '#915bf9', + table_text: 'var(--table-text-color)', + status_success:'#138913', + status_fail:"#ff3b30", + status_update:"#03a9f4", + status_pending:"#ffa500", + status_offline:"#8f8e93", + A_HOVER:'var(--button-primary-hover-background-color)' + }, + spacing: { + mbase: 'var(--FORM_SPAN)', + label: '12px', // 选择器和label之间的间距,待删 + btnbase: 'var(--LAYOUT_MARGIN)', // x方向的间距 + btnybase: 'var(--LAYOUT_MARGIN)', // y轴方向的间距 + btnrbase: '20px', // 页面最右侧边距20px + formtop: 'var(--FORM_SPAN)', + icon: '5px', + blockbase: '40px', + DEFAULT_BORDER_RADIUS: 'var(--border-radius)', + TREE_TITLE:'var(--small-padding) var(--LAYOUT_PADDING);' + }, + borderColor: { + 'color-base': 'var(--border-color)' + } + } + }, + plugins: [], + corePlugins: { + preflight: false, + }, + } + + \ No newline at end of file diff --git a/frontend/packages/dashboard/tsconfig.json b/frontend/packages/dashboard/tsconfig.json new file mode 100644 index 0000000..3dbba79 --- /dev/null +++ b/frontend/packages/dashboard/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "paths": { + "@common/*": ["../common/src/*"], + "@core/*": ["../core/src/*"], + "@dashboard/*": ["./src/*"] + }, + }, + "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/frontend/packages/dashboard/tsconfig.node.json b/frontend/packages/dashboard/tsconfig.node.json new file mode 100644 index 0000000..42872c5 --- /dev/null +++ b/frontend/packages/dashboard/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/packages/market/src/const/serviceHub/const.tsx b/frontend/packages/market/src/const/serviceHub/const.tsx index 6705e76..ed36ec8 100644 --- a/frontend/packages/market/src/const/serviceHub/const.tsx +++ b/frontend/packages/market/src/const/serviceHub/const.tsx @@ -61,7 +61,7 @@ export const SERVICE_HUB_TABLE_COLUMNS: ProColumns[] = ellipsis:true }, { - title: '可用分区', + title: '可用环境', dataIndex: 'partition', ellipsis:true, renderText:(_,entity:ServiceHubTableListItem)=>entity.partition?.map((x)=>x.name).join(',') diff --git a/frontend/packages/market/src/pages/serviceHub/ApplyServiceModal.tsx b/frontend/packages/market/src/pages/serviceHub/ApplyServiceModal.tsx index 6bed81e..4989d30 100644 --- a/frontend/packages/market/src/pages/serviceHub/ApplyServiceModal.tsx +++ b/frontend/packages/market/src/pages/serviceHub/ApplyServiceModal.tsx @@ -84,7 +84,7 @@ export const ApplyServiceModal = forwardRef{entity.project.name} - label="申请的分区" + label="申请的环境" name="partitions" rules={[{ required: true, message: '必填项' }]} > diff --git a/frontend/packages/market/src/pages/serviceHub/ServiceHubGroup.tsx b/frontend/packages/market/src/pages/serviceHub/ServiceHubGroup.tsx index cc40ce5..8d3f1b0 100644 --- a/frontend/packages/market/src/pages/serviceHub/ServiceHubGroup.tsx +++ b/frontend/packages/market/src/pages/serviceHub/ServiceHubGroup.tsx @@ -142,7 +142,7 @@ export const ServiceHubGroup = ({children,filterOption,dispatch}:ServiceHubGroup
-

分区

+

环境

TODO: description + +## Usage + +``` +const common = require('common'); + +// TODO: DEMONSTRATE API +``` diff --git a/frontend/packages/openApi/__tests__/openApi.test.js b/frontend/packages/openApi/__tests__/openApi.test.js new file mode 100644 index 0000000..61028bb --- /dev/null +++ b/frontend/packages/openApi/__tests__/openApi.test.js @@ -0,0 +1,7 @@ +'use strict'; + +const openApi = require('..'); +const assert = require('assert').strict; + +assert.strictEqual(openApi(), 'Hello from openApi'); +console.info('openApi tests passed'); diff --git a/frontend/packages/openApi/package.json b/frontend/packages/openApi/package.json new file mode 100644 index 0000000..3bb59ab --- /dev/null +++ b/frontend/packages/openApi/package.json @@ -0,0 +1,15 @@ +{ + "name": "open-api", + "version": "0.0.0", + "description": "openApi module", + "scripts": { + "dev": "vite", + "build": "vite build", + "test": "node ./__tests__/common.test.js" + }, + "dependencies": { + "copy-to-clipboard": "^3.3.3" + }, + "devDependencies": { + } +} diff --git a/frontend/packages/openApi/postcss.config.js b/frontend/packages/openApi/postcss.config.js new file mode 100644 index 0000000..8039309 --- /dev/null +++ b/frontend/packages/openApi/postcss.config.js @@ -0,0 +1,15 @@ +/* + * @Date: 2023-11-27 17:31:54 + * @LastEditors: maggieyyy + * @LastEditTime: 2023-11-29 15:49:05 + * @FilePath: \applatform\frontend\packages\core\postcss.config.js + */ +export default { + plugins: { + 'postcss-import': {}, + 'tailwindcss/nesting': {}, + tailwindcss: {}, + autoprefixer: {} + }, + } + \ No newline at end of file diff --git a/frontend/packages/core/src/pages/openApi/OpenApiConfig.tsx b/frontend/packages/openApi/src/pages/OpenApiConfig.tsx similarity index 100% rename from frontend/packages/core/src/pages/openApi/OpenApiConfig.tsx rename to frontend/packages/openApi/src/pages/OpenApiConfig.tsx diff --git a/frontend/packages/core/src/pages/openApi/OpenApiList.tsx b/frontend/packages/openApi/src/pages/OpenApiList.tsx similarity index 97% rename from frontend/packages/core/src/pages/openApi/OpenApiList.tsx rename to frontend/packages/openApi/src/pages/OpenApiList.tsx index c1df89c..d8d6624 100644 --- a/frontend/packages/core/src/pages/openApi/OpenApiList.tsx +++ b/frontend/packages/openApi/src/pages/OpenApiList.tsx @@ -8,8 +8,9 @@ import {useFetch} from "@common/hooks/http.ts"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; import {OpenApiConfig, OpenApiConfigFieldType, OpenApiConfigHandle} from "./OpenApiConfig.tsx"; import { EntityItem } from "@common/const/type.ts"; -import { SimpleMemberItem } from "../../const/system/type.ts"; +import { SimpleMemberItem } from "@common/const/type.ts"; import TableBtnWithPermission from "@common/components/aoplatform/TableBtnWithPermission.tsx"; +import { frontendTimeSorter } from "@common/utils/dataTransfer.ts"; type OpenApiTableListItem = { id:string; @@ -60,15 +61,12 @@ const OPENAPI_LIST_COLUMNS: ProColumns[] = [ }, { title: '更新时间', - width:176, + width:182, dataIndex: 'updateTime', sorter: (a,b)=>(new Date(a.updateTime)).getTime() - (new Date(b.updateTime)).getTime() } ]; -export const frontendTimeSorter = (a:{[k:string]:string},b: { [k: string]: string }, field:string) =>{ - return (new Date((a)[field])).getTime() - (new Date((b)[field])).getTime() -} export default function OpenApiList(){ const { modal,message } = App.useApp() diff --git a/frontend/packages/openApi/tailwind.config.js b/frontend/packages/openApi/tailwind.config.js new file mode 100644 index 0000000..e53065a --- /dev/null +++ b/frontend/packages/openApi/tailwind.config.js @@ -0,0 +1,86 @@ +/* + * @Date: 2023-11-27 17:31:44 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:36:11 + * @FilePath: \frontend\packages\market\tailwind.config.js + */ +/** @type {import('tailwindcss').Config} */ + +export default { + important:true, + content: [ + `./index.html`, + `../*/src/**/*.{js,ts,jsx,tsx}`, + ], + theme: { + extend: { + width: { + INPUT_NORMAL: '100%', + // INPUT_NORMAL: '346px', + INPUT_LARGE: '508px', + GROUP: '240px', + SEARCH: '276px', + LOG: '254px' + }, + minHeight:{ + TEXTAREA:'68px' + }, + borderRadius: { + DEFAULT: 'var(--border-radius)', + SEARCH_RADIUS: '50px' + }, + boxShadow:{ + SCROLL: '0 2px 2px #0000000d', + SCROLL_TOP:' 0 -2px 2px -2px var(--border-color)' + }, + colors: { + DISABLE_BG: 'var(--disabled-background-color)', + MAIN_TEXT: 'var(--text-color)', + MAIN_HOVER_TEXT: 'var(--text-hover-color)', + SECOND_TEXT:'var(--disabled-text-color)', + MAIN_BG: 'var(--background-color)', + MENU_BG:'var(--MENU-BG-COLOR)', + 'bar-theme': 'var(--bar-background-color)', + BORDER: 'var(--border-color)', + NAVBAR_BTN_BG: 'var(--item-active-background-color)', + MAIN_DISABLED_BG: 'var(--disabled-background-color)', + theme: 'var(--primary-color)', + DESC_TEXT: 'var(--TITLE_TEXT)', + HOVER_BG: 'var(--item-hover-background-color)', + guide_cluster: '#ee6760', + guide_upstream: '#f9a429', + guide_api: '#71d24d', + guide_publishApi: '#5884ff', + guide_final: '#915bf9', + table_text: 'var(--table-text-color)', + status_success:'#138913', + status_fail:"#ff3b30", + status_update:"#03a9f4", + status_pending:"#ffa500", + status_offline:"#8f8e93", + A_HOVER:'var(--button-primary-hover-background-color)' + }, + spacing: { + mbase: 'var(--FORM_SPAN)', + label: '12px', // 选择器和label之间的间距,待删 + btnbase: 'var(--LAYOUT_MARGIN)', // x方向的间距 + btnybase: 'var(--LAYOUT_MARGIN)', // y轴方向的间距 + btnrbase: '20px', // 页面最右侧边距20px + formtop: 'var(--FORM_SPAN)', + icon: '5px', + blockbase: '40px', + DEFAULT_BORDER_RADIUS: 'var(--border-radius)', + TREE_TITLE:'var(--small-padding) var(--LAYOUT_PADDING);' + }, + borderColor: { + 'color-base': 'var(--border-color)' + } + } + }, + plugins: [], + corePlugins: { + preflight: false, + }, + } + + \ No newline at end of file diff --git a/frontend/packages/openApi/tsconfig.json b/frontend/packages/openApi/tsconfig.json new file mode 100644 index 0000000..61db1ea --- /dev/null +++ b/frontend/packages/openApi/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "paths": { + "@common/*": ["../common/src/*"], + "@core/*": ["../core/src/*"], + "@market/*": ["./src/*"] + }, + }, + "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/frontend/packages/openApi/tsconfig.node.json b/frontend/packages/openApi/tsconfig.node.json new file mode 100644 index 0000000..42872c5 --- /dev/null +++ b/frontend/packages/openApi/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/frontend/packages/systemRunning/README.md b/frontend/packages/systemRunning/README.md new file mode 100644 index 0000000..631a11f --- /dev/null +++ b/frontend/packages/systemRunning/README.md @@ -0,0 +1,11 @@ +# `systemRunning` + +> TODO: description + +## Usage + +``` +const systemRunning = require('systemRunning'); + +// TODO: DEMONSTRATE API +``` diff --git a/frontend/packages/systemRunning/__tests__/systemRunning.test.js b/frontend/packages/systemRunning/__tests__/systemRunning.test.js new file mode 100644 index 0000000..3d25b66 --- /dev/null +++ b/frontend/packages/systemRunning/__tests__/systemRunning.test.js @@ -0,0 +1,7 @@ +'use strict'; + +const systemRunning = require('..'); +const assert = require('assert').strict; + +assert.strictEqual(systemRunning(), 'Hello from systemRunning'); +console.info('systemRunning tests passed'); diff --git a/frontend/packages/systemRunning/package.json b/frontend/packages/systemRunning/package.json new file mode 100644 index 0000000..0bc1781 --- /dev/null +++ b/frontend/packages/systemRunning/package.json @@ -0,0 +1,8 @@ +{ + "name": "systemrunning", + "version": "1.0.0", + "description": "> TODO: description", + "author": "maggieyyy <61950669+maggieyyy@users.noreply.github.com>", + "homepage": "", + "license": "ISC" +} diff --git a/frontend/packages/systemRunning/postcss.config.js b/frontend/packages/systemRunning/postcss.config.js new file mode 100644 index 0000000..8039309 --- /dev/null +++ b/frontend/packages/systemRunning/postcss.config.js @@ -0,0 +1,15 @@ +/* + * @Date: 2023-11-27 17:31:54 + * @LastEditors: maggieyyy + * @LastEditTime: 2023-11-29 15:49:05 + * @FilePath: \applatform\frontend\packages\core\postcss.config.js + */ +export default { + plugins: { + 'postcss-import': {}, + 'tailwindcss/nesting': {}, + tailwindcss: {}, + autoprefixer: {} + }, + } + \ No newline at end of file diff --git a/frontend/packages/core/src/pages/systemRunning/SystemRunning.tsx b/frontend/packages/systemRunning/src/pages/SystemRunning.tsx similarity index 98% rename from frontend/packages/core/src/pages/systemRunning/SystemRunning.tsx rename to frontend/packages/systemRunning/src/pages/SystemRunning.tsx index 59f99e0..3f9a793 100644 --- a/frontend/packages/core/src/pages/systemRunning/SystemRunning.tsx +++ b/frontend/packages/systemRunning/src/pages/SystemRunning.tsx @@ -1,8 +1,8 @@ /* * @Date: 2024-03-15 10:53:52 * @LastEditors: maggieyyy - * @LastEditTime: 2024-06-06 18:46:24 - * @FilePath: \frontend\packages\core\src\pages\systemRunning\SystemRunning.tsx + * @LastEditTime: 2024-07-12 20:01:30 + * @FilePath: \frontend\packages\systemRunning\src\pages\SystemRunning.tsx */ import { useRef, useState, useEffect, useCallback } from "react"; @@ -13,9 +13,9 @@ import { App, Button, Spin, Tooltip } from "antd"; import { debounce } from "lodash-es"; import { LoadingOutlined, ZoomInOutlined, ZoomOutOutlined } from "@ant-design/icons"; import G6, { Graph, registerEdge, Item } from "@antv/g6"; -import { PictureTypeEnum, NodeClickItem, GraphData } from "../../const/system-running/type.ts"; +import { PictureTypeEnum, NodeClickItem, GraphData } from "@core/const/system-running/type.ts"; import { UnionFind, edgesFormatter, getNodeSpacing, nodesFormatter } from "@common/utils/systemRunning.ts"; -import { EDGE_STYLE, END_ARROW_STYLE, OUT_SPACE_CONTENT_EDGE_COLOR, RELATIVE_PICTURE_NODE_FONTSIZE, SELF_SPACE_CONTENT_EDGE_COLOR, SYSTEM_TUNNING_CONFIG } from "../../const/system-running/const.ts"; +import { EDGE_STYLE, END_ARROW_STYLE, OUT_SPACE_CONTENT_EDGE_COLOR, RELATIVE_PICTURE_NODE_FONTSIZE, SELF_SPACE_CONTENT_EDGE_COLOR, SYSTEM_TUNNING_CONFIG } from "@core/const/system-running/const.ts"; import ReactDOM from "react-dom"; import {BasicResponse, STATUS_CODE} from "@common/const/const.ts"; import SystemRunningInstruction from "./SystemRunningInstruction.tsx"; diff --git a/frontend/packages/core/src/pages/systemRunning/SystemRunningInstruction.tsx b/frontend/packages/systemRunning/src/pages/SystemRunningInstruction.tsx similarity index 100% rename from frontend/packages/core/src/pages/systemRunning/SystemRunningInstruction.tsx rename to frontend/packages/systemRunning/src/pages/SystemRunningInstruction.tsx diff --git a/frontend/packages/systemRunning/tailwind.config.js b/frontend/packages/systemRunning/tailwind.config.js new file mode 100644 index 0000000..e53065a --- /dev/null +++ b/frontend/packages/systemRunning/tailwind.config.js @@ -0,0 +1,86 @@ +/* + * @Date: 2023-11-27 17:31:44 + * @LastEditors: maggieyyy + * @LastEditTime: 2024-06-05 10:36:11 + * @FilePath: \frontend\packages\market\tailwind.config.js + */ +/** @type {import('tailwindcss').Config} */ + +export default { + important:true, + content: [ + `./index.html`, + `../*/src/**/*.{js,ts,jsx,tsx}`, + ], + theme: { + extend: { + width: { + INPUT_NORMAL: '100%', + // INPUT_NORMAL: '346px', + INPUT_LARGE: '508px', + GROUP: '240px', + SEARCH: '276px', + LOG: '254px' + }, + minHeight:{ + TEXTAREA:'68px' + }, + borderRadius: { + DEFAULT: 'var(--border-radius)', + SEARCH_RADIUS: '50px' + }, + boxShadow:{ + SCROLL: '0 2px 2px #0000000d', + SCROLL_TOP:' 0 -2px 2px -2px var(--border-color)' + }, + colors: { + DISABLE_BG: 'var(--disabled-background-color)', + MAIN_TEXT: 'var(--text-color)', + MAIN_HOVER_TEXT: 'var(--text-hover-color)', + SECOND_TEXT:'var(--disabled-text-color)', + MAIN_BG: 'var(--background-color)', + MENU_BG:'var(--MENU-BG-COLOR)', + 'bar-theme': 'var(--bar-background-color)', + BORDER: 'var(--border-color)', + NAVBAR_BTN_BG: 'var(--item-active-background-color)', + MAIN_DISABLED_BG: 'var(--disabled-background-color)', + theme: 'var(--primary-color)', + DESC_TEXT: 'var(--TITLE_TEXT)', + HOVER_BG: 'var(--item-hover-background-color)', + guide_cluster: '#ee6760', + guide_upstream: '#f9a429', + guide_api: '#71d24d', + guide_publishApi: '#5884ff', + guide_final: '#915bf9', + table_text: 'var(--table-text-color)', + status_success:'#138913', + status_fail:"#ff3b30", + status_update:"#03a9f4", + status_pending:"#ffa500", + status_offline:"#8f8e93", + A_HOVER:'var(--button-primary-hover-background-color)' + }, + spacing: { + mbase: 'var(--FORM_SPAN)', + label: '12px', // 选择器和label之间的间距,待删 + btnbase: 'var(--LAYOUT_MARGIN)', // x方向的间距 + btnybase: 'var(--LAYOUT_MARGIN)', // y轴方向的间距 + btnrbase: '20px', // 页面最右侧边距20px + formtop: 'var(--FORM_SPAN)', + icon: '5px', + blockbase: '40px', + DEFAULT_BORDER_RADIUS: 'var(--border-radius)', + TREE_TITLE:'var(--small-padding) var(--LAYOUT_PADDING);' + }, + borderColor: { + 'color-base': 'var(--border-color)' + } + } + }, + plugins: [], + corePlugins: { + preflight: false, + }, + } + + \ No newline at end of file diff --git a/frontend/packages/systemRunning/tsconfig.json b/frontend/packages/systemRunning/tsconfig.json new file mode 100644 index 0000000..7c6fbbf --- /dev/null +++ b/frontend/packages/systemRunning/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + /* Linting */ + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "paths": { + "@common/*": ["../common/src/*"], + "@core/*": ["../core/src/*"], + }, + }, + "include": ["src", "public/iconpark_eolink.js", "public/iconpark_apinto.js", "../common/src/component/aoplatform/EditableTableWithModal.tsx", "../common/src/components/aoplatform/TransferTable.tsx", "../common/src/components/aoplatform/TreeWithMore.tsx", "../common/src/components/aoplatform/DatePicker.tsx", "../common/src/components/aoplatform/TimeRangeSelector.tsx", "../common/src/components/aoplatform/TimePicker.tsx", "../common/src/components/aoplatform/MemberTransfer.tsx", "../common/src/components/aoplatform/Navigation.tsx", "../common/src/components/aoplatform/PageList.tsx", "../common/src/components/aoplatform/GroupTree.tsx", "../common/src/components/aoplatform/ErrorBoundary.tsx", "../core/src/pages/serviceCategory/ServiceHubCategoryConfig.tsx"], + "references": [{ "path": "./tsconfig.node.json" }] +} diff --git a/frontend/packages/systemRunning/tsconfig.node.json b/frontend/packages/systemRunning/tsconfig.node.json new file mode 100644 index 0000000..42872c5 --- /dev/null +++ b/frontend/packages/systemRunning/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "composite": true, + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/gateway/handler.go b/gateway/handler.go index 2ef6b41..839953d 100644 --- a/gateway/handler.go +++ b/gateway/handler.go @@ -15,29 +15,19 @@ func RegisterInitHandleFunc(handleFunc InitHandleFunc) { initHandlers = append(initHandlers, handleFunc) } -type InitHandleFunc func(ctx context.Context, partitionId string, client IClientDriver) error +type InitHandleFunc func(ctx context.Context, clusterId string, client IClientDriver) error -func (f InitHandleFunc) Init(ctx context.Context, partitionId string, client IClientDriver) error { - return f(ctx, partitionId, client) +func (f InitHandleFunc) Init(ctx context.Context, clusterId string, client IClientDriver) error { + return f(ctx, clusterId, client) } type InitHandler interface { - Init(ctx context.Context, partitionId string, client IClientDriver) error + Init(ctx context.Context, clusterId string, client IClientDriver) error } -func InitGateway(ctx context.Context, partitionId string, client IClientDriver) (err error) { - //defer func() { - // if err == nil { - // err = client.Commit(ctx) - // } else { - // errRollback := client.Rollback(ctx) - // if errRollback != nil { - // log.Warn(err) - // } - // } - //}() +func InitGateway(ctx context.Context, clusterId string, client IClientDriver) (err error) { for _, h := range initHandlers { - err = h.Init(ctx, partitionId, client) + err = h.Init(ctx, clusterId, client) if err != nil { return } diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index c2c1767..0e5280f 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -9,15 +9,14 @@ type Item struct { } type ServiceItem struct { - Id string `json:"id"` - Name string `json:"name"` - Tags []auto.Label `json:"tags" aolabel:"tag"` - Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` - //Partition []auto.Label `json:"partition" aolabel:"partition"` - Description string `json:"description"` - Logo string `json:"logo"` - ApiNum int64 `json:"api_num"` - SubscriberNum int64 `json:"subscriber_num"` + Id string `json:"id"` + Name string `json:"name"` + Tags []auto.Label `json:"tags" aolabel:"tag"` + Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` + Description string `json:"description"` + Logo string `json:"logo"` + ApiNum int64 `json:"api_num"` + SubscriberNum int64 `json:"subscriber_num"` } type ServiceDetail struct { @@ -27,11 +26,9 @@ type ServiceDetail struct { Basic *ServiceBasic `json:"basic"` Apis []*ServiceApi `json:"apis"` DisableApis []*ServiceApiBasic `json:"disable_apis"` - Partition []*Partition `json:"partition"` } type ServiceBasic struct { - //Organization auto.Label `json:"organization" aolabel:"organization"` Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` ApiNum int `json:"api_num"` diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index af1933e..3854052 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -8,8 +8,6 @@ import ( "math" "sort" - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/apipark/service/project" "github.com/eolinker/apipark/service/subscribe" @@ -54,7 +52,6 @@ type imlCatalogueModule struct { releaseService release.IReleaseService `autowired:""` subscribeService subscribe.ISubscribeService `autowired:""` subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - partitionService partition.IPartitionService `autowired:""` transaction store.ITransaction `autowired:""` root *Root @@ -175,18 +172,6 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca docStr = doc.Doc } - globalPartitions, err := i.partitionService.List(ctx) - if err != nil { - return nil, err - } - - partitions := utils.SliceToSlice(globalPartitions, func(t *partition.Partition) *catalogue_dto.Partition { - return &catalogue_dto.Partition{ - Id: t.UUID, - Name: t.Name, - Prefix: t.Prefix, - } - }) r, err := i.releaseService.GetRunning(ctx, s.Project) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { @@ -199,7 +184,6 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Team: auto.UUID(s.Team), ApiNum: 0, }, - Partition: partitions, }, nil } @@ -282,8 +266,7 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca ApiNum: len(apis), SubscriberNum: subscribeCount[s.Id], }, - Apis: apis, - Partition: partitions, + Apis: apis, }, nil } @@ -336,7 +319,7 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c Name: v.Name, Tags: auto.List(serviceTagMap[v.Id]), Catalogue: auto.UUID(v.Catalogue), - //Partition: auto.List(ps), + //Cluster: auto.List(ps), ApiNum: apiNum, SubscriberNum: subscribeCount[v.Id], Description: v.Description, diff --git a/module/certificate/certificate.go b/module/certificate/certificate.go index 2d5088a..726f4a1 100644 --- a/module/certificate/certificate.go +++ b/module/certificate/certificate.go @@ -11,9 +11,9 @@ import ( ) type ICertificateModule interface { - Create(ctx context.Context, partitionId string, create *certificate_dto.FileInput) error + Create(ctx context.Context, clusterId string, create *certificate_dto.FileInput) error Update(ctx context.Context, id string, edit *certificate_dto.FileInput) error - ListForPartition(ctx context.Context, partitionId string) ([]*certificate_dto.Certificate, error) + List(ctx context.Context, clusterId string) ([]*certificate_dto.Certificate, error) Detail(ctx context.Context, id string) (*certificate_dto.Certificate, *certificate_dto.File, error) Delete(ctx context.Context, id string) error } diff --git a/module/certificate/dto/dto.go b/module/certificate/dto/dto.go index a13b201..4c9f9b5 100644 --- a/module/certificate/dto/dto.go +++ b/module/certificate/dto/dto.go @@ -21,7 +21,7 @@ func FromModel(c *certificate.Certificate) *Certificate { Id: c.ID, Name: c.Name, Domains: c.Domains, - Partition: c.Partition, + Partition: c.Cluster, NotBefore: auto.TimeLabel(c.NotBefore), NotAfter: auto.TimeLabel(c.NotAfter), Updater: auto.UUID(c.Updater), diff --git a/module/certificate/impl.go b/module/certificate/impl.go index 9778c02..e3b978e 100644 --- a/module/certificate/impl.go +++ b/module/certificate/impl.go @@ -5,14 +5,13 @@ import ( "encoding/base64" "errors" "fmt" + "time" + "github.com/eolinker/eosc/log" "gorm.io/gorm" - "time" "github.com/eolinker/apipark/gateway" - "github.com/eolinker/apipark/service/partition" - "github.com/google/uuid" "github.com/eolinker/apipark/service/cluster" @@ -29,15 +28,14 @@ var ( ) type imlCertificate struct { - service certificate.ICertificateService `autowired:""` - userInfoService account.IAccountService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - transaction store.ITransaction `autowired:""` + service certificate.ICertificateService `autowired:""` + userInfoService account.IAccountService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + transaction store.ITransaction `autowired:""` } -func (m *imlCertificate) getCertificates(ctx context.Context, partitionId string) ([]*gateway.DynamicRelease, error) { - certs, err := m.service.List(ctx, partitionId) +func (m *imlCertificate) getCertificates(ctx context.Context, clusterId string) ([]*gateway.DynamicRelease, error) { + certs, err := m.service.List(ctx, clusterId) if err != nil { return nil, err } @@ -65,12 +63,12 @@ func (m *imlCertificate) getCertificates(ctx context.Context, partitionId string return publishCerts, nil } -func (m *imlCertificate) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { +func (m *imlCertificate) initGateway(ctx context.Context, clusterId string, clientDriver gateway.IClientDriver) error { certificateClient, err := clientDriver.Dynamic("certificate") if err != nil { return err } - certs, err := m.getCertificates(ctx, partitionId) + certs, err := m.getCertificates(ctx, clusterId) if err != nil { return err } @@ -117,38 +115,29 @@ func (m *imlCertificate) syncGateway(ctx context.Context, clusterId string, rele return dynamicClient.Offline(ctx, releaseInfo) } -func (m *imlCertificate) Create(ctx context.Context, partitionId string, create *certificatedto.FileInput) error { - _, err := m.partitionService.Get(ctx, partitionId) - if err != nil { - return err - } - clusters, err := m.clusterService.ListByClusters(ctx, partitionId) - if err != nil { - return err - } +func (m *imlCertificate) Create(ctx context.Context, clusterId string, create *certificatedto.FileInput) error { + return m.transaction.Transaction(ctx, func(ctx context.Context) error { id := uuid.New().String() version := time.Now().Format("20060102150405") - for _, c := range clusters { - err = m.syncGateway(ctx, c.Uuid, &gateway.DynamicRelease{ - BasicItem: &gateway.BasicItem{ - ID: id, - Description: "", - Version: version, - MatchLabels: map[string]string{ - "module": "certificate", - }, - }, - Attr: map[string]interface{}{ - "key": create.Key, - "pem": create.Cert, + err := m.syncGateway(ctx, clusterId, &gateway.DynamicRelease{ + BasicItem: &gateway.BasicItem{ + ID: id, + Description: "", + Version: version, + MatchLabels: map[string]string{ + "module": "certificate", }, - }, true) - if err != nil { - return err - } + }, + Attr: map[string]interface{}{ + "key": create.Key, + "pem": create.Cert, + }, + }, true) + if err != nil { + return err } - _, err = m.save(ctx, id, partitionId, create) + _, err = m.save(ctx, id, clusterId, create) if err != nil { return err } @@ -162,7 +151,7 @@ func (m *imlCertificate) Update(ctx context.Context, id string, edit *certificat if err != nil { return err } - clusters, err := m.clusterService.ListByClusters(ctx, old.Partition) + clusters, err := m.clusterService.ListByClusters(ctx, old.Cluster) if err != nil { return err } @@ -187,15 +176,15 @@ func (m *imlCertificate) Update(ctx context.Context, id string, edit *certificat return err } } - _, err = m.save(ctx, id, old.Partition, edit) + _, err = m.save(ctx, id, old.Cluster, edit) if err != nil { return err } return nil }) } -func (m *imlCertificate) ListForPartition(ctx context.Context, partitionId string) ([]*certificatedto.Certificate, error) { - certs, err := m.service.List(ctx, partitionId) +func (m *imlCertificate) List(ctx context.Context, clusterId string) ([]*certificatedto.Certificate, error) { + certs, err := m.service.List(ctx, clusterId) if err != nil { return nil, err } @@ -223,7 +212,7 @@ func (m *imlCertificate) Delete(ctx context.Context, id string) error { } return err } - clusters, err := m.clusterService.ListByClusters(ctx, cert.Partition) + clusters, err := m.clusterService.ListByClusters(ctx, cert.Cluster) if err != nil { return err } diff --git a/module/cluster/cluster.go b/module/cluster/cluster.go new file mode 100644 index 0000000..37abdbb --- /dev/null +++ b/module/cluster/cluster.go @@ -0,0 +1,21 @@ +package cluster + +import ( + "context" + "reflect" + + cluster_dto "github.com/eolinker/apipark/module/cluster/dto" + "github.com/eolinker/go-common/autowire" +) + +type IClusterModule interface { + CheckCluster(ctx context.Context, address ...string) ([]*cluster_dto.Node, error) + ResetCluster(ctx context.Context, clusterId string, address string) ([]*cluster_dto.Node, error) + ClusterNodes(ctx context.Context, clusterId string) ([]*cluster_dto.Node, error) +} + +func init() { + autowire.Auto[IClusterModule](func() reflect.Value { + return reflect.ValueOf(new(imlClusterModule)) + }) +} diff --git a/module/cluster/dto/input.go b/module/cluster/dto/input.go new file mode 100644 index 0000000..9d69052 --- /dev/null +++ b/module/cluster/dto/input.go @@ -0,0 +1,40 @@ +package cluster_dto + +//type Create struct { +// Id string `json:"id,omitempty"` +// Name string `json:"name,omitempty"` +// Description string `json:"description,omitempty"` +// Prefix string `json:"prefix,omitempty"` +// Url string `json:"url,omitempty"` +// ManagerAddress string `json:"manager_address,omitempty"` +//} +//type Edit struct { +// Name *string `json:"name,omitempty"` +// Description *string `json:"description,omitempty"` +// Prefix *string `json:"prefix,omitempty"` +// Url *string `json:"url,omitempty"` +//} + +//type SaveMonitorConfig struct { +// Driver string `json:"driver"` +// Config map[string]interface{} `json:"config"` +//} + +//type MonitorConfig struct { +// Driver string `json:"driver"` +// Config map[string]interface{} `json:"config"` +//} + +//type MonitorPartition struct { +// Id string `json:"id"` +// Name string `json:"name"` +// EnableMonitor bool `json:"enable_monitor"` +//} + +type ResetCluster struct { + ManagerAddress string `json:"manager_address"` +} + +type CheckCluster struct { + Address string `json:"address"` +} diff --git a/module/partition/dto/output.go b/module/cluster/dto/output.go similarity index 98% rename from module/partition/dto/output.go rename to module/cluster/dto/output.go index 68e7a76..212c54e 100644 --- a/module/partition/dto/output.go +++ b/module/cluster/dto/output.go @@ -1,4 +1,4 @@ -package partition_dto +package cluster_dto import ( "github.com/eolinker/go-common/auto" diff --git a/module/cluster/impl.go b/module/cluster/impl.go new file mode 100644 index 0000000..5c052db --- /dev/null +++ b/module/cluster/impl.go @@ -0,0 +1,300 @@ +package cluster + +import ( + "context" + + cluster_dto "github.com/eolinker/apipark/module/cluster/dto" + + "github.com/eolinker/apipark/gateway/admin" + "github.com/eolinker/eosc/log" + + "github.com/eolinker/go-common/store" + + "github.com/eolinker/apipark/gateway" + + "github.com/eolinker/ap-account/service/account" + "github.com/eolinker/apipark/service/cluster" + "github.com/eolinker/go-common/utils" +) + +var ( + _ IClusterModule = (*imlClusterModule)(nil) +) + +type imlClusterModule struct { + clusterService cluster.IClusterService `autowired:""` + userNameService account.IAccountService `autowired:""` + transaction store.ITransaction `autowired:""` +} + +func (m *imlClusterModule) CheckCluster(ctx context.Context, address ...string) ([]*cluster_dto.Node, error) { + info, err := admin.Admin(address...).Info(ctx) + if err != nil { + return nil, err + } + nodesOut := utils.SliceToSlice(info.Nodes, func(i *admin.Node) *cluster_dto.Node { + return &cluster_dto.Node{ + Id: i.Id, + Name: i.Name, + Admins: i.Admin, + Peers: i.Peer, + Gateways: i.Server, + } + }) + nodeStatus(ctx, nodesOut) + + return nodesOut, nil +} + +func (m *imlClusterModule) ResetCluster(ctx context.Context, clusterId string, address string) ([]*cluster_dto.Node, error) { + + nodes, err := m.clusterService.UpdateAddress(ctx, clusterId, address) + if err != nil { + return nil, err + } + err = m.initGateway(ctx, clusterId) + if err != nil { + return nil, err + } + nodesOut := utils.SliceToSlice(nodes, func(i *cluster.Node) *cluster_dto.Node { + return &cluster_dto.Node{ + Id: i.Uuid, + Name: i.Name, + Admins: i.Admin, + Peers: i.Peer, + Gateways: i.Server, + } + }) + + nodeStatus(ctx, nodesOut) + return nodesOut, nil +} +func (m *imlClusterModule) initGateway(ctx context.Context, clusterId string) error { + client, err := m.clusterService.GatewayClient(ctx, clusterId) + if err != nil { + return err + } + defer func() { + err := client.Close(ctx) + if err != nil { + log.Warn("close apinto client:", err) + } + }() + return gateway.InitGateway(ctx, clusterId, client) +} +func (m *imlClusterModule) ClusterNodes(ctx context.Context, clusterId string) ([]*cluster_dto.Node, error) { + + nodes, err := m.clusterService.Nodes(ctx) + if err != nil { + return nil, err + } + nodesOut := utils.SliceToSlice(nodes, func(i *cluster.Node) *cluster_dto.Node { + return &cluster_dto.Node{ + Id: i.Uuid, + Name: i.Name, + Admins: i.Admin, + Peers: i.Peer, + Gateways: i.Server, + } + }) + nodeStatus(ctx, nodesOut) + + return nodesOut, nil +} + +// +//func (m *imlClusterModule) CreatePartition(ctx context.Context, create *paritiondto.Create) (*paritiondto.Detail, error) { +// if create.Id == "" { +// create.Id = uuid.New().String() +// } +// if create.Name == "" { +// return nil, errors.New("name is empty") +// } +// clusterId := "" +// err := m.transaction.Transaction(ctx, func(ctx context.Context) error { +// clusterInfo, err := m.clusterService.Create(ctx, create.Id, create.Id, create.Description, create.ManagerAddress) +// if err != nil { +// return err +// } +// if create.Prefix != "" { +// create.Prefix = fmt.Sprintf("/%s", strings.TrimPrefix(create.Prefix, "/")) +// } +// clusterId = clusterInfo.Uuid +// return m.partitionService.Create(ctx, &partition.CreatePartition{ +// Uuid: create.Id, +// Name: create.Name, +// Resume: create.Description, +// Prefix: create.Prefix, +// Url: create.Url, +// Cluster: clusterInfo.Uuid, +// }) +// }) +// if err != nil { +// return nil, err +// } +// err = m.initGateway(ctx, create.Id, clusterId) +// if err != nil { +// return nil, err +// } +// return m.Get(ctx, create.Id) +//} +// +//func (m *imlClusterModule) Search(ctx context.Context, keyword string) ([]*paritiondto.Item, error) { +// partitions, err := m.partitionService.Search(ctx, keyword, nil) +// if err != nil { +// return nil, err +// } +// countMap, err := m.clusterService.CountByPartition(ctx) +// if err != nil { +// return nil, err +// } +// items := utils.SliceToSlice(partitions, func(i *partition.Cluster) *paritiondto.Item { +// +// return &paritiondto.Item{ +// Creator: auto.UUID(i.Creator), +// Updater: auto.UUID(i.Updater), +// Id: i.UUID, +// Name: i.Name, +// Description: i.Resume, +// ClusterNum: countMap[i.UUID], +// CreateTime: auto.TimeLabel(i.CreateTime), +// UpdateTime: auto.TimeLabel(i.UpdateTime), +// } +// }) +// if len(items) > 0 { +// counts, err := m.clusterService.CountByPartition(ctx) +// if err != nil { +// return nil, err +// } +// for _, item := range items { +// item.ClusterNum = counts[item.Id] +// } +// } +// +// return items, nil +//} +// +//func (m *imlClusterModule) Get(ctx context.Context, id string) (*paritiondto.Detail, error) { +// pm, err := m.partitionService.Get(ctx, id) +// if err != nil { +// return nil, err +// } +// //oDetails, err := m.organizationService.Search(ctx, "") +// //if err != nil { +// // return nil, err +// //} +// //canDelete := true +// //for _, o := range oDetails { +// // for _, p := range o.Clusters { +// // if p == id { +// // canDelete = false +// // break +// // } +// // } +// // if !canDelete { +// // break +// // } +// //} +// +// pd := &paritiondto.Detail{ +// Creator: auto.UUID(pm.Creator), +// Updater: auto.UUID(pm.Updater), +// Id: pm.UUID, +// Name: pm.Name, +// Description: pm.Resume, +// Prefix: pm.Prefix, +// CreateTime: auto.TimeLabel(pm.CreateTime), +// UpdateTime: auto.TimeLabel(pm.UpdateTime), +// //CanDelete: canDelete, +// } +// return pd, nil +//} +// +//func (m *imlClusterModule) Update(ctx context.Context, id string, edit *paritiondto.Edit) (*paritiondto.Detail, error) { +// err := m.partitionService.Save(ctx, id, &partition.EditPartition{ +// Name: edit.Name, +// Resume: edit.Description, +// Prefix: edit.Prefix, +// Url: edit.Url, +// }) +// if err != nil { +// return nil, err +// } +// return m.Get(ctx, id) +//} +// +//func (m *imlClusterModule) Delete(ctx context.Context, id string) error { +// return m.transaction.Transaction(ctx, func(ctx context.Context) error { +// info, err := m.partitionService.Get(ctx, id) +// if err != nil { +// if errors.Is(err, gorm.ErrRecordNotFound) { +// return nil +// } +// return err +// } +// err = m.clusterService.Delete(ctx, info.Cluster) +// if err != nil { +// return err +// } +// return m.partitionService.Delete(ctx, id) +// }) +// +//} +// +//func (m *imlClusterModule) Simple(ctx context.Context) ([]*paritiondto.Simple, error) { +// pm, err := m.partitionService.Search(ctx, "", nil) +// if err != nil { +// return nil, err +// } +// pd := utils.SliceToSlice(pm, func(i *partition.Cluster) *paritiondto.Simple { +// return &paritiondto.Simple{ +// Id: i.UUID, +// Name: i.Name, +// } +// }) +// return pd, nil +//} +// +//func (m *imlClusterModule) SimpleByIds(ctx context.Context, ids []string) ([]*paritiondto.Simple, error) { +// pm, err := m.partitionService.Search(ctx, "", map[string]interface{}{ +// "uuid": ids, +// }) +// if err != nil { +// return nil, err +// } +// pd := utils.SliceToSlice(pm, func(i *partition.Cluster) *paritiondto.Simple { +// return &paritiondto.Simple{ +// Id: i.UUID, +// Name: i.Name, +// } +// }) +// return pd, nil +// +//} +//func (m *imlClusterModule) SimpleWithCluster(ctx context.Context) ([]*paritiondto.SimpleWithCluster, error) { +// pm, err := m.partitionService.Search(ctx, "", nil) +// if err != nil { +// return nil, err +// } +// +// clusterList, err := m.clusterService.List(ctx) +// if err != nil { +// return nil, err +// } +// +// clusterMap := utils.SliceToMapArrayO(clusterList, func(i *cluster.Cluster) (string, *paritiondto.Cluster) { +// return i.Cluster, &paritiondto.Cluster{ +// Id: i.Uuid, +// Name: i.Name, +// Description: i.Resume, +// } +// }) +// pd := utils.SliceToSlice(pm, func(i *partition.Cluster) *paritiondto.SimpleWithCluster { +// return &paritiondto.SimpleWithCluster{ +// Id: i.UUID, +// Name: i.Name, +// Clusters: clusterMap[i.UUID], +// } +// }) +// return pd, nil +//} diff --git a/module/partition/util.go b/module/cluster/util.go similarity index 69% rename from module/partition/util.go rename to module/cluster/util.go index c98a916..5675b3a 100644 --- a/module/partition/util.go +++ b/module/cluster/util.go @@ -1,15 +1,15 @@ -package partition +package cluster import ( "context" "sync" - partition_dto "github.com/eolinker/apipark/module/partition/dto" + cluster_dto "github.com/eolinker/apipark/module/cluster/dto" "github.com/eolinker/apipark/gateway/admin" ) -func nodeStatus(ctx context.Context, nodes []*partition_dto.Node) { +func nodeStatus(ctx context.Context, nodes []*cluster_dto.Node) { if len(nodes) == 0 { return } @@ -26,7 +26,7 @@ func nodeStatus(ctx context.Context, nodes []*partition_dto.Node) { } wg.Wait() } -func doPingRouting(ctx context.Context, n *partition_dto.Node, wg *sync.WaitGroup) { +func doPingRouting(ctx context.Context, n *cluster_dto.Node, wg *sync.WaitGroup) { n.Status = ping(ctx, n.Admins...) wg.Done() } diff --git a/module/dynamic-module/dto/input.go b/module/dynamic-module/dto/input.go index 02bfb14..8c13a53 100644 --- a/module/dynamic-module/dto/input.go +++ b/module/dynamic-module/dto/input.go @@ -16,6 +16,6 @@ type EditDynamicModule struct { Config *map[string]PartitionConfig `json:"config"` } -type PartitionInput struct { - Partitions []string `json:"partitions" aocheck:"partition"` +type ClusterInput struct { + Clusters []string `json:"clusters" aocheck:"cluster"` } diff --git a/module/dynamic-module/dynamic_module.go b/module/dynamic-module/dynamic_module.go index 1deaab0..c0f12b7 100644 --- a/module/dynamic-module/dynamic_module.go +++ b/module/dynamic-module/dynamic_module.go @@ -17,14 +17,14 @@ type IDynamicModuleModule interface { Delete(ctx context.Context, module string, ids []string) error Get(ctx context.Context, module string, id string) (*dynamic_module_dto.DynamicModule, error) List(ctx context.Context, module string, keyword string, page int, pageSize int) ([]map[string]interface{}, int64, error) - PluginInfo(ctx context.Context, module string, partitionIds ...string) (*dynamic_module_dto.PluginInfo, error) + PluginInfo(ctx context.Context, module string, clusterIds ...string) (*dynamic_module_dto.PluginInfo, error) Render(ctx context.Context, module string) (map[string]interface{}, error) ModuleDrivers(ctx context.Context, group string) ([]*dynamic_module_dto.ModuleDriver, error) - Online(ctx context.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error - Offline(ctx context.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error - PartitionStatuses(ctx context.Context, module string, keyword string, page int, pageSize int) (map[string]map[string]string, error) - PartitionStatus(ctx context.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) + Online(ctx context.Context, module string, id string, clusterInput *dynamic_module_dto.ClusterInput) error + Offline(ctx context.Context, module string, id string, clusterInput *dynamic_module_dto.ClusterInput) error + //PartitionStatuses(ctx context.Context, module string, keyword string, page int, pageSize int) (map[string]map[string]string, error) + //PartitionStatus(ctx context.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) } func init() { diff --git a/module/dynamic-module/iml.go b/module/dynamic-module/iml.go index 2dbe9ce..1bf0ead 100644 --- a/module/dynamic-module/iml.go +++ b/module/dynamic-module/iml.go @@ -4,10 +4,11 @@ import ( "context" "encoding/json" "fmt" - "github.com/eolinker/eosc/log" "strings" "time" + "github.com/eolinker/eosc/log" + "github.com/eolinker/apipark/gateway" "github.com/eolinker/go-common/store" @@ -18,14 +19,10 @@ import ( "github.com/eolinker/go-common/utils" - "github.com/eolinker/go-common/auto" - "github.com/google/uuid" "github.com/eolinker/apipark/module/dynamic-module/driver" - "github.com/eolinker/apipark/service/partition" - dynamic_module_dto "github.com/eolinker/apipark/module/dynamic-module/dto" dynamic_module "github.com/eolinker/apipark/service/dynamic-module" ) @@ -33,7 +30,6 @@ import ( var _ IDynamicModuleModule = (*imlDynamicModule)(nil) type imlDynamicModule struct { - partitionService partition.IPartitionService `autowired:""` clusterService cluster.IClusterService `autowired:""` dynamicModuleService dynamic_module.IDynamicModuleService `autowired:""` dynamicModulePublishService dynamic_module.IDynamicModulePublishService `autowired:""` @@ -41,40 +37,38 @@ type imlDynamicModule struct { transaction store.ITransaction `autowired:""` } -func (i *imlDynamicModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { +func (i *imlDynamicModule) initGateway(ctx context.Context, clusterId string, clientDriver gateway.IClientDriver) error { + // TODO: 初始化集群操作 return nil } -func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error { +func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, clusterInput *dynamic_module_dto.ClusterInput) error { _, has := driver.Get(module) if !has { return fmt.Errorf("模块【%s】不存在", module) } - if len(partitionInput.Partitions) == 0 { + if len(clusterInput.Clusters) == 0 { return fmt.Errorf("上线分区失败,分区为空") } - partitions, err := i.partitionService.List(ctx, partitionInput.Partitions...) - if err != nil { - return err - } - if len(partitions) == 0 { - return fmt.Errorf("上线分区失败,可用分区为空") - } id = strings.ToLower(fmt.Sprintf("%s_%s", id, module)) info, err := i.dynamicModuleService.Get(ctx, id) if err != nil { return fmt.Errorf("上线失败,配置不存在") } + clusters, err := i.clusterService.List(ctx, clusterInput.Clusters...) + if err != nil { + return fmt.Errorf("上线失败,集群不存在") + } return i.transaction.Transaction(ctx, func(ctx context.Context) error { - cfg := make(map[string]*gateway.DynamicRelease) - err = json.Unmarshal([]byte(info.Config), &cfg) + data := make(map[string]*gateway.DynamicRelease) + err = json.Unmarshal([]byte(info.Config), &data) if err != nil { return err } - for _, p := range partitions { - pCfg, ok := cfg[p.UUID] + for _, c := range clusters { + cfg, ok := data[c.Uuid] if !ok { continue } @@ -83,24 +77,23 @@ func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, ID: uuid.New().String(), DynamicModule: id, Module: module, - Partition: p.UUID, - Cluster: p.Cluster, + Cluster: c.Uuid, Version: info.Version, }) if err != nil { return err } - err := i.dynamicClient(ctx, p.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { + err = i.dynamicClient(ctx, c.Uuid, module, func(dynamicClient gateway.IDynamicClient) error { err = json.Unmarshal([]byte(info.Config), &cfg) if err != nil { return err } - pCfg.ID = id - pCfg.Version = info.Version - pCfg.MatchLabels = map[string]string{ + cfg.ID = id + cfg.Version = info.Version + cfg.MatchLabels = map[string]string{ "module": module, } - err = dynamicClient.Online(ctx, pCfg) + err = dynamicClient.Online(ctx, cfg) if err != nil { return err } @@ -116,26 +109,19 @@ func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, }) } -func (i *imlDynamicModule) Offline(ctx context.Context, module string, id string, partitionInput *dynamic_module_dto.PartitionInput) error { +func (i *imlDynamicModule) Offline(ctx context.Context, module string, id string, clusterInput *dynamic_module_dto.ClusterInput) error { _, has := driver.Get(module) if !has { return fmt.Errorf("模块【%s】不存在", module) } - if len(partitionInput.Partitions) == 0 { + if len(clusterInput.Clusters) == 0 { return fmt.Errorf("下线分区失败,分区为空") } - partitions, err := i.partitionService.List(ctx, partitionInput.Partitions...) - if err != nil { - return err - } - if len(partitions) == 0 { - return fmt.Errorf("下线分区失败,可用分区为空") - } return i.transaction.Transaction(ctx, func(ctx context.Context) error { id = strings.ToLower(fmt.Sprintf("%s_%s", id, module)) - for _, p := range partitions { - err := i.dynamicClient(ctx, p.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { + for _, clusterId := range clusterInput.Clusters { + err := i.dynamicClient(ctx, clusterId, module, func(dynamicClient gateway.IDynamicClient) error { return dynamicClient.Offline(ctx, &gateway.DynamicRelease{ BasicItem: &gateway.BasicItem{ ID: id, @@ -151,54 +137,55 @@ func (i *imlDynamicModule) Offline(ctx context.Context, module string, id string }) } -func (i *imlDynamicModule) PartitionStatuses(ctx context.Context, module string, keyword string, page int, pageSize int) (map[string]map[string]string, error) { - _, has := driver.Get(module) - if !has { - return nil, fmt.Errorf("模块【%s】不存在", module) - } - list, _, err := i.dynamicModuleService.SearchByPage(ctx, keyword, map[string]interface{}{ - "module": module, - }, page, pageSize, "update_at desc") - if err != nil { - return nil, err - } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return nil, err - } - out := make(map[string]map[string]string) - for _, c := range partitions { - err := i.dynamicClient(ctx, c.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { - versions, err := dynamicClient.Versions(ctx, map[string]string{ - "module": module, - }) - if err != nil { - return err - } - for _, l := range list { - id := strings.TrimSuffix(l.ID, fmt.Sprintf("_%s", module)) - if _, ok := out[id]; !ok { - out[id] = make(map[string]string) - } - - out[id][c.UUID] = "未发布" - if v, ok := versions[strings.ToLower(l.ID)]; ok { - if v == l.Version { - out[id][c.UUID] = "已发布" - } else { - out[id][c.UUID] = "待发布" - } - } - } - return nil - }) - if err != nil { - return nil, err - } - - } - return out, nil -} +// +//func (i *imlDynamicModule) PartitionStatuses(ctx context.Context, module string, keyword string, page int, pageSize int) (map[string]map[string]string, error) { +// _, has := driver.Get(module) +// if !has { +// return nil, fmt.Errorf("模块【%s】不存在", module) +// } +// list, _, err := i.dynamicModuleService.SearchByPage(ctx, keyword, map[string]interface{}{ +// "module": module, +// }, page, pageSize, "update_at desc") +// if err != nil { +// return nil, err +// } +// partitions, err := i.partitionService.List(ctx) +// if err != nil { +// return nil, err +// } +// out := make(map[string]map[string]string) +// for _, c := range partitions { +// err := i.dynamicClient(ctx, c.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { +// versions, err := dynamicClient.Versions(ctx, map[string]string{ +// "module": module, +// }) +// if err != nil { +// return err +// } +// for _, l := range list { +// id := strings.TrimSuffix(l.ID, fmt.Sprintf("_%s", module)) +// if _, ok := out[id]; !ok { +// out[id] = make(map[string]string) +// } +// +// out[id][c.UUID] = "未发布" +// if v, ok := versions[strings.ToLower(l.ID)]; ok { +// if v == l.Version { +// out[id][c.UUID] = "已发布" +// } else { +// out[id][c.UUID] = "待发布" +// } +// } +// } +// return nil +// }) +// if err != nil { +// return nil, err +// } +// +// } +// return out, nil +//} func (i *imlDynamicModule) dynamicClient(ctx context.Context, clusterId string, resource string, h func(gateway.IDynamicClient) error) error { client, err := i.clusterService.GatewayClient(ctx, clusterId) @@ -219,72 +206,73 @@ func (i *imlDynamicModule) dynamicClient(ctx context.Context, clusterId string, return h(dynamic) } -func (i *imlDynamicModule) PartitionStatus(ctx context.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) { - _, has := driver.Get(module) - - if !has { - return nil, fmt.Errorf("模块【%s】不存在", module) - } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return nil, err - } - partitionIds := utils.SliceToSlice(partitions, func(s *partition.Partition) string { - return s.UUID - }) - suffix := fmt.Sprintf("_%s", module) - id = id + suffix - info, err := i.dynamicModuleService.Get(ctx, id) - if err != nil { - return nil, err - } - publishMap, err := i.dynamicModulePublishService.Latest(ctx, id, partitionIds) - if err != nil { - return nil, err - } - - partitionInfos := make([]*dynamic_module_dto.PartitionInfo, 0, len(partitionIds)) - for _, c := range partitions { - err := i.dynamicClient(ctx, c.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { - version, err := dynamicClient.Version(ctx, id) - if err != nil { - return err - } - updater := "" - updateTime := time.Time{} - publishInfo, ok := publishMap[c.UUID] - if ok { - updater = publishInfo.Creator - updateTime = publishInfo.CreateAt - } - cInfo := &dynamic_module_dto.PartitionInfo{ - Name: c.UUID, - Title: c.Name, - Status: "未发布", - Updater: auto.UUID(updater), - UpdateTime: auto.TimeLabel(updateTime), - } - if version == info.Version { - cInfo.Status = "已发布" - } else if version != "" { - cInfo.Status = "待发布" - } - partitionInfos = append(partitionInfos, cInfo) - return nil - }) - if err != nil { - return nil, err - } - - } - return &dynamic_module_dto.OnlineInfo{ - Id: strings.TrimSuffix(info.ID, suffix), - Name: strings.TrimSuffix(info.ID, suffix), - Title: info.Name, - Description: info.Description, - Partitions: partitionInfos, - }, nil -} +// +//func (i *imlDynamicModule) PartitionStatus(ctx context.Context, module string, id string) (*dynamic_module_dto.OnlineInfo, error) { +// _, has := driver.Get(module) +// +// if !has { +// return nil, fmt.Errorf("模块【%s】不存在", module) +// } +// partitions, err := i.partitionService.List(ctx) +// if err != nil { +// return nil, err +// } +// partitionIds := utils.SliceToSlice(partitions, func(s *partition.Partition) string { +// return s.UUID +// }) +// suffix := fmt.Sprintf("_%s", module) +// id = id + suffix +// info, err := i.dynamicModuleService.Get(ctx, id) +// if err != nil { +// return nil, err +// } +// publishMap, err := i.dynamicModulePublishService.Latest(ctx, id, partitionIds) +// if err != nil { +// return nil, err +// } +// +// partitionInfos := make([]*dynamic_module_dto.PartitionInfo, 0, len(partitionIds)) +// for _, c := range partitions { +// err := i.dynamicClient(ctx, c.Cluster, module, func(dynamicClient gateway.IDynamicClient) error { +// version, err := dynamicClient.Version(ctx, id) +// if err != nil { +// return err +// } +// updater := "" +// updateTime := time.Time{} +// publishInfo, ok := publishMap[c.UUID] +// if ok { +// updater = publishInfo.Creator +// updateTime = publishInfo.CreateAt +// } +// cInfo := &dynamic_module_dto.PartitionInfo{ +// Name: c.UUID, +// Title: c.Name, +// Status: "未发布", +// Updater: auto.UUID(updater), +// UpdateTime: auto.TimeLabel(updateTime), +// } +// if version == info.Version { +// cInfo.Status = "已发布" +// } else if version != "" { +// cInfo.Status = "待发布" +// } +// partitionInfos = append(partitionInfos, cInfo) +// return nil +// }) +// if err != nil { +// return nil, err +// } +// +// } +// return &dynamic_module_dto.OnlineInfo{ +// Id: strings.TrimSuffix(info.ID, suffix), +// Name: strings.TrimSuffix(info.ID, suffix), +// Title: info.Name, +// Description: info.Description, +// Clusters: partitionInfos, +// }, nil +//} func (i *imlDynamicModule) ModuleDrivers(ctx context.Context, group string) ([]*dynamic_module_dto.ModuleDriver, error) { ds := driver.List(group) @@ -306,28 +294,24 @@ func (i *imlDynamicModule) Render(ctx context.Context, module string) (map[strin return d.Define().Render(), nil } -func (i *imlDynamicModule) PluginInfo(ctx context.Context, module string, partitionIds ...string) (*dynamic_module_dto.PluginInfo, error) { +func (i *imlDynamicModule) PluginInfo(ctx context.Context, module string, clusterIds ...string) (*dynamic_module_dto.PluginInfo, error) { d, has := driver.Get(module) if !has { return nil, fmt.Errorf("module %s not found", module) } - partitions, err := i.partitionService.List(ctx, partitionIds...) - if err != nil { - return nil, err - } - fields := make([]*driver.Field, 0, len(partitionIds)) - for _, c := range partitions { - fields = append(fields, &driver.Field{ - Name: c.UUID, - Title: fmt.Sprintf("状态:%s", c.Name), - Attr: "status", - Enum: []string{ - "已发布", - "待发布", - "未发布", - }, - }) - } + + fields := make([]*driver.Field, 0, 1) + + fields = append(fields, &driver.Field{ + Name: "status", + Title: fmt.Sprintf("状态:"), + Attr: "status", + Enum: []string{ + "已发布", + "待发布", + "未发布", + }, + }) return &dynamic_module_dto.PluginInfo{ PluginBasic: &dynamic_module_dto.PluginBasic{ Id: d.ID(), diff --git a/module/my-team/dto/input.go b/module/my-team/dto/input.go index 34d4fc1..aff2f9e 100644 --- a/module/my-team/dto/input.go +++ b/module/my-team/dto/input.go @@ -9,3 +9,8 @@ type EditTeam struct { type UserIDs struct { Users []string `json:"users"` } + +type UpdateMemberRole struct { + Roles []string `json:"roles" aocheck:"role"` + Users []string `json:"users" aocheck:"user"` +} diff --git a/module/my-team/dto/output.go b/module/my-team/dto/output.go index 7c275eb..ca3c35d 100644 --- a/module/my-team/dto/output.go +++ b/module/my-team/dto/output.go @@ -7,105 +7,69 @@ import ( ) type Item struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - Organization auto.Label `json:"organization" aolabel:"organization"` - ProjectNum int64 `json:"system_num"` - CanDelete bool `json:"can_delete"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + ProjectNum int64 `json:"system_num"` + CanDelete bool `json:"can_delete"` } -//func ToItem(model *team.Team) *Item { -// return &Item{ -// Id: model.Id, -// Name: model.Name, -// Description: model.Description, -// Master: auto.UUID(model.Master), -// CreateTime: auto.TimeLabel(model.CreateTime), -// UpdateTime: auto.TimeLabel(model.UpdateTime), -// Organization: auto.UUID(model.Organization), -// ProjectNum: model.ProjectNum, -// } -//} - func ToItem(model *team.Team, projectNum int64) *Item { return &Item{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - ProjectNum: projectNum, - CanDelete: projectNum == 0, + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + ProjectNum: projectNum, + CanDelete: projectNum == 0, } } type SimpleTeam struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Organization auto.Label `json:"organization" aolabel:"organization"` - AvailablePartitions []auto.Label `json:"available_partitions" aolabel:"partition"` - DisablePartitions []auto.Label `json:"disable_partitions" aolabel:"partition"` - AppNum int64 `json:"app_num"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + ServiceNum int64 `json:"service_num"` + AppNum int64 `json:"app_num"` } type Team struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - Organization auto.Label `json:"organization" aolabel:"organization"` - Creator auto.Label `json:"creator" aolabel:"user"` - Updater auto.Label `json:"updater" aolabel:"user"` - AvailablePartitions []auto.Label `json:"available_partitions" aolabel:"partition"` - DisablePartitions []auto.Label `json:"disable_partitions" aolabel:"partition"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + Creator auto.Label `json:"creator" aolabel:"user"` + Updater auto.Label `json:"updater" aolabel:"user"` } func ToTeam(model *team.Team) *Team { return &Team{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - Creator: auto.UUID(model.Creator), - Updater: auto.UUID(model.Updater), + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Creator: auto.UUID(model.Creator), + Updater: auto.UUID(model.Updater), } } type Member struct { - UserId string `json:"user_id"` - Name auto.Label `json:"name" aolabel:"user"` - Role string `json:"role"` - UserGroup []auto.Label `json:"user_group" aolabel:"user_group"` + User auto.Label `json:"user" aolabel:"user"` + Roles []auto.Label `json:"roles" aolabel:"role"` AttachTime auto.TimeLabel `json:"attach_time"` - CanDelete bool `json:"can_delete"` } -func ToMember(model *team_member.Member, masterID string, groupIDs ...string) *Member { - role := "团队管理员" - canDelete := false - if model.UID != masterID { - role = "团队成员" - canDelete = true - } +func ToMember(model *team_member.Member, roles ...string) *Member { + return &Member{ - UserId: model.UID, - Name: auto.UUID(model.UID), - Role: role, - UserGroup: auto.List(groupIDs), + User: auto.UUID(model.UID), + Roles: auto.List(roles), AttachTime: auto.TimeLabel(model.CreateTime), - CanDelete: canDelete, } } diff --git a/module/my-team/iml.go b/module/my-team/iml.go index b2fe2aa..cd8030c 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -5,9 +5,9 @@ import ( "errors" "fmt" - "gorm.io/gorm" + "github.com/eolinker/ap-account/service/role" - "github.com/eolinker/apipark/service/partition" + "gorm.io/gorm" "github.com/eolinker/apipark/service/project" @@ -18,8 +18,6 @@ import ( "github.com/eolinker/go-common/store" - user_group "github.com/eolinker/ap-account/service/user-group" - team_member "github.com/eolinker/apipark/service/team-member" team_dto "github.com/eolinker/apipark/module/my-team/dto" @@ -32,49 +30,56 @@ var ( ) type imlTeamModule struct { - teamService team.ITeamService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - userGroupMemberService user_group.IUserGroupMemberService `autowired:""` - userService user.IUserService `autowired:""` - departmentMemberService department_member.IMemberService `autowired:""` - projectService project.IProjectService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - transaction store.ITransaction `autowired:""` + teamService team.ITeamService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + roleService role.IRoleService `autowired:""` + roleMemberService role.IRoleMemberService `autowired:""` + userService user.IUserService `autowired:""` + departmentMemberService department_member.IMemberService `autowired:""` + projectService project.IProjectService `autowired:""` + transaction store.ITransaction `autowired:""` } -func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, error) { - tv, err := m.teamService.Get(ctx, id) +func (m *imlTeamModule) UpdateMemberRole(ctx context.Context, id string, input *team_dto.UpdateMemberRole) error { + _, err := m.teamService.Get(ctx, id) if err != nil { - return nil, err + return err } - //availablePartitions, err := m.organizationService.Partitions(ctx, tv.Organization) - //if err != nil { - // return nil, err - //} - globalPartitions, err := m.partitionService.List(ctx) + return m.transaction.Transaction(ctx, func(ctx context.Context) error { + for _, roleId := range input.Roles { + err = m.roleMemberService.RemoveUserRole(ctx, roleId, input.Users...) + if err != nil { + return err + } + for _, userId := range input.Users { + err = m.roleMemberService.Add(ctx, &role.AddMember{ + Role: roleId, + User: userId, + Target: role.TeamTarget(id), + }) + if err != nil { + return err + } + } + } + return nil + }) +} + +func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, error) { + tv, err := m.teamService.Get(ctx, id) if err != nil { return nil, err } - globalPartitionMap := utils.SliceToMapO(globalPartitions, func(p *partition.Partition) (string, struct{}) { - return p.UUID, struct{}{} - }) - //for _, p := range availablePartitions { - // delete(globalPartitionMap, p) - //} + return &team_dto.Team{ - Id: tv.Id, - Name: tv.Name, - Description: tv.Description, - Master: auto.UUID(tv.Master), - CreateTime: auto.TimeLabel(tv.CreateTime), - UpdateTime: auto.TimeLabel(tv.UpdateTime), - Organization: auto.UUID(tv.Organization), - Creator: auto.UUID(tv.Creator), - Updater: auto.UUID(tv.Updater), - //AvailablePartitions: auto.List(availablePartitions), - DisablePartitions: auto.List(utils.MapToSlice(globalPartitionMap, func(k string, v struct{}) string { - return k - })), + Id: tv.Id, + Name: tv.Name, + Description: tv.Description, + CreateTime: auto.TimeLabel(tv.CreateTime), + UpdateTime: auto.TimeLabel(tv.UpdateTime), + Creator: auto.UUID(tv.Creator), + Updater: auto.UUID(tv.Updater), }, nil } @@ -124,7 +129,6 @@ func (m *imlTeamModule) Edit(ctx context.Context, id string, input *team_dto.Edi return m.teamService.Save(ctx, id, &team.EditTeam{ Name: input.Name, Description: input.Description, - Master: input.Master, }) }) @@ -150,45 +154,34 @@ func (m *imlTeamModule) SimpleTeams(ctx context.Context, keyword string) ([]*tea if err != nil { return nil, err } - //partitionMap, err := m.organizationService.PartitionsByOrganization(ctx) - //if err != nil { - // return nil, err - //} - globalPartitions, err := m.partitionService.List(ctx) - if err != nil { - return nil, err - } - apps, err := m.projectService.Search(ctx, "", map[string]interface{}{ - "team": teamIDs, - "as_app": true, - "master": utils.UserId(ctx), + + projects, err := m.projectService.Search(ctx, "", map[string]interface{}{ + "team": teamIDs, }) + projectCount := make(map[string]int64) appCount := make(map[string]int64) - for _, app := range apps { - if _, ok := appCount[app.Team]; !ok { - appCount[app.Team] = 0 + for _, p := range projects { + if p.AsServer { + if _, ok := projectCount[p.Team]; !ok { + projectCount[p.Team] = 0 + } + projectCount[p.Team]++ + } + if p.AsApp { + if _, ok := appCount[p.Team]; !ok { + appCount[p.Team] = 0 + } + appCount[p.Team]++ } - appCount[app.Team]++ } outList := utils.SliceToSlice(list, func(s *team.Team) *team_dto.SimpleTeam { - globalPartitionMap := utils.SliceToMapO(globalPartitions, func(p *partition.Partition) (string, struct{}) { - return p.UUID, struct{}{} - }) - //availablePartitions := partitionMap[s.Organization] - //for _, p := range availablePartitions { - // delete(globalPartitionMap, p) - //} return &team_dto.SimpleTeam{ - Id: s.Id, - Name: s.Name, - Description: s.Description, - Organization: auto.UUID(s.Organization), - //AvailablePartitions: auto.List(availablePartitions), - DisablePartitions: auto.List(utils.MapToSlice(globalPartitionMap, func(k string, v struct{}) string { - return k - })), - AppNum: appCount[s.Id], + Id: s.Id, + Name: s.Name, + Description: s.Description, + ServiceNum: projectCount[s.Id], + AppNum: appCount[s.Id], } }) return outList, nil @@ -199,27 +192,69 @@ func (m *imlTeamModule) AddMember(ctx context.Context, id string, uuids ...strin if err != nil { return err } + return m.transaction.Transaction(ctx, func(ctx context.Context) error { + err = m.teamMemberService.AddMemberTo(ctx, id, uuids...) + if err != nil { + return err + } + r, err := m.roleService.GetDefaultRole(ctx, role.GroupTeam) + if err != nil { + return err + } + for _, uid := range uuids { + err = m.roleMemberService.Add(ctx, &role.AddMember{Role: r.Id, User: uid, Target: role.TeamTarget(id)}) + if err != nil { + return err + } + } + return nil + }) - return m.teamMemberService.AddMemberTo(ctx, id, uuids...) } func (m *imlTeamModule) RemoveMember(ctx context.Context, id string, uuids ...string) error { - teamInfo, err := m.teamService.Get(ctx, id) + _, err := m.teamService.Get(ctx, id) if err != nil { return err } - newUuids := make([]string, 0, len(uuids)) - for _, uuid := range uuids { - if teamInfo.Master == uuid { - continue + + supperRole, err := m.roleService.GetSupperRole(ctx, role.GroupTeam) + if err != nil { + return err + } + count, err := m.roleMemberService.CountByRole(ctx, role.TeamTarget(id), supperRole.Id) + if err != nil { + return err + } + members, err := m.roleMemberService.List(ctx, role.TeamTarget(id), uuids...) + if err != nil { + return err + } + if len(members) >= int(count) { + supperRoleCount := 0 + for _, member := range members { + if member.Role == supperRole.Id { + supperRoleCount++ + } + } + + if supperRoleCount == int(count) { + return errors.New("can not delete all team admin") } - newUuids = append(newUuids, uuid) } - return m.teamMemberService.RemoveMemberFrom(ctx, id, newUuids...) + + return m.transaction.Transaction(ctx, func(ctx context.Context) error { + err = m.roleMemberService.RemoveUserRole(ctx, role.TeamTarget(id), uuids...) + if err != nil { + return err + } + return m.teamMemberService.RemoveMemberFrom(ctx, id, uuids...) + }) + } func (m *imlTeamModule) Members(ctx context.Context, id string, keyword string) ([]*team_dto.Member, error) { - teamInfo, err := m.teamService.Get(ctx, id) + _, err := m.teamService.Get(ctx, id) if err != nil { return nil, err } @@ -234,12 +269,17 @@ func (m *imlTeamModule) Members(ctx context.Context, id string, keyword string) if err != nil { return nil, err } + roleMembers, err := m.roleMemberService.List(ctx, role.TeamTarget(id)) + if err != nil { + return nil, err + } + roleMemberMap := utils.SliceToMapArrayO(roleMembers, func(r *role.Member) (string, string) { + return r.User, r.Role + }) - groupMemberMap, err := m.userGroupMemberService.FilterMembersForUser(ctx, userIds...) out := make([]*team_dto.Member, 0, len(members)) for _, member := range members { - gIDs, _ := groupMemberMap[member.UID] - out = append(out, team_dto.ToMember(member, teamInfo.Master, gIDs...)) + out = append(out, team_dto.ToMember(member, roleMemberMap[member.UID]...)) } return out, nil diff --git a/module/my-team/team.go b/module/my-team/team.go index e45bbaa..f12ac32 100644 --- a/module/my-team/team.go +++ b/module/my-team/team.go @@ -26,6 +26,9 @@ type ITeamModule interface { Members(ctx context.Context, id string, keyword string) ([]*team_dto.Member, error) // SimpleMembers 获取团队成员简易列表 SimpleMembers(ctx context.Context, id string, keyword string) ([]*team_dto.SimpleMember, error) + + // UpdateMemberRole 更新成员角色 + UpdateMemberRole(ctx context.Context, id string, input *team_dto.UpdateMemberRole) error } func init() { diff --git a/module/partition/dto/input.go b/module/partition/dto/input.go deleted file mode 100644 index d6d824e..0000000 --- a/module/partition/dto/input.go +++ /dev/null @@ -1,40 +0,0 @@ -package partition_dto - -type Create struct { - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Prefix string `json:"prefix,omitempty"` - Url string `json:"url,omitempty"` - ManagerAddress string `json:"manager_address,omitempty"` -} -type Edit struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - Prefix *string `json:"prefix,omitempty"` - Url *string `json:"url,omitempty"` -} - -type SaveMonitorConfig struct { - Driver string `json:"driver"` - Config map[string]interface{} `json:"config"` -} - -type MonitorConfig struct { - Driver string `json:"driver"` - Config map[string]interface{} `json:"config"` -} - -type MonitorPartition struct { - Id string `json:"id"` - Name string `json:"name"` - EnableMonitor bool `json:"enable_monitor"` -} - -type ResetCluster struct { - ManagerAddress string `json:"manager_address"` -} - -type CheckCluster struct { - Address string `json:"address"` -} diff --git a/module/partition/impl.go b/module/partition/impl.go deleted file mode 100644 index f312695..0000000 --- a/module/partition/impl.go +++ /dev/null @@ -1,317 +0,0 @@ -package partition - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/eolinker/apipark/gateway/admin" - "github.com/eolinker/eosc/log" - - "github.com/eolinker/go-common/store" - - "github.com/eolinker/apipark/gateway" - - "gorm.io/gorm" - - "github.com/google/uuid" - - "github.com/eolinker/ap-account/service/account" - paritiondto "github.com/eolinker/apipark/module/partition/dto" - "github.com/eolinker/apipark/service/cluster" - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/utils" -) - -var ( - _ IPartitionModule = (*imlPartition)(nil) -) - -type imlPartition struct { - partitionService partition.IPartitionService `autowired:""` - //organizationService organization.IOrganizationService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - userNameService account.IAccountService `autowired:""` - //monitorService monitor.IMonitorService `autowired:""` - transaction store.ITransaction `autowired:""` -} - -func (m *imlPartition) CheckCluster(ctx context.Context, address ...string) ([]*paritiondto.Node, error) { - info, err := admin.Admin(address...).Info(ctx) - if err != nil { - return nil, err - } - nodesOut := utils.SliceToSlice(info.Nodes, func(i *admin.Node) *paritiondto.Node { - return &paritiondto.Node{ - Id: i.Id, - Name: i.Name, - Admins: i.Admin, - Peers: i.Peer, - Gateways: i.Server, - } - }) - nodeStatus(ctx, nodesOut) - - return nodesOut, nil -} - -func (m *imlPartition) ResetCluster(ctx context.Context, partitionId string, address string) ([]*paritiondto.Node, error) { - info, err := m.partitionService.Get(ctx, partitionId) - if err != nil { - return nil, err - } - - nodes, err := m.clusterService.UpdateAddress(ctx, info.Cluster, address) - if err != nil { - return nil, err - } - err = m.initGateway(ctx, partitionId, info.Cluster) - if err != nil { - return nil, err - } - nodesOut := utils.SliceToSlice(nodes, func(i *cluster.Node) *paritiondto.Node { - return &paritiondto.Node{ - Id: i.Uuid, - Name: i.Name, - Admins: i.Admin, - Peers: i.Peer, - Gateways: i.Server, - } - }) - - nodeStatus(ctx, nodesOut) - return nodesOut, nil -} -func (m *imlPartition) initGateway(ctx context.Context, partitionId, clusterId string) error { - client, err := m.clusterService.GatewayClient(ctx, clusterId) - if err != nil { - return err - } - defer func() { - err := client.Close(ctx) - if err != nil { - log.Warn("close apinto client:", err) - } - }() - return gateway.InitGateway(ctx, partitionId, client) -} -func (m *imlPartition) ClusterNodes(ctx context.Context, partitionId string) ([]*paritiondto.Node, error) { - info, err := m.partitionService.Get(ctx, partitionId) - if err != nil { - return nil, err - } - nodes, err := m.clusterService.Nodes(ctx, info.Cluster) - if err != nil { - return nil, err - } - nodesOut := utils.SliceToSlice(nodes, func(i *cluster.Node) *paritiondto.Node { - return &paritiondto.Node{ - Id: i.Uuid, - Name: i.Name, - Admins: i.Admin, - Peers: i.Peer, - Gateways: i.Server, - } - }) - nodeStatus(ctx, nodesOut) - - return nodesOut, nil -} - -func (m *imlPartition) CreatePartition(ctx context.Context, create *paritiondto.Create) (*paritiondto.Detail, error) { - if create.Id == "" { - create.Id = uuid.New().String() - } - if create.Name == "" { - return nil, errors.New("name is empty") - } - clusterId := "" - err := m.transaction.Transaction(ctx, func(ctx context.Context) error { - clusterInfo, err := m.clusterService.Create(ctx, create.Id, create.Id, create.Description, create.ManagerAddress) - if err != nil { - return err - } - if create.Prefix != "" { - create.Prefix = fmt.Sprintf("/%s", strings.TrimPrefix(create.Prefix, "/")) - } - clusterId = clusterInfo.Uuid - return m.partitionService.Create(ctx, &partition.CreatePartition{ - Uuid: create.Id, - Name: create.Name, - Resume: create.Description, - Prefix: create.Prefix, - Url: create.Url, - Cluster: clusterInfo.Uuid, - }) - }) - if err != nil { - return nil, err - } - err = m.initGateway(ctx, create.Id, clusterId) - if err != nil { - return nil, err - } - return m.Get(ctx, create.Id) -} - -func (m *imlPartition) Search(ctx context.Context, keyword string) ([]*paritiondto.Item, error) { - partitions, err := m.partitionService.Search(ctx, keyword, nil) - if err != nil { - return nil, err - } - countMap, err := m.clusterService.CountByPartition(ctx) - if err != nil { - return nil, err - } - items := utils.SliceToSlice(partitions, func(i *partition.Partition) *paritiondto.Item { - - return &paritiondto.Item{ - Creator: auto.UUID(i.Creator), - Updater: auto.UUID(i.Updater), - Id: i.UUID, - Name: i.Name, - Description: i.Resume, - ClusterNum: countMap[i.UUID], - CreateTime: auto.TimeLabel(i.CreateTime), - UpdateTime: auto.TimeLabel(i.UpdateTime), - } - }) - if len(items) > 0 { - counts, err := m.clusterService.CountByPartition(ctx) - if err != nil { - return nil, err - } - for _, item := range items { - item.ClusterNum = counts[item.Id] - } - } - - return items, nil -} - -func (m *imlPartition) Get(ctx context.Context, id string) (*paritiondto.Detail, error) { - pm, err := m.partitionService.Get(ctx, id) - if err != nil { - return nil, err - } - //oDetails, err := m.organizationService.Search(ctx, "") - //if err != nil { - // return nil, err - //} - //canDelete := true - //for _, o := range oDetails { - // for _, p := range o.Partitions { - // if p == id { - // canDelete = false - // break - // } - // } - // if !canDelete { - // break - // } - //} - - pd := &paritiondto.Detail{ - Creator: auto.UUID(pm.Creator), - Updater: auto.UUID(pm.Updater), - Id: pm.UUID, - Name: pm.Name, - Description: pm.Resume, - Prefix: pm.Prefix, - CreateTime: auto.TimeLabel(pm.CreateTime), - UpdateTime: auto.TimeLabel(pm.UpdateTime), - //CanDelete: canDelete, - } - return pd, nil -} - -func (m *imlPartition) Update(ctx context.Context, id string, edit *paritiondto.Edit) (*paritiondto.Detail, error) { - err := m.partitionService.Save(ctx, id, &partition.EditPartition{ - Name: edit.Name, - Resume: edit.Description, - Prefix: edit.Prefix, - Url: edit.Url, - }) - if err != nil { - return nil, err - } - return m.Get(ctx, id) -} - -func (m *imlPartition) Delete(ctx context.Context, id string) error { - return m.transaction.Transaction(ctx, func(ctx context.Context) error { - info, err := m.partitionService.Get(ctx, id) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil - } - return err - } - err = m.clusterService.Delete(ctx, info.Cluster) - if err != nil { - return err - } - return m.partitionService.Delete(ctx, id) - }) - -} - -func (m *imlPartition) Simple(ctx context.Context) ([]*paritiondto.Simple, error) { - pm, err := m.partitionService.Search(ctx, "", nil) - if err != nil { - return nil, err - } - pd := utils.SliceToSlice(pm, func(i *partition.Partition) *paritiondto.Simple { - return &paritiondto.Simple{ - Id: i.UUID, - Name: i.Name, - } - }) - return pd, nil -} - -func (m *imlPartition) SimpleByIds(ctx context.Context, ids []string) ([]*paritiondto.Simple, error) { - pm, err := m.partitionService.Search(ctx, "", map[string]interface{}{ - "uuid": ids, - }) - if err != nil { - return nil, err - } - pd := utils.SliceToSlice(pm, func(i *partition.Partition) *paritiondto.Simple { - return &paritiondto.Simple{ - Id: i.UUID, - Name: i.Name, - } - }) - return pd, nil - -} -func (m *imlPartition) SimpleWithCluster(ctx context.Context) ([]*paritiondto.SimpleWithCluster, error) { - pm, err := m.partitionService.Search(ctx, "", nil) - if err != nil { - return nil, err - } - - clusterList, err := m.clusterService.List(ctx) - if err != nil { - return nil, err - } - - clusterMap := utils.SliceToMapArrayO(clusterList, func(i *cluster.Cluster) (string, *paritiondto.Cluster) { - return i.Partition, &paritiondto.Cluster{ - Id: i.Uuid, - Name: i.Name, - Description: i.Resume, - } - }) - pd := utils.SliceToSlice(pm, func(i *partition.Partition) *paritiondto.SimpleWithCluster { - return &paritiondto.SimpleWithCluster{ - Id: i.UUID, - Name: i.Name, - Clusters: clusterMap[i.UUID], - } - }) - return pd, nil -} diff --git a/module/partition/partition.go b/module/partition/partition.go deleted file mode 100644 index f0b4ace..0000000 --- a/module/partition/partition.go +++ /dev/null @@ -1,29 +0,0 @@ -package partition - -import ( - "context" - "reflect" - - parition_dto "github.com/eolinker/apipark/module/partition/dto" - "github.com/eolinker/go-common/autowire" -) - -type IPartitionModule interface { - CreatePartition(ctx context.Context, partition *parition_dto.Create) (*parition_dto.Detail, error) - Search(ctx context.Context, keyword string) ([]*parition_dto.Item, error) - Get(ctx context.Context, id string) (*parition_dto.Detail, error) - Update(ctx context.Context, id string, edit *parition_dto.Edit) (*parition_dto.Detail, error) - Delete(ctx context.Context, id string) error - Simple(ctx context.Context) ([]*parition_dto.Simple, error) - SimpleByIds(ctx context.Context, ids []string) ([]*parition_dto.Simple, error) - SimpleWithCluster(ctx context.Context) ([]*parition_dto.SimpleWithCluster, error) - CheckCluster(ctx context.Context, address ...string) ([]*parition_dto.Node, error) - ResetCluster(ctx context.Context, partitionId string, address string) ([]*parition_dto.Node, error) - ClusterNodes(ctx context.Context, partitionId string) ([]*parition_dto.Node, error) -} - -func init() { - autowire.Auto[IPartitionModule](func() reflect.Value { - return reflect.ValueOf(new(imlPartition)) - }) -} diff --git a/module/permit/project/iml.go b/module/permit/project/iml.go index 51b9428..ced8642 100644 --- a/module/permit/project/iml.go +++ b/module/permit/project/iml.go @@ -13,7 +13,6 @@ import ( permit_dto "github.com/eolinker/apipark/module/permit/dto" permit_type "github.com/eolinker/apipark/service/permit-type" "github.com/eolinker/apipark/service/project" - project_member "github.com/eolinker/apipark/service/project-member" "github.com/eolinker/apipark/service/team" team_member "github.com/eolinker/apipark/service/team-member" "github.com/eolinker/eosc/log" @@ -46,16 +45,16 @@ var ( ) type imlProjectPermitModule struct { - projectService project.IProjectService `autowired:""` - teamProject team.ITeamService `autowired:""` - permitService permit.IPermit `autowired:""` - projectMemberService project_member.IMemberService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - identityTeamService permit_identity.IdentityTeamService `autowired:""` - userGroupMemberService user_group.IUserGroupMemberService `autowired:""` - userGroupService user_group.IUserGroupService `autowired:""` - userService user.IUserService `autowired:""` - roleService role.IRoleService `autowired:""` + projectService project.IProjectService `autowired:""` + teamProject team.ITeamService `autowired:""` + permitService permit.IPermit `autowired:""` + //projectMemberService project_member.IMemberService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + identityTeamService permit_identity.IdentityTeamService `autowired:""` + //userGroupMemberService user_group.IUserGroupMemberService `autowired:""` + userGroupService user_group.IUserGroupService `autowired:""` + userService user.IUserService `autowired:""` + roleService role.IRoleService `autowired:""` //projectRoleService project_role.IProjectRoleService `autowired:""` } diff --git a/module/plugin-partition/dto/input.go b/module/plugin-cluster/dto/input.go similarity index 100% rename from module/plugin-partition/dto/input.go rename to module/plugin-cluster/dto/input.go diff --git a/module/plugin-partition/dto/plugin.go b/module/plugin-cluster/dto/plugin.go similarity index 94% rename from module/plugin-partition/dto/plugin.go rename to module/plugin-cluster/dto/plugin.go index 44f0c47..4c66814 100644 --- a/module/plugin-partition/dto/plugin.go +++ b/module/plugin-cluster/dto/plugin.go @@ -23,7 +23,7 @@ type Define struct { Default plugin_model.ConfigType `json:"default"` } type PluginOutput struct { - //Partition auto.Label `json:"partition,omitempty" aolabel:"partition"` + //Cluster auto.Label `json:"partition,omitempty" aolabel:"partition"` Name string `json:"name"` Cname string `json:"cname"` Extend string `json:"extend"` diff --git a/module/plugin-cluster/iml.go b/module/plugin-cluster/iml.go new file mode 100644 index 0000000..b0b9222 --- /dev/null +++ b/module/plugin-cluster/iml.go @@ -0,0 +1,174 @@ +package plugin_cluster + +import ( + "context" + "fmt" + + plugin_cluster "github.com/eolinker/apipark/service/plugin-cluster" + + "github.com/eolinker/apipark/gateway" + "github.com/eolinker/apipark/model/plugin_model" + "github.com/eolinker/apipark/module/plugin-cluster/dto" + "github.com/eolinker/apipark/service/cluster" + "github.com/eolinker/eosc/log" + "github.com/eolinker/go-common/auto" + "github.com/eolinker/go-common/utils" +) + +var ( + _ IPluginClusterModule = (*imlPluginClusterModule)(nil) +) + +type imlPluginClusterModule struct { + service plugin_cluster.IPluginService `autowired:""` + //partitionService partition.IPartitionService `autowired:""` + clusterService cluster.IClusterService `autowired:""` +} + +func (m *imlPluginClusterModule) UpdateDefine(ctx context.Context, defines []*plugin_model.Define) error { + err := m.service.SaveDefine(ctx, defines) + if err != nil { + return err + } + return m.initAllCluster(ctx) +} +func (m *imlPluginClusterModule) initAllCluster(ctx context.Context) error { + + clusters, err := m.clusterService.List(ctx) + if err != nil { + return err + } + + for _, c := range clusters { + err := m.initCluster(ctx, c.Uuid) + if err != nil { + log.Warn("init cluster:%s %s", c.Name, err.Error()) + } + } + return nil +} +func (m *imlPluginClusterModule) initGateway(ctx context.Context, clusterId string, clientDriver gateway.IClientDriver) error { + configForPartitions, err := m.service.ListCluster(ctx, clusterId) + if err != nil { + return err + } + pluginConfigs := utils.SliceToSlice(configForPartitions, func(s *plugin_cluster.ConfigPartition) *gateway.PluginConfig { + + return &gateway.PluginConfig{ + Id: s.Extend, + Name: s.Plugin, + Config: s.Config.Config, + Status: s.Status.String(), + } + }) + + return clientDriver.PluginSetting().Set(ctx, pluginConfigs) +} +func (m *imlPluginClusterModule) GetDefine(ctx context.Context, name string) (*dto.Define, error) { + define, err := m.service.GetDefine(ctx, name) + if err != nil { + return nil, err + } + return &dto.Define{ + Name: define.Name, + Cname: define.Cname, + Desc: define.Desc, + Default: define.Config, + Render: define.Render, + Extend: define.Extend, + }, nil +} + +func (m *imlPluginClusterModule) Options(ctx context.Context) ([]*dto.PluginOption, error) { + defines, err := m.service.Defines(ctx, plugin_model.OpenKind) + if err != nil { + return nil, err + } + + return utils.SliceToSlice(defines, func(s *plugin_cluster.PluginDefine) *dto.PluginOption { + return &dto.PluginOption{ + Name: s.Name, + Cname: s.Cname, + Desc: s.Desc, + Default: s.Config, + Render: s.Render, + } + }), nil +} + +func (m *imlPluginClusterModule) List(ctx context.Context, clusterId string) ([]*dto.Item, error) { + + configPartitions, err := m.service.ListCluster(ctx, clusterId, plugin_model.OpenKind) + if err != nil { + return nil, err + } + return utils.SliceToSlice(configPartitions, func(s *plugin_cluster.ConfigPartition) *dto.Item { + return &dto.Item{ + + Name: s.Plugin, + Cname: s.Cname, + Desc: s.Desc, + Extend: s.Extend, + Operator: auto.UUIDP(s.Operator), + Update: (*auto.TimeLabel)(s.Update), + Create: (*auto.TimeLabel)(s.Create), + } + }), nil +} + +func (m *imlPluginClusterModule) Get(ctx context.Context, clusterId string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) { + if clusterId == "" { + return nil, nil, fmt.Errorf("partition is require") + } + cf, define, err := m.service.GetConfig(ctx, clusterId, name) + if err != nil { + return nil, nil, err + } + if define.Kind != plugin_model.OpenKind { + return nil, nil, fmt.Errorf("plugin %s [extend:%s] not support for setting ", name, define.Extend) + } + out := &dto.PluginOutput{ + //Cluster: auto.UUID(cf.Cluster), + Name: cf.Plugin, + Cname: define.Cname, + Extend: define.Extend, + Desc: define.Desc, + Status: cf.Status, + Config: cf.Config, + } + if cf.Operator != "" { + out.Operator = auto.UUIDP(cf.Operator) + } + if cf.Create != nil { + out.Create = (*auto.TimeLabel)(cf.Create) + } + if cf.Update != nil { + out.Update = (*auto.TimeLabel)(cf.Update) + } + return out, define.Render, nil + +} + +func (m *imlPluginClusterModule) Set(ctx context.Context, clusterId string, name string, config *dto.PluginSetting) error { + + err := m.service.SetCluster(ctx, clusterId, name, config.Status, config.Config) + if err != nil { + return err + } + + return m.initCluster(ctx, clusterId) +} + +func (m *imlPluginClusterModule) initCluster(ctx context.Context, clusterId string) error { + client, err := m.clusterService.GatewayClient(ctx, clusterId) + if err != nil { + return err + } + defer func() { + err := client.Close(ctx) + if err != nil { + log.Warn("close apinto client:", err) + } + }() + return m.initGateway(ctx, clusterId, client) +} diff --git a/module/plugin-partition/plugin-partition.go b/module/plugin-cluster/plugin-partition.go similarity index 56% rename from module/plugin-partition/plugin-partition.go rename to module/plugin-cluster/plugin-partition.go index b9dc854..77c7761 100644 --- a/module/plugin-partition/plugin-partition.go +++ b/module/plugin-cluster/plugin-partition.go @@ -1,26 +1,27 @@ -package plugin_partition +package plugin_cluster import ( "context" + "reflect" + "github.com/eolinker/apipark/gateway" "github.com/eolinker/apipark/model/plugin_model" - "github.com/eolinker/apipark/module/plugin-partition/dto" + "github.com/eolinker/apipark/module/plugin-cluster/dto" "github.com/eolinker/go-common/autowire" - "reflect" ) -type IPluginPartitionModule interface { - List(ctx context.Context, partition string) ([]*dto.Item, error) - Get(ctx context.Context, partition string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) - Set(ctx context.Context, partition string, name string, config *dto.PluginSetting) error +type IPluginClusterModule interface { + List(ctx context.Context, clusterId string) ([]*dto.Item, error) + Get(ctx context.Context, clusterId string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) + Set(ctx context.Context, clusterId string, name string, config *dto.PluginSetting) error Options(ctx context.Context) ([]*dto.PluginOption, error) GetDefine(ctx context.Context, name string) (*dto.Define, error) UpdateDefine(ctx context.Context, defines []*plugin_model.Define) error } func init() { - autowire.Auto[IPluginPartitionModule](func() reflect.Value { - m := new(imlPluginPartitionModule) + autowire.Auto[IPluginClusterModule](func() reflect.Value { + m := new(imlPluginClusterModule) gateway.RegisterInitHandleFunc(m.initGateway) return reflect.ValueOf(m) }) diff --git a/module/plugin-partition/iml.go b/module/plugin-partition/iml.go deleted file mode 100644 index f50e711..0000000 --- a/module/plugin-partition/iml.go +++ /dev/null @@ -1,176 +0,0 @@ -package plugin_partition - -import ( - "context" - "fmt" - - "github.com/eolinker/apipark/gateway" - "github.com/eolinker/apipark/model/plugin_model" - "github.com/eolinker/apipark/module/plugin-partition/dto" - "github.com/eolinker/apipark/service/cluster" - "github.com/eolinker/apipark/service/partition" - pluginPartition "github.com/eolinker/apipark/service/plugin-partition" - "github.com/eolinker/eosc/log" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/go-common/utils" -) - -var ( - _ IPluginPartitionModule = (*imlPluginPartitionModule)(nil) -) - -type imlPluginPartitionModule struct { - service pluginPartition.IPluginService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` -} - -func (m *imlPluginPartitionModule) UpdateDefine(ctx context.Context, defines []*plugin_model.Define) error { - err := m.service.SaveDefine(ctx, defines) - if err != nil { - return err - } - return m.initAllPartition(ctx) -} -func (m *imlPluginPartitionModule) initAllPartition(ctx context.Context) error { - partitions, err := m.partitionService.List(ctx) - if err != nil { - return err - } - - for _, p := range partitions { - err := m.initPartition(ctx, p) - if err != nil { - log.Warn("init partition:%s %s", p.Name, err.Error()) - } - } - return nil -} -func (m *imlPluginPartitionModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - configForPartitions, err := m.service.ListPartition(ctx, partitionId) - if err != nil { - return err - } - pluginConfigs := utils.SliceToSlice(configForPartitions, func(s *pluginPartition.ConfigPartition) *gateway.PluginConfig { - - return &gateway.PluginConfig{ - Id: s.Extend, - Name: s.Plugin, - Config: s.Config.Config, - Status: s.Status.String(), - } - }) - - return clientDriver.PluginSetting().Set(ctx, pluginConfigs) -} -func (m *imlPluginPartitionModule) GetDefine(ctx context.Context, name string) (*dto.Define, error) { - define, err := m.service.GetDefine(ctx, name) - if err != nil { - return nil, err - } - return &dto.Define{ - Name: define.Name, - Cname: define.Cname, - Desc: define.Desc, - Default: define.Config, - Render: define.Render, - Extend: define.Extend, - }, nil -} - -func (m *imlPluginPartitionModule) Options(ctx context.Context) ([]*dto.PluginOption, error) { - defines, err := m.service.Defines(ctx, plugin_model.OpenKind) - if err != nil { - return nil, err - } - - return utils.SliceToSlice(defines, func(s *pluginPartition.PluginDefine) *dto.PluginOption { - return &dto.PluginOption{ - Name: s.Name, - Cname: s.Cname, - Desc: s.Desc, - Default: s.Config, - Render: s.Render, - } - }), nil -} - -func (m *imlPluginPartitionModule) List(ctx context.Context, partition string) ([]*dto.Item, error) { - - configPartitions, err := m.service.ListPartition(ctx, partition, plugin_model.OpenKind) - if err != nil { - return nil, err - } - return utils.SliceToSlice(configPartitions, func(s *pluginPartition.ConfigPartition) *dto.Item { - return &dto.Item{ - - Name: s.Plugin, - Cname: s.Cname, - Desc: s.Desc, - Extend: s.Extend, - Operator: auto.UUIDP(s.Operator), - Update: (*auto.TimeLabel)(s.Update), - Create: (*auto.TimeLabel)(s.Create), - } - }), nil -} - -func (m *imlPluginPartitionModule) Get(ctx context.Context, partition string, name string) (config *dto.PluginOutput, render plugin_model.Render, er error) { - if partition == "" { - return nil, nil, fmt.Errorf("partition is require") - } - cf, define, err := m.service.GetConfig(ctx, partition, name) - if err != nil { - return nil, nil, err - } - if define.Kind != plugin_model.OpenKind { - return nil, nil, fmt.Errorf("plugin %s [extend:%s] not support for setting ", name, define.Extend) - } - out := &dto.PluginOutput{ - //Partition: auto.UUID(cf.Partition), - Name: cf.Plugin, - Cname: define.Cname, - Extend: define.Extend, - Desc: define.Desc, - Status: cf.Status, - Config: cf.Config, - } - if cf.Operator != "" { - out.Operator = auto.UUIDP(cf.Operator) - } - if cf.Create != nil { - out.Create = (*auto.TimeLabel)(cf.Create) - } - if cf.Update != nil { - out.Update = (*auto.TimeLabel)(cf.Update) - } - return out, define.Render, nil - -} - -func (m *imlPluginPartitionModule) Set(ctx context.Context, partition string, name string, config *dto.PluginSetting) error { - - err := m.service.SetPartition(ctx, partition, name, config.Status, config.Config) - if err != nil { - return err - } - partitionInfo, err := m.partitionService.Get(ctx, partition) - if err != nil { - return err - } - return m.initPartition(ctx, partitionInfo) -} - -func (m *imlPluginPartitionModule) initPartition(ctx context.Context, partitionInfo *partition.Partition) error { - client, err := m.clusterService.GatewayClient(ctx, partitionInfo.Cluster) - if err != nil { - return err - } - defer func() { - err := client.Close(ctx) - if err != nil { - log.Warn("close apinto client:", err) - } - }() - return m.initGateway(ctx, partitionInfo.UUID, client) -} diff --git a/module/project-authorization/iml.go b/module/project-authorization/iml.go index 155b16a..79718a5 100644 --- a/module/project-authorization/iml.go +++ b/module/project-authorization/iml.go @@ -7,8 +7,6 @@ import ( "fmt" "time" - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/eosc/log" authDriver "github.com/eolinker/apipark/module/project-authorization/auth-driver" @@ -36,7 +34,6 @@ var _ IProjectAuthorizationModule = (*imlProjectAuthorizationModule)(nil) type imlProjectAuthorizationModule struct { projectService project.IProjectService `autowired:""` projectAuthorizationService projectAuthorization.IProjectAuthorizationService `autowired:""` - partitionService partition.IPartitionService `autowired:""` clusterService cluster.IClusterService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -103,14 +100,7 @@ func (i *imlProjectAuthorizationModule) initGateway(ctx context.Context, partiti func (i *imlProjectAuthorizationModule) online(ctx context.Context, projectInfo *project.Project) error { - partitions, err := i.partitionService.List(ctx) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { - return p.UUID - }) - clusters, err := i.clusterService.List(ctx, partitionIds...) + clusters, err := i.clusterService.List(ctx) if err != nil { return err } @@ -144,7 +134,7 @@ func (i *imlProjectAuthorizationModule) online(ctx context.Context, projectInfo for _, c := range clusters { err := i.doOnline(ctx, c.Uuid, app) if err != nil { - log.Warnf("project authorization online for partition[%s] %v", c.Partition, err) + log.Warnf("project authorization online for cluster[%s] %v", c.Name, err) } } return nil @@ -263,19 +253,13 @@ func (i *imlProjectAuthorizationModule) DeleteAuthorization(ctx context.Context, if err != nil { return err } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { - return p.UUID - }) + return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.projectAuthorizationService.Delete(ctx, aid) if err != nil { return err } - clusters, err := i.clusterService.List(ctx, partitionIds...) + clusters, err := i.clusterService.List(ctx) if err != nil { return err } @@ -287,7 +271,7 @@ func (i *imlProjectAuthorizationModule) DeleteAuthorization(ctx context.Context, for _, c := range clusters { err := i.doOffline(ctx, c.Uuid, app) if err != nil { - log.Warnf("project authorization offline for partition[%s] %v", c.Partition, err) + log.Warnf("project authorization offline for cluster[%s] %v", c.Name, err) } } return nil diff --git a/module/project/dto/output.go b/module/project/dto/output.go index f7312f1..4c58336 100644 --- a/module/project/dto/output.go +++ b/module/project/dto/output.go @@ -6,19 +6,14 @@ import ( ) type ProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - //Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - ApiNum int64 `json:"api_num"` - ServiceNum int64 `json:"service_num"` - //SubscribeNum int64 `json:"subscribe_num"` - Description string `json:"description"` - //Master auto.Label `json:"master" aolabel:"user"` - //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - CanDelete bool `json:"can_delete"` + Id string `json:"id"` + Name string `json:"name"` + Team auto.Label `json:"team" aolabel:"team"` + ApiNum int64 `json:"api_num"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + CanDelete bool `json:"can_delete"` } type AppItem struct { @@ -34,12 +29,10 @@ type AppItem struct { } type SimpleProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - //Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - Description string `json:"description"` + Id string `json:"id"` + Name string `json:"name"` + Team auto.Label `json:"team" aolabel:"team"` + Description string `json:"description"` } type SimpleAppItem struct { @@ -50,19 +43,15 @@ type SimpleAppItem struct { } type Project struct { - Id string `json:"id"` - Name string `json:"name"` - Prefix string `json:"prefix,omitempty"` - Description string `json:"description"` - //Organization auto.Label `json:"organization" aolabel:"organization"` - Team auto.Label `json:"team" aolabel:"team"` - //Master auto.Label `json:"master" aolabel:"user"` - //Partition []auto.Label `json:"partition,omitempty" aolabel:"partition"` - //OrganizationPrefix string `json:"organization_prefix,omitempty"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - AsServer bool `json:"as_server"` - AsApp bool `json:"as_app"` + Id string `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix,omitempty"` + Description string `json:"description"` + Team auto.Label `json:"team" aolabel:"team"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + AsServer bool `json:"as_server"` + AsApp bool `json:"as_app"` } type App struct { diff --git a/module/project/iml.go b/module/project/iml.go index 6395ae8..42805d5 100644 --- a/module/project/iml.go +++ b/module/project/iml.go @@ -7,15 +7,15 @@ import ( "sort" "strings" - "github.com/eolinker/apipark/service/partition" + "github.com/eolinker/apipark/service/tag" + + "github.com/eolinker/apipark/service/service" "github.com/eolinker/apipark/service/subscribe" "gorm.io/gorm" "github.com/eolinker/apipark/service/api" - "github.com/eolinker/apipark/service/service" - "github.com/eolinker/go-common/auto" team_member "github.com/eolinker/apipark/service/team-member" @@ -38,11 +38,10 @@ var ( ) type imlProjectModule struct { - partitionService partition.IPartitionService `autowired:""` - projectService project.IProjectService `autowired:""` - //projectMemberService project_member.IMemberService `autowired:""` + projectService project.IProjectService `autowired:""` teamService team.ITeamService `autowired:""` teamMemberService team_member.ITeamMemberService `autowired:""` + tagService tag.ITagService `autowired:""` serviceService service.IServiceService `autowired:""` apiService api.IAPIService `autowired:""` transaction store.ITransaction `autowired:""` @@ -84,10 +83,6 @@ func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, if err != nil { return nil, err } - serviceCountMap, err := i.serviceService.CountByGroup(ctx, "", map[string]interface{}{"project": projectIDs}, "project") - if err != nil { - return nil, err - } items := make([]*project_dto.ProjectItem, 0, len(projects)) for _, model := range projects { @@ -95,18 +90,15 @@ func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, continue } apiCount := apiCountMap[model.Id] - serviceCount := serviceCountMap[model.Id] items = append(items, &project_dto.ProjectItem{ Id: model.Id, Name: model.Name, Description: model.Description, - //Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + CanDelete: apiCount == 0, }) } return items, nil @@ -138,7 +130,7 @@ func (i *imlProjectModule) SimpleProjects(ctx context.Context, keyword string) ( // if err != nil { // return nil, err // } - // w["uuid"] = utils.SliceToSlice(pp, func(p *project.Partition) string { + // w["uuid"] = utils.SliceToSlice(pp, func(p *project.Cluster) string { // return p.Project // }) //} @@ -226,13 +218,11 @@ func (i *imlProjectModule) Search(ctx context.Context, teamID string, keyword st Id: model.Id, Name: model.Name, Description: model.Description, - //Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - ServiceNum: serviceCount, - CanDelete: apiCount == 0 && serviceCount == 0, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + CanDelete: apiCount == 0 && serviceCount == 0, }) } return items, nil @@ -247,9 +237,8 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp Id: input.Id, Name: input.Name, Description: input.Description, - //Master: input.Master, - Team: teamID, - Prefix: input.Prefix, + Team: teamID, + Prefix: input.Prefix, } if input.AsApp == nil { // 默认值为false @@ -265,19 +254,7 @@ func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, inp } input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") err := i.transaction.Transaction(ctx, func(ctx context.Context) error { - - //// 判断用户是否在团队内 - //members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{input.Master}) - //if err != nil { - // return err - //} - //if len(members) == 0 { - // return fmt.Errorf("master is not in team") - //} - return i.projectService.Create(ctx, mo) - - //return i.projectMemberService.AddMemberTo(ctx, input.Id, input.Master) }) if err != nil { return nil, err @@ -292,36 +269,9 @@ func (i *imlProjectModule) EditProject(ctx context.Context, id string, input *pr } err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - //if input.Master != nil { - //projectInfo, err := i.projectService.Get(ctx, id) - //if err != nil { - // return err - //} - - //// 判断用户是否在团队内 - //members, err := i.teamMemberService.Members(ctx, []string{projectInfo.Team}, []string{*input.Master}) - //if err != nil { - // return err - //} - //if len(members) == 0 { - // return fmt.Errorf("master is not in team") - //} - //// 负责人是否在项目内,若不在,则新增 - //projectMembers, err := i.projectMemberService.Members(ctx, []string{id}, []string{*input.Master}) - //if err != nil { - // return err - //} - //if len(projectMembers) == 0 { - // err = i.projectMemberService.AddMemberTo(ctx, id, *input.Master) - // if err != nil { - // return err - // } - //} - //} return i.projectService.Save(ctx, id, &project.EditProject{ Name: input.Name, Description: input.Description, - //Master: input.Master, }) }) @@ -341,205 +291,59 @@ func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { if count > 0 { return fmt.Errorf("project has apis, can not delete") } - //// 删除项目成员 - //err = i.projectMemberService.Delete(ctx, id) - //if err != nil { - // return err - //} return i.projectService.Delete(ctx, id) }) return err } -//var _ IProjectMemberModule = (*imlProjectMemberModule)(nil) -// -//type imlProjectMemberModule struct { -// projectService project.IProjectService `autowired:""` -// projectMemberService project_member.IMemberService `autowired:""` -// //projectRoleService project_role.IProjectRoleService `autowired:""` -// userService user.IUserService `autowired:""` -// transaction store.ITransaction `autowired:""` -// teamMemberService team_member.ITeamMemberService `autowired:""` -//} -// -//func (i *imlProjectMemberModule) SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { -// -// pro, err := i.projectService.Get(ctx, pid) -// if err != nil { -// return nil, err -// } -// -// users, err := i.userService.Search(ctx, keyword, -1) -// if err != nil { -// return nil, err -// } -// userIds := utils.SliceToSlice(users, func(s *user.User) string { -// return s.UID -// }) -// -// members, err := i.teamMemberService.Members(ctx, []string{pro.Team}, userIds) -// if err != nil { -// return nil, err -// } -// userMaps := utils.SliceToMap(users, func(s *user.User) string { -// return s.UID -// }) -// -// return utils.SliceToSlice(members, func(s *member.Member) *project_dto.TeamMemberToAdd { -// uf := userMaps[s.UID] -// return &project_dto.TeamMemberToAdd{ -// Id: uf.UID, -// Name: uf.Username, -// Email: uf.Email, -// //Department: uf., -// } -// }, func(m *member.Member) bool { -// _, has := userMaps[m.UID] -// return has -// }), nil -// -//} -// -//func (i *imlProjectMemberModule) SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { -// members, err := i.projectMemberService.Members(ctx, []string{pid}, nil) -// if err != nil { -// return nil, err -// } -// userIds := utils.SliceToSlice(members, func(s *member.Member) string { -// return s.UID -// }) -// users, err := i.userService.Get(ctx, userIds...) -// if err != nil { -// return nil, err -// } -// out := utils.SliceToSlice(users, func(s *user.User) *project_dto.SimpleMemberItem { -// return &project_dto.SimpleMemberItem{ -// Id: s.UID, -// Name: s.Username, -// } -// }) -// return out, nil -//} - -// -//func (i *imlProjectMemberModule) Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { -// pInfo, err := i.projectService.Get(ctx, id) -// if err != nil { -// return nil, err -// } -// users, err := i.userService.Search(ctx, keyword, -1) -// if err != nil { -// return nil, err -// } -// userMap := make(map[string]*user.User) -// userIds := make([]string, 0, len(users)) -// for _, u := range users { -// userIds = append(userIds, u.UID) -// userMap[u.UID] = u -// } -// members, err := i.projectMemberService.Members(ctx, []string{id}, userIds) -// if err != nil { -// return nil, err -// } -// roleMap, err := i.projectRoleService.RoleMap(ctx, id) -// if err != nil { -// return nil, err -// } -// -// out := utils.SliceToSlice(members, func(info *project_member.Member) *project_dto.MemberItem { -// roleIDs := make([]string, 0, len(roleMap[info.UID])) -// for _, r := range roleMap[info.UID] { -// roleIDs = append(roleIDs, r.Rid) -// } -// item := &project_dto.MemberItem{ -// User: auto.UUID(info.UID), -// Email: "", -// Roles: auto.List(roleIDs), -// } -// -// u, ok := userMap[info.UID] -// if ok { -// item.Email = u.Email -// } -// if pInfo.Master == info.UID { -// item.CanDelete = false -// } else { -// item.CanDelete = true -// } -// return item -// -// }) -// return out, nil -//} -// -//func (i *imlProjectMemberModule) AddMember(ctx context.Context, pid string, userIDs []string) error { -// _, err := i.projectService.Get(ctx, pid) -// if err != nil { -// return err -// } -// return i.projectMemberService.AddMemberTo(ctx, pid, userIDs...) -//} -// -//func (i *imlProjectMemberModule) RemoveMember(ctx context.Context, pid string, userIDs []string) error { -// // 删除的成员是否有项目负责人 -// info, err := i.projectService.Get(ctx, pid) -// if err != nil { -// return err -// } -// uids := make([]string, 0, len(userIDs)) -// for _, id := range userIDs { -// if id != info.Master { -// uids = append(uids, id) -// } -// } -// if len(uids) == 0 { -// return nil -// } -// return i.projectMemberService.RemoveMemberFrom(ctx, pid, userIDs...) -//} -// -//func (i *imlProjectMemberModule) EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error { -// return i.transaction.Transaction(ctx, func(ctx context.Context) error { -// _, err := i.projectService.Get(ctx, pid) -// if err != nil { -// return err -// } -// _, err = i.userService.Get(ctx, uid) -// if err != nil { -// return err -// } -// -// err = i.projectRoleService.DeleteRole(ctx, pid, uid) -// if err != nil { -// return err -// } -// for _, rid := range roles { -// err = i.projectRoleService.AddRole(ctx, pid, uid, rid) -// if err != nil { -// return err -// } -// } -// return nil -// }) -//} +func (i *imlProjectModule) getTagUuids(ctx context.Context, tags []string) ([]string, error) { + list, err := i.tagService.Search(ctx, "", map[string]interface{}{"name": tags}) + if err != nil { + return nil, err + } + tagMap := make(map[string]string) + for _, t := range list { + tagMap[t.Name] = t.Id + } + tagList := make([]string, 0, len(tags)) + repeatTag := make(map[string]struct{}) + for _, t := range tags { + if _, ok := repeatTag[t]; ok { + continue + } + repeatTag[t] = struct{}{} + v := &tag.CreateTag{ + Name: t, + } + id, ok := tagMap[t] + if !ok { + v.Id = uuid.New().String() + err = i.tagService.Create(ctx, v) + if err != nil { + return nil, err + } + tagMap[t] = v.Id + } else { + v.Id = id + } + tagList = append(tagList, v.Id) + } + return tagList, nil +} var _ IAppModule = &imlAppModule{} type imlAppModule struct { - teamService team.ITeamService `autowired:""` - projectService project.IProjectService `autowired:""` - //projectMemberService project_member.IMemberService `autowired:""` + teamService team.ITeamService `autowired:""` + projectService project.IProjectService `autowired:""` teamMemberService team_member.ITeamMemberService `autowired:""` subscribeService subscribe.ISubscribeService `autowired:""` transaction store.ITransaction `autowired:""` } func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) { - //teamInfo, err := i.teamService.Get(ctx, teamID) - //if err != nil { - // return nil, err - //} + if input.Id == "" { input.Id = uuid.New().String() } @@ -548,9 +352,8 @@ func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *proj Id: input.Id, Name: input.Name, Description: input.Description, - //Master: userId, - Team: teamID, - AsApp: true, + Team: teamID, + AsApp: true, } // 判断用户是否在团队内 members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{userId}) @@ -564,11 +367,7 @@ func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *proj err = i.transaction.Transaction(ctx, func(ctx context.Context) error { return i.projectService.Create(ctx, mo) - //if err != nil { - // return err - //} - // - //return i.projectMemberService.AddMemberTo(ctx, input.Id, userId) + }) if err != nil { return nil, err @@ -603,7 +402,6 @@ func (i *imlAppModule) searchMyApps(ctx context.Context, teamId string, keyword userID := utils.UserId(ctx) condition := make(map[string]interface{}) condition["as_app"] = true - condition["master"] = userID if teamId != "" { _, err := i.teamService.Get(ctx, teamId) if err != nil { @@ -751,8 +549,6 @@ func (i *imlAppModule) DeleteApp(ctx context.Context, appId string) error { if !info.AsApp { return errors.New("not app, can not delete") } - //if info.Master != utils.UserId(ctx) { - // return errors.New("not master, can not delete") - //} + return i.projectService.Delete(ctx, appId) } diff --git a/module/project_diff/iml.go b/module/project_diff/iml.go index 816be78..f0c562d 100644 --- a/module/project_diff/iml.go +++ b/module/project_diff/iml.go @@ -5,11 +5,8 @@ import ( "errors" "fmt" - "gorm.io/gorm" - "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/cluster" - "github.com/eolinker/apipark/service/partition" "github.com/eolinker/apipark/service/project_diff" "github.com/eolinker/apipark/service/release" "github.com/eolinker/apipark/service/universally/commit" @@ -19,24 +16,17 @@ import ( ) type imlProjectDiff struct { - apiService api.IAPIService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - releaseService release.IReleaseService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` + apiService api.IAPIService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + releaseService release.IReleaseService `autowired:""` + clusterService cluster.IClusterService `autowired:""` } func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease, targetRelease string) (*project_diff.Diff, error) { if targetRelease == "" { return nil, fmt.Errorf("target release is required") } - partitions, err := m.partitionService.List(ctx) - if err != nil { - return nil, err - } - if len(partitions) == 0 { - return nil, fmt.Errorf("no partition for project %s", projectId) - } + var target *projectInfo targetReleaseValue, err := m.releaseService.GetRelease(ctx, targetRelease) @@ -56,10 +46,14 @@ func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease return nil, err } target.id = projectId - partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { - return i.UUID + clusters, err := m.clusterService.List(ctx) + if err != nil { + return nil, err + } + clusterIds := utils.SliceToSlice(clusters, func(i *cluster.Cluster) string { + return i.Uuid }) - diff := m.diff(partitionIds, base, target) + diff := m.diff(clusterIds, base, target) return diff, nil } @@ -120,14 +114,14 @@ func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, ba apiDocs: documents, upstreamCommits: upstreamCommits, } - partitions, err := m.partitionService.List(ctx) + clusters, err := m.clusterService.List(ctx) if err != nil { return nil, false, err } - partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { - return i.UUID + clusterIds := utils.SliceToSlice(clusters, func(i *cluster.Cluster) string { + return i.Uuid }) - return m.diff(partitionIds, base, target), true, nil + return m.diff(clusterIds, base, target), true, nil } func (m *imlProjectDiff) getReleaseInfo(ctx context.Context, releaseId string) (*projectInfo, error) { commits, err := m.releaseService.GetCommits(ctx, releaseId) @@ -182,7 +176,7 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p out := &project_diff.Diff{ Apis: nil, Upstreams: nil, - //Partitions: partitions, + //Clusters: partitions, } baseApis := utils.NewSet(utils.SliceToSlice(base.apis, func(i *api.APIInfo) string { return i.UUID @@ -297,32 +291,34 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p func (m *imlProjectDiff) Out(ctx context.Context, diff *project_diff.Diff) (*DiffOut, error) { - partitions, err := m.partitionService.List(ctx, diff.Partitions...) + clusters, err := m.clusterService.List(ctx, diff.Clusters...) if err != nil { return nil, err } - - // 检查分区是否配置集群,若没有配置,则报错 - requirePartition := make([]*partition.Partition, 0, len(partitions)) - for _, p := range partitions { - if p.Cluster == "" { - requirePartition = append(requirePartition, p) - continue - } - _, err = m.clusterService.Get(ctx, p.Cluster) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - requirePartition = append(requirePartition, p) - continue - } - return nil, err - } - - } - - if len(requirePartition) > 0 { - return nil, fmt.Errorf("unset gateway for partitions %v", requirePartition) - } + if len(clusters) == 0 { + return nil, fmt.Errorf("unset gateway for clusters %v", diff.Clusters) + } + //// 检查分区是否配置集群,若没有配置,则报错 + //requirePartition := make([]*partition.Partition, 0, len(partitions)) + //for _, p := range partitions { + // if p.Cluster == "" { + // requirePartition = append(requirePartition, p) + // continue + // } + // _, err = m.clusterService.Get(ctx, p.Cluster) + // if err != nil { + // if !errors.Is(err, gorm.ErrRecordNotFound) { + // requirePartition = append(requirePartition, p) + // continue + // } + // return nil, err + // } + // + //} + // + //if len(requirePartition) > 0 { + // return nil, fmt.Errorf("unset gateway for partitions %v", requirePartition) + //} out := &DiffOut{} out.Apis = utils.SliceToSlice(diff.Apis, func(i *project_diff.ApiDiff) *ApiDiffOut { diff --git a/module/project_diff/out.go b/module/project_diff/out.go index 77d6781..f07a4ff 100644 --- a/module/project_diff/out.go +++ b/module/project_diff/out.go @@ -50,8 +50,8 @@ type UpstreamDiffOut struct { // Upstreams: utils.SliceToSlice(d.Upstreams, func(s *project_diff.UpstreamDiff) *UpstreamDiffOut { // return &UpstreamDiffOut{ // Upstream: s.Name, -// Partition: auto.UUID(s.Partition), -// Partition: auto.UUID(s.Partition), +// Cluster: auto.UUID(s.Cluster), +// Cluster: auto.UUID(s.Cluster), // Change: s.Change, // Type: s.Type, // Addr: s.Addr, diff --git a/module/publish/dto/out.go b/module/publish/dto/out.go index 6165ff9..509a045 100644 --- a/module/publish/dto/out.go +++ b/module/publish/dto/out.go @@ -53,8 +53,8 @@ type PublishDetail struct { } type PublishStatus struct { - Partition auto.Label `json:"partition" aolabel:"partition"` - Cluster auto.Label `json:"cluster" aolabel:"cluster"` - Status string `json:"status"` - Error string `json:"error"` + //Partition auto.Label `json:"partition" aolabel:"partition"` + Cluster auto.Label `json:"cluster" aolabel:"cluster"` + Status string `json:"status"` + Error string `json:"error"` } diff --git a/module/publish/iml.go b/module/publish/iml.go index 86a232b..f65f698 100644 --- a/module/publish/iml.go +++ b/module/publish/iml.go @@ -6,8 +6,6 @@ import ( "fmt" "time" - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/apipark/service/universally/commit" "github.com/eolinker/apipark/service/api" @@ -45,7 +43,6 @@ type imlPublishModule struct { upstreamService upstream.IUpstreamService `autowired:""` releaseService release.IReleaseService `autowired:""` clusterService cluster.IClusterService `autowired:""` - partitionService partition.IPartitionService `autowired:""` projectService project.IProjectService `autowired:""` } @@ -176,7 +173,7 @@ func (m *imlPublishModule) getProjectRelease(ctx context.Context, projectID stri }, nil } -func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releaseId string, version string, partitionIds []string) (map[string]*gateway.ProjectRelease, error) { +func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releaseId, version string, clusterIds []string) (map[string]*gateway.ProjectRelease, error) { commits, err := m.releaseService.GetCommits(ctx, releaseId) if err != nil { return nil, err @@ -248,7 +245,7 @@ func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releas upstreamReleaseMap := make(map[string]*gateway.UpstreamRelease) for _, c := range upstreamCommits { - for _, partitionId := range partitionIds { + for _, partitionId := range clusterIds { upstreamRelease := &gateway.UpstreamRelease{ BasicItem: &gateway.BasicItem{ ID: c.Target, @@ -270,7 +267,7 @@ func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releas } } - for _, clusterId := range partitionIds { + for _, clusterId := range clusterIds { projectReleaseMap[clusterId] = &gateway.ProjectRelease{ Id: projectID, Version: version, @@ -305,10 +302,9 @@ func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, errMsg = "发布超时" } return &dto.PublishStatus{ - Partition: auto.UUID(s.Partition), - Cluster: auto.UUID(s.Cluster), - Status: status.String(), - Error: errMsg, + Cluster: auto.UUID(s.Cluster), + Status: status.String(), + Error: errMsg, } }), nil @@ -467,18 +463,14 @@ func (m *imlPublishModule) Accept(ctx context.Context, project string, id string return m.publishService.Accept(ctx, project, id, commits) } -func (m *imlPublishModule) publish(ctx context.Context, id string, partitionId string, projectRelease *gateway.ProjectRelease) error { - pInfo, err := m.partitionService.Get(ctx, partitionId) - if err != nil { - return err - } +func (m *imlPublishModule) publish(ctx context.Context, id string, clusterId string, projectRelease *gateway.ProjectRelease) error { + publishStatus := &publish.Status{ - Publish: id, - Partition: partitionId, - Status: publish.StatusPublishing, - UpdateAt: time.Now(), + Publish: id, + Status: publish.StatusPublishing, + UpdateAt: time.Now(), } - err = m.publishService.SetPublishStatus(ctx, publishStatus) + err := m.publishService.SetPublishStatus(ctx, publishStatus) if err != nil { return fmt.Errorf("set publishing publishStatus error: %v", err) } @@ -489,7 +481,7 @@ func (m *imlPublishModule) publish(ctx context.Context, id string, partitionId s } }() - client, err := m.clusterService.GatewayClient(ctx, pInfo.Cluster) + client, err := m.clusterService.GatewayClient(ctx, clusterId) if err != nil { publishStatus.Status = publish.StatusPublishError publishStatus.Error = err.Error() @@ -529,20 +521,22 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin if flow.Status != publish.StatusAccept { return errors.New("只有通过状态才能发布") } - partitions, err := m.partitionService.List(ctx) + clusters, err := m.clusterService.List(ctx) if err != nil { return err } - partitionIds := utils.SliceToSlice(partitions, func(p *partition.Partition) string { - return p.UUID + clusterIds := utils.SliceToSlice(clusters, func(i *cluster.Cluster) string { + return i.Uuid }) - projectReleaseMap, err := m.getReleaseInfo(ctx, project, flow.Release, flow.Release, partitionIds) + + projectReleaseMap, err := m.getReleaseInfo(ctx, project, flow.Release, flow.Release, clusterIds) if err != nil { return err } hasError := false - for _, partitionId := range partitionIds { - err = m.publish(ctx, flow.Id, partitionId, projectReleaseMap[partitionId]) + + for _, c := range clusters { + err = m.publish(ctx, flow.Id, c.Uuid, projectReleaseMap[c.Uuid]) if err != nil { hasError = true log.Error(err) diff --git a/module/release/iml.go b/module/release/iml.go index 7f56a6a..93de49d 100644 --- a/module/release/iml.go +++ b/module/release/iml.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "github.com/eolinker/apipark/service/partition" + "github.com/eolinker/apipark/service/cluster" projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/release/dto" @@ -37,7 +37,7 @@ type imlReleaseModule struct { publishService publish.IPublishService `autowired:""` transaction store.ITransaction `autowired:""` projectService project.IProjectService `autowired:""` - partitionService partition.IPartitionService `autowired:""` + clusterService cluster.IClusterService `autowired:""` } func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input *dto.CreateInput) (string, error) { @@ -49,9 +49,9 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * } return "", err } - partitions, err := m.partitionService.List(ctx) - if err != nil { - return "", fmt.Errorf("partitions not set:%w", err) + clusters, err := m.clusterService.List(ctx) + if err != nil || len(clusters) == 0 { + return "", fmt.Errorf("cluster not set:%w", err) } apis, err := m.apiService.ListForProject(ctx, proInfo.Id) @@ -109,8 +109,8 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * return c.Key, c.UUID }) }) - if !m.releaseService.Completeness(utils.SliceToSlice(partitions, func(s *partition.Partition) string { - return s.UUID + if !m.releaseService.Completeness(utils.SliceToSlice(clusters, func(s *cluster.Cluster) string { + return s.Uuid }), apiUUIDS, apiProxy, apiDocs, upstreams) { return "", errors.New("completeness check failed") } diff --git a/module/service/iml.go b/module/service/iml.go index 19f2607..df46a90 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -3,30 +3,12 @@ package service import ( "context" "errors" - "fmt" - "strings" - - "github.com/eolinker/apipark/service/partition" - "github.com/eolinker/apipark/service/subscribe" - "github.com/eolinker/eosc/log" - - "github.com/eolinker/apipark/gateway" - - "github.com/eolinker/apipark/service/cluster" - - "github.com/eolinker/apipark/service/api" + "github.com/eolinker/apipark/service/project" "gorm.io/gorm" - "github.com/eolinker/go-common/utils" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/apipark/service/tag" - - "github.com/eolinker/apipark/service/project" - "github.com/google/uuid" - serviceDto "github.com/eolinker/apipark/module/service/dto" "github.com/eolinker/apipark/service/service" "github.com/eolinker/go-common/store" @@ -40,275 +22,35 @@ var ( ) type imlServiceModule struct { - projectService project.IProjectService `autowired:""` - serviceService service.IServiceService `autowired:""` - serviceTagService service.ITagService `autowired:""` - servicePartitionService service.IPartitionsService `autowired:""` - serviceDocService service.IDocService `autowired:""` - tagService tag.ITagService `autowired:""` - serviceApiService service.IApiService `autowired:""` - apiService api.IAPIService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - clusterService cluster.IClusterService `autowired:""` + projectService project.IProjectService `autowired:""` + serviceDocService service.IDocService `autowired:""` transaction store.ITransaction `autowired:""` } -func (i *imlServiceModule) getServiceApis(ctx context.Context, projectIds []string) ([]*gateway.ServiceRelease, error) { - services, err := i.serviceService.ListByProject(ctx, projectIds...) - if err != nil { - return nil, err - } - serviceIds := utils.SliceToSlice(services, func(s *service.Service) string { - return s.Id - }, func(s *service.Service) bool { - return s.Status == service.StatusOn - }) - apis, err := i.serviceApiService.List(ctx, serviceIds...) - if err != nil { - return nil, err - } - serviceMap := utils.SliceToMapArrayO(apis, func(s *service.Api) (string, string) { - return s.Sid, s.Aid - }) - - return utils.MapToSlice(serviceMap, func(k string, v []string) *gateway.ServiceRelease { - return &gateway.ServiceRelease{ - ID: k, - Apis: v, - } - }), nil -} - -func (i *imlServiceModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projects, err := i.projectService.List(ctx) - projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { - return p.Id - }) - releases, err := i.getServiceApis(ctx, projectIds) - if err != nil { - return err - } - - return clientDriver.Service().Online(ctx, releases...) - -} - -func (i *imlServiceModule) SimpleList(ctx context.Context, pid string) ([]*serviceDto.SimpleItem, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - list, err := i.serviceService.Search(ctx, "", map[string]interface{}{ - "project": pid, - }) - return utils.SliceToSlice(list, func(i *service.Service) *serviceDto.SimpleItem { - return &serviceDto.SimpleItem{ - Id: i.Id, - Name: i.Name, - } - }), nil -} - -func (i *imlServiceModule) syncServiceApi(ctx context.Context, sid string, apiIds []string, partitionIds []string, isOnline bool) error { - partitions, err := i.partitionService.List(ctx, partitionIds...) - if err != nil { - return err - } - - for _, p := range partitions { - err := i.syncServiceApiForCluster(ctx, p.Cluster, sid, apiIds, isOnline) - if err != nil { - log.Warnf("sync service api for partition[%s] %s", p.UUID, err.Error()) - } - } - return nil -} -func (i *imlServiceModule) syncServiceApiForCluster(ctx context.Context, clusterId string, sid string, apiIds []string, isOnline bool) error { - client, err := i.clusterService.GatewayClient(ctx, clusterId) - if err != nil { - return err - } - defer func() { - err := client.Close(ctx) - if err != nil { - log.Warn("close apinto client:", err) - } - }() - if !isOnline { - err = client.Service().Offline(ctx, &gateway.ServiceRelease{ - ID: sid, - Apis: apiIds, - }) - if err != nil { - return err - } - } else { - err = client.Service().Online(ctx, &gateway.ServiceRelease{ - ID: sid, - Apis: apiIds, - }) - if err != nil { - return err - } - } - return nil -} -func (i *imlServiceModule) BindServiceApi(ctx context.Context, pid string, sid string, apis *serviceDto.BindApis) error { - if len(apis.Apis) == 0 { - return nil - } - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - if err != nil { - return fmt.Errorf("get project(%s) error: %v", pid, err) - } - sInfo, err := i.serviceService.Get(ctx, sid) - if err != nil { - return fmt.Errorf("get service(%s) error: %v", sid, err) - } - - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *service.Partition) string { - return p.Pid - }) - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - lastSort, err := i.serviceApiService.LastSortIndex(ctx, sid) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - } - for _, aid := range apis.Apis { - lastSort++ - err = i.serviceApiService.Bind(ctx, sid, aid, lastSort) - if err != nil { - return err - } - } - if sInfo.Status == service.StatusOff { - // 未开启,不上线服务 - return nil - } - return i.syncServiceApi(ctx, sid, apis.Apis, partitionIds, true) - }) -} - -func (i *imlServiceModule) UnbindServiceApi(ctx context.Context, pid string, sid string, apiIds []string) error { - if len(apiIds) == 0 { - return nil - } - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return err - } - sInfo, err := i.serviceService.Get(ctx, sid) - if err != nil { - return err - } - - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *service.Partition) string { - return p.Pid - }) - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - for _, aid := range apiIds { - err = i.serviceApiService.Unbind(ctx, sid, aid) - if err != nil { - return err - } - } - - if sInfo.Status == service.StatusOff { - // 未开启,不下线api - return nil - } - return i.syncServiceApi(ctx, sid, apiIds, partitionIds, false) - }) -} - -func (i *imlServiceModule) SortApis(ctx context.Context, pid string, sid string, apis *serviceDto.BindApis) error { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return err - } - if len(apis.Apis) == 0 { - return nil - } - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.serviceApiService.Clear(ctx, sid) - if err != nil { - return err - } - for idx, aid := range apis.Apis { - err = i.serviceApiService.Bind(ctx, sid, aid, idx+1) - if err != nil { - return err - } - } - return nil - }) -} - -func (i *imlServiceModule) ServiceApis(ctx context.Context, pid string, sid string) ([]*serviceDto.ServiceApi, error) { +func (i *imlServiceModule) ServiceDoc(ctx context.Context, pid string) (*serviceDto.ServiceDoc, error) { _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) if err != nil { return nil, err } - apis, err := i.serviceApiService.List(ctx, sid) + info, err := i.projectService.Get(ctx, pid) if err != nil { return nil, err } - sorts := make([]*serviceDto.ServiceApi, 0, len(apis)) - for _, a := range apis { - apiInfo, err := i.apiService.GetInfo(ctx, a.Aid) - if err != nil { - return nil, err - } - sorts = append(sorts, &serviceDto.ServiceApi{ - Id: a.Aid, - Name: apiInfo.Name, - Method: apiInfo.Method, - Path: apiInfo.Path, - Description: apiInfo.Description, - }) - } - return sorts, nil -} - -func (i *imlServiceModule) ServiceDoc(ctx context.Context, pid string, sid string) (*serviceDto.ServiceDoc, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - info, err := i.serviceService.Get(ctx, sid) - if err != nil { - return nil, err - } - doc, err := i.serviceDocService.Get(ctx, sid) + doc, err := i.serviceDocService.Get(ctx, pid) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } return &serviceDto.ServiceDoc{ - Id: sid, + Id: pid, Name: info.Name, Doc: "", }, nil } return &serviceDto.ServiceDoc{ - Id: sid, + Id: pid, Name: info.Name, Doc: doc.Doc, Creator: auto.UUID(doc.Creator), @@ -318,394 +60,14 @@ func (i *imlServiceModule) ServiceDoc(ctx context.Context, pid string, sid strin }, nil } -func (i *imlServiceModule) SaveServiceDoc(ctx context.Context, pid string, sid string, input *serviceDto.SaveServiceDoc) error { +func (i *imlServiceModule) SaveServiceDoc(ctx context.Context, pid string, input *serviceDto.SaveServiceDoc) error { _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) if err != nil { return err } return i.serviceDocService.Save(ctx, &service.SaveDoc{ - Sid: sid, + Sid: pid, Doc: input.Doc, }) } - -func (i *imlServiceModule) Search(ctx context.Context, keyword string, pid string) ([]*serviceDto.ServiceItem, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - - services, err := i.serviceService.Search(ctx, keyword, map[string]interface{}{ - "project": pid, - }, "update_at desc", "create_at desc") - if err != nil { - return nil, err - } - serviceIds := utils.SliceToSlice(services, func(s *service.Service) string { - return s.Id - }) - partitionMap, err := i.servicePartitionService.PartitionsByService(ctx, serviceIds...) - if err != nil { - return nil, err - } - subscribers, err := i.subscribeService.ListByServices(ctx, serviceIds...) - if err != nil { - return nil, err - } - subscribeMap := make(map[string]struct{}) - for _, s := range subscribers { - if s.ApplyStatus != subscribe.ApplyStatusReview && s.ApplyStatus != subscribe.ApplyStatusSubscribe { - continue - } - if _, ok := subscribeMap[s.Service]; ok { - continue - } - subscribeMap[s.Service] = struct{}{} - } - - items := make([]*serviceDto.ServiceItem, 0, len(serviceIds)) - for _, s := range services { - - apiCount, err := i.serviceApiService.Count(ctx, s.Id) - if err != nil { - return nil, err - } - _, notDelete := subscribeMap[s.Id] - items = append(items, &serviceDto.ServiceItem{ - Id: s.Id, - Name: s.Name, - Partition: auto.List(partitionMap[s.Id]), - ServiceType: s.ServiceType, - ApiNum: apiCount, - Status: s.Status, - CreateTime: auto.TimeLabel(s.CreateTime), - UpdateTime: auto.TimeLabel(s.UpdateTime), - CanDelete: !notDelete, - }) - - } - - return items, nil -} - -func (i *imlServiceModule) Create(ctx context.Context, pid string, input *serviceDto.CreateService) (*serviceDto.Service, error) { - pInfo, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - if input.ID == "" { - input.ID = uuid.New().String() - } - if input.ServiceType != "inner" && input.Catalogue == nil { - return nil, fmt.Errorf("group is required") - } - catalogue := "" - if input.Catalogue != nil { - catalogue = *input.Catalogue - } - - err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - t := strings.Join(input.Tags, ",") - err = i.serviceService.Create(ctx, &service.CreateService{ - Uuid: input.ID, - Name: input.Name, - Description: input.Description, - Logo: input.Logo, - ServiceType: input.ServiceType, - Project: pid, - Team: pInfo.Team, - Catalogue: catalogue, - Status: service.StatusOff, - Tag: t, - }) - if err != nil { - return err - } - err = i.servicePartitionService.Delete(ctx, nil, []string{input.ID}) - if err != nil { - return err - } - for _, p := range input.Partition { - err = i.servicePartitionService.Create(ctx, &service.CreatePartition{ - Sid: input.ID, - Pid: p, - }) - if err != nil { - return err - } - } - tags, err := i.getTagUuids(ctx, input.Tags) - if err != nil { - return err - } - err = i.serviceTagService.Delete(ctx, nil, []string{input.ID}) - if err != nil { - return err - } - for _, t := range tags { - err = i.serviceTagService.Create(ctx, &service.CreateTag{ - Tid: t, - Sid: input.ID, - }) - if err != nil { - return err - } - } - - return nil - }) - if err != nil { - return nil, err - } - return i.Get(ctx, pid, input.ID) -} - -func (i *imlServiceModule) getTagUuids(ctx context.Context, tags []string) ([]string, error) { - list, err := i.tagService.Search(ctx, "", map[string]interface{}{"name": tags}) - if err != nil { - return nil, err - } - tagMap := make(map[string]string) - for _, t := range list { - tagMap[t.Name] = t.Id - } - tagList := make([]string, 0, len(tags)) - repeatTag := make(map[string]struct{}) - for _, t := range tags { - if _, ok := repeatTag[t]; ok { - continue - } - repeatTag[t] = struct{}{} - v := &tag.CreateTag{ - Name: t, - } - id, ok := tagMap[t] - if !ok { - v.Id = uuid.New().String() - err = i.tagService.Create(ctx, v) - if err != nil { - return nil, err - } - tagMap[t] = v.Id - } else { - v.Id = id - } - tagList = append(tagList, v.Id) - } - return tagList, nil -} - -func (i *imlServiceModule) Edit(ctx context.Context, pid string, sid string, input *serviceDto.EditService) (*serviceDto.Service, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - - err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - t := strings.Join(input.Tags, ",") - err = i.serviceService.Save(ctx, sid, &service.EditService{ - Name: input.Name, - Description: input.Description, - Logo: input.Logo, - ServiceType: input.ServiceType, - Catalogue: input.Catalogue, - Tag: &t, - }) - if err != nil { - return err - } - tags, err := i.getTagUuids(ctx, input.Tags) - if err != nil { - return err - } - err = i.serviceTagService.Delete(ctx, nil, []string{sid}) - if err != nil { - return err - } - for _, t := range tags { - err = i.serviceTagService.Create(ctx, &service.CreateTag{ - Tid: t, - Sid: sid, - }) - if err != nil { - return err - } - } - - return nil - }) - if err != nil { - return nil, err - } - return i.Get(ctx, pid, sid) -} - -func (i *imlServiceModule) Delete(ctx context.Context, pid string, sid string) error { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return err - } - list, err := i.subscribeService.ListByServices(ctx, sid) - if err != nil { - return err - } - for _, l := range list { - if l.ApplyStatus == subscribe.ApplyStatusSubscribe || l.ApplyStatus == subscribe.ApplyStatusReview { - return fmt.Errorf("service %s is used", sid) - } - } - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return err - } - partitionIds := make([]string, 0, len(partitions)) - for _, p := range partitions { - partitionIds = append(partitionIds, p.Pid) - } - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - err := i.serviceService.Delete(ctx, sid) - if err != nil { - return err - } - err = i.servicePartitionService.Delete(ctx, nil, []string{sid}) - if err != nil { - return err - } - err = i.serviceTagService.Delete(ctx, nil, []string{sid}) - if err != nil { - return err - } - apis, err := i.serviceApiService.List(ctx, sid) - if err != nil { - return err - } - err = i.serviceApiService.Clear(ctx, sid) - if err != nil { - return err - } - apiIds := utils.SliceToSlice(apis, func(s *service.Api) string { - return s.Aid - }) - - return i.syncServiceApi(ctx, sid, apiIds, partitionIds, false) - }) -} - -func (i *imlServiceModule) Get(ctx context.Context, pid string, sid string) (*serviceDto.Service, error) { - info, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return nil, err - } - s, err := i.serviceService.Get(ctx, sid) - if err != nil { - return nil, err - } - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return nil, err - } - partitionIds := make([]string, 0, len(partitions)) - for _, p := range partitions { - partitionIds = append(partitionIds, p.Pid) - } - tags, err := i.serviceTagService.List(ctx, []string{sid}, nil) - if err != nil { - return nil, err - } - tagIds := make([]string, 0, len(tags)) - for _, t := range tags { - tagIds = append(tagIds, t.Tid) - } - - out := &serviceDto.Service{ - Id: s.Id, - Name: s.Name, - Description: s.Description, - Logo: s.Logo, - ServiceType: s.ServiceType, - Team: auto.UUID(info.Team), - Project: auto.UUID(s.Project), - Catalogue: auto.UUID(s.Catalogue), - Partition: auto.List(partitionIds), - Tags: auto.List(tagIds), - Status: s.Status, - } - return out, nil -} - -func (i *imlServiceModule) Enable(ctx context.Context, pid string, sid string) error { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return err - } - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *service.Partition) string { - return p.Pid - }) - status := service.StatusOn - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.serviceService.Save(ctx, sid, &service.EditService{ - Status: &status, - }) - if err != nil { - return err - } - apis, err := i.serviceApiService.List(ctx, sid) - if err != nil { - return err - } - if len(apis) == 0 { - return nil - } - apiIds := utils.SliceToSlice(apis, func(i *service.Api) string { - return i.Aid - }) - return i.syncServiceApi(ctx, sid, apiIds, partitionIds, true) - }) - -} - -func (i *imlServiceModule) Disable(ctx context.Context, pid string, sid string) error { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) - - if err != nil { - return err - } - partitions, err := i.servicePartitionService.List(ctx, sid) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(p *service.Partition) string { - return p.Pid - }) - status := service.StatusOff - return i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.serviceService.Save(ctx, sid, &service.EditService{ - Status: &status, - }) - if err != nil { - return err - } - apis, err := i.serviceApiService.List(ctx, sid) - if err != nil { - return err - } - if len(apis) == 0 { - return nil - } - apiIds := utils.SliceToSlice(apis, func(i *service.Api) string { - return i.Aid - }) - return i.syncServiceApi(ctx, sid, apiIds, partitionIds, false) - }) -} diff --git a/module/service/service.go b/module/service/service.go index 7ba15d3..7ea3fd5 100644 --- a/module/service/service.go +++ b/module/service/service.go @@ -10,34 +10,10 @@ import ( ) type IServiceModule interface { - // Search 关键字获取服务列表 - Search(ctx context.Context, keyword string, pid string) ([]*service_dto.ServiceItem, error) - // Create 创建服务 - Create(ctx context.Context, pid string, input *service_dto.CreateService) (*service_dto.Service, error) - // Edit 编辑服务 - Edit(ctx context.Context, pid string, sid string, input *service_dto.EditService) (*service_dto.Service, error) - // Delete 删除服务 - Delete(ctx context.Context, pid string, sid string) error - // Get 获取服务详情 - Get(ctx context.Context, pid string, sid string) (*service_dto.Service, error) - // Enable 启用服务 - Enable(ctx context.Context, pid string, sid string) error - // Disable 禁用服务 - Disable(ctx context.Context, pid string, sid string) error // ServiceDoc 服务文档 - ServiceDoc(ctx context.Context, pid string, sid string) (*service_dto.ServiceDoc, error) + ServiceDoc(ctx context.Context, pid string) (*service_dto.ServiceDoc, error) // SaveServiceDoc 保存服务文档 - SaveServiceDoc(ctx context.Context, pid string, sid string, input *service_dto.SaveServiceDoc) error - // ServiceApis 服务API - ServiceApis(ctx context.Context, pid string, sid string) ([]*service_dto.ServiceApi, error) - // BindServiceApi 绑定服务API - BindServiceApi(ctx context.Context, pid string, sid string, apis *service_dto.BindApis) error - // UnbindServiceApi 解绑服务API - UnbindServiceApi(ctx context.Context, pid string, sid string, apis []string) error - // SortApis 排序API - SortApis(ctx context.Context, pid string, sid string, apis *service_dto.BindApis) error - // SimpleList 简单列表 - SimpleList(ctx context.Context, pid string) ([]*service_dto.SimpleItem, error) + SaveServiceDoc(ctx context.Context, pid string, input *service_dto.SaveServiceDoc) error } func init() { diff --git a/module/subscribe/dto/input.go b/module/subscribe/dto/input.go index 8f9faa5..4f8dc66 100644 --- a/module/subscribe/dto/input.go +++ b/module/subscribe/dto/input.go @@ -5,11 +5,11 @@ type AddSubscriber struct { Service string `json:"service" aocheck:"service"` Project string `json:"subscriber" aocheck:"project"` Applier string `json:"applier" aocheck:"user"` - //Partition []string `json:"partition" aocheck:"partition"` + //Cluster []string `json:"partition" aocheck:"partition"` } type Approve struct { - //Partition []string `json:"partition" aocheck:"partition"` + //Cluster []string `json:"partition" aocheck:"partition"` Opinion string `json:"opinion"` Operate string `json:"operate"` } diff --git a/module/subscribe/dto/output.go b/module/subscribe/dto/output.go index 70ec6fe..2baaaf5 100644 --- a/module/subscribe/dto/output.go +++ b/module/subscribe/dto/output.go @@ -6,7 +6,7 @@ type Subscriber struct { Id string `json:"id"` Project auto.Label `json:"project" aolabel:"project"` Service auto.Label `json:"service" aolabel:"service"` - //Partition []auto.Label `json:"partition" aolabel:"partition"` + //Cluster []auto.Label `json:"partition" aolabel:"partition"` Subscriber auto.Label `json:"subscriber" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` @@ -19,7 +19,7 @@ type Subscriber struct { type SubscriptionItem struct { Id string `json:"id"` Service auto.Label `json:"service" aolabel:"service"` - //Partition auto.Label `json:"partition" aolabel:"partition"` + //Cluster auto.Label `json:"partition" aolabel:"partition"` ApplyStatus int `json:"apply_status"` Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` diff --git a/module/subscribe/iml.go b/module/subscribe/iml.go index 1958f6c..2af4cf5 100644 --- a/module/subscribe/iml.go +++ b/module/subscribe/iml.go @@ -2,12 +2,9 @@ package subscribe import ( "context" - "errors" "fmt" - "github.com/eolinker/apipark/service/partition" "github.com/eolinker/eosc/log" - "gorm.io/gorm" "github.com/eolinker/apipark/gateway" @@ -35,7 +32,6 @@ var ( ) type imlSubscribeModule struct { - partitionService partition.IPartitionService `autowired:""` projectService project.IProjectService `autowired:""` subscribeService subscribe.ISubscribeService `autowired:""` subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` @@ -44,43 +40,6 @@ type imlSubscribeModule struct { transaction store.ITransaction `autowired:""` } -//func (i *imlSubscribeModule) PartitionServices(ctx context.Context, app string) ([]*subscribe_dto.PartitionServiceItem, error) { -// pInfo, err := i.projectService.Get(ctx, app) -// if err != nil { -// return nil, fmt.Errorf("get application error: %w", err) -// } -// if !pInfo.AsApp { -// return nil, fmt.Errorf("project %s is not an application", app) -// } -// partitions, err := i.partitionService.List(ctx) -// if err != nil { -// return nil, err -// } -// subscriptions, err := i.subscribeService.SubscriptionsByApplication(ctx, app) -// if err != nil { -// return nil, err -// } -// subscriptionCount := make(map[string]int64) -// for _, s := range subscriptions { -// if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { -// continue -// } -// if _, ok := subscriptionCount[s.Partition]; !ok { -// subscriptionCount[s.Partition] = 0 -// } -// subscriptionCount[s.Partition]++ -// } -// items := make([]*subscribe_dto.PartitionServiceItem, 0) -// for _, p := range partitions { -// items = append(items, &subscribe_dto.PartitionServiceItem{ -// Id: p.UUID, -// Name: p.Name, -// ServiceNum: subscriptionCount[p.UUID], -// }) -// } -// return items, nil -//} - func (i *imlSubscribeModule) getSubscribers(ctx context.Context, projectIds []string) ([]*gateway.SubscribeRelease, error) { subscribers, err := i.subscribeService.SubscribersByProject(ctx, projectIds...) if err != nil { @@ -172,13 +131,11 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, if subscription.ApplyStatus != subscribe.ApplyStatusSubscribe { return fmt.Errorf("subscription can not be revoked") } - partitions, err := i.partitionService.List(ctx) + + clusters, err := i.clusterService.List(ctx) if err != nil { return err } - partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { - return i.UUID - }) applyStatus := subscribe.ApplyStatusUnsubscribe return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.subscribeService.Save(ctx, uuid, &subscribe.UpdateSubscribe{ @@ -187,8 +144,8 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, if err != nil { return err } - for _, p := range partitionIds { - err = i.offlineForCluster(ctx, p, &gateway.SubscribeRelease{ + for _, c := range clusters { + err = i.offlineForCluster(ctx, c.Uuid, &gateway.SubscribeRelease{ Service: subscription.Service, Application: subscription.Application, }) @@ -240,10 +197,6 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, if err != nil { return err } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return err - } if input.Uuid == "" { input.Uuid = uuid.New().String() @@ -253,6 +206,10 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, Application: input.Project, Expired: "0", } + clusters, err := i.clusterService.List(ctx) + if err != nil { + return err + } return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ @@ -266,10 +223,10 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, if err != nil { return err } - for _, p := range partitions { - err = i.onlineSubscriber(ctx, p.UUID, sub) + for _, c := range clusters { + err = i.onlineSubscriber(ctx, c.Uuid, sub) if err != nil { - return fmt.Errorf("add subscriber for partition[%s] %v", p.UUID, err) + return fmt.Errorf("add subscriber for cluster[%s] %v", c.Uuid, err) } } @@ -278,13 +235,9 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, } -func (i *imlSubscribeModule) onlineSubscriber(ctx context.Context, partitionId string, subscriber *gateway.SubscribeRelease) error { - info, err := i.partitionService.Get(ctx, partitionId) - if err != nil { - return err - } +func (i *imlSubscribeModule) onlineSubscriber(ctx context.Context, clusterId string, subscriber *gateway.SubscribeRelease) error { - client, err := i.clusterService.GatewayClient(ctx, info.Cluster) + client, err := i.clusterService.GatewayClient(ctx, clusterId) if err != nil { return err } @@ -300,19 +253,10 @@ func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project strin if err != nil { return err } - partitions, err := i.partitionService.List(ctx) + clusters, err := i.clusterService.List(ctx) if err != nil { return err } - for _, p := range partitions { - err = i.offlineForCluster(ctx, p.UUID, &gateway.SubscribeRelease{ - Service: serviceId, - Application: applicationId, - }) - if err != nil { - return fmt.Errorf("offline subscribe for partition[%s] %s", p.UUID, err) - } - } return i.transaction.Transaction(ctx, func(ctx context.Context) error { list, err := i.subscribeService.ListByApplication(ctx, serviceId, applicationId) @@ -329,24 +273,18 @@ func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project strin return err } } - for _, p := range partitions { - err := i.offlineForCluster(ctx, p.UUID, releaseInfo) + for _, c := range clusters { + err = i.offlineForCluster(ctx, c.Uuid, releaseInfo) if err != nil { - return fmt.Errorf("offline subscribe for partition[%s] %s", p.UUID, err) + return fmt.Errorf("offline subscribe for cluster[%s] %s", c.Uuid, err) } } return nil }) } -func (i *imlSubscribeModule) offlineForCluster(ctx context.Context, partitionId string, config *gateway.SubscribeRelease) error { - info, err := i.partitionService.Get(ctx, partitionId) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - return nil - } - client, err := i.clusterService.GatewayClient(ctx, info.Cluster) +func (i *imlSubscribeModule) offlineForCluster(ctx context.Context, clusterId string, config *gateway.SubscribeRelease) error { + + client, err := i.clusterService.GatewayClient(ctx, clusterId) if err != nil { return err } @@ -417,7 +355,6 @@ type imlSubscribeApprovalModule struct { subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` projectService project.IProjectService `autowired:""` clusterService cluster.IClusterService `autowired:""` - partitionService partition.IPartitionService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -426,13 +363,7 @@ func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id st if err != nil { return err } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return err - } - partitionIds := utils.SliceToSlice(partitions, func(i *partition.Partition) string { - return i.UUID - }) + return i.transaction.Transaction(ctx, func(ctx context.Context) error { userID := utils.UserId(ctx) status := subscribe.ApplyStatusSubscribe @@ -448,7 +379,7 @@ func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id st if err != nil { return err } - cs, err := i.clusterService.List(ctx, partitionIds...) + cs, err := i.clusterService.List(ctx) if err != nil { return err } @@ -461,7 +392,7 @@ func (i *imlSubscribeApprovalModule) Pass(ctx context.Context, pid string, id st }) if err != nil { - log.Warnf("online subscriber for partition[%s] %v", c.Partition, err) + log.Warnf("online subscriber for cluster[%s] %v", c.Uuid, err) } } diff --git a/module/team/dto/input.go b/module/team/dto/input.go index 64ae4d7..040d202 100644 --- a/module/team/dto/input.go +++ b/module/team/dto/input.go @@ -4,10 +4,9 @@ type CreateTeam struct { Id string `json:"id"` Name string `json:"name" binding:"required"` Description string `json:"description"` - Master string `json:"master" aocheck:"user"` + Master string `json:"master"` } type EditTeam struct { Name *string `json:"name"` Description *string `json:"description"` - Master *string `json:"master" aocheck:"user"` } diff --git a/module/team/dto/output.go b/module/team/dto/output.go index e545ade..d15d1f5 100644 --- a/module/team/dto/output.go +++ b/module/team/dto/output.go @@ -6,55 +6,47 @@ import ( ) type Item struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - Organization auto.Label `json:"organization" aolabel:"organization"` - CanDelete bool `json:"can_delete"` - ProjectNum int64 `json:"system_num"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + CanDelete bool `json:"can_delete"` + ProjectNum int64 `json:"system_num"` } func ToItem(model *team.Team, projectNum int64) *Item { return &Item{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - ProjectNum: projectNum, - CanDelete: projectNum == 0, + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + ProjectNum: projectNum, + CanDelete: projectNum == 0, } } type Team struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Master auto.Label `json:"master" aolabel:"user"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - Organization auto.Label `json:"organization" aolabel:"organization"` - Creator auto.Label `json:"creator" aolabel:"user"` - Updater auto.Label `json:"updater" aolabel:"user"` - CanDelete bool `json:"can_delete"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + Creator auto.Label `json:"creator" aolabel:"user"` + Updater auto.Label `json:"updater" aolabel:"user"` + CanDelete bool `json:"can_delete"` } func ToTeam(model *team.Team, projectNum int) *Team { return &Team{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Organization: auto.UUID(model.Organization), - Creator: auto.UUID(model.Creator), - Updater: auto.UUID(model.Updater), - CanDelete: projectNum == 0, + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Creator: auto.UUID(model.Creator), + Updater: auto.UUID(model.Updater), + CanDelete: projectNum == 0, } } diff --git a/module/team/iml.go b/module/team/iml.go index 11ec075..4e7f34e 100644 --- a/module/team/iml.go +++ b/module/team/iml.go @@ -4,6 +4,10 @@ import ( "context" "fmt" + "github.com/eolinker/go-common/utils" + + "github.com/eolinker/ap-account/service/role" + "github.com/eolinker/apipark/service/project" "github.com/eolinker/go-common/store" @@ -23,11 +27,13 @@ var ( ) type imlTeamModule struct { - service team.ITeamService `autowired:""` - memberService team_member.ITeamMemberService `autowired:""` - userService user.IUserService `autowired:""` - projectService project.IProjectService `autowired:""` - transaction store.ITransaction `autowired:""` + service team.ITeamService `autowired:""` + memberService team_member.ITeamMemberService `autowired:""` + userService user.IUserService `autowired:""` + projectService project.IProjectService `autowired:""` + roleService role.IRoleService `autowired:""` + roleMemberService role.IRoleMemberService `autowired:""` + transaction store.ITransaction `autowired:""` } func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, error) { @@ -70,12 +76,28 @@ func (m *imlTeamModule) Create(ctx context.Context, input *team_dto.CreateTeam) Id: input.Id, Name: input.Name, Description: input.Description, - Master: input.Master, }) if err != nil { return err } - return m.memberService.AddMemberTo(ctx, input.Id, input.Master) + if input.Master == "" { + input.Master = utils.UserId(ctx) + } + + err = m.memberService.AddMemberTo(ctx, input.Id, input.Master) + if err != nil { + return err + } + supperRole, err := m.roleService.GetDefaultRole(ctx, role.GroupTeam) + if err != nil { + return err + } + + return m.roleMemberService.Add(ctx, &role.AddMember{ + Role: supperRole.Id, + User: input.Master, + Target: role.TeamTarget(input.Id), + }) }) if err != nil { return nil, err @@ -85,23 +107,9 @@ func (m *imlTeamModule) Create(ctx context.Context, input *team_dto.CreateTeam) func (m *imlTeamModule) Edit(ctx context.Context, id string, input *team_dto.EditTeam) (*team_dto.Team, error) { err := m.transaction.Transaction(ctx, func(ctx context.Context) error { - if input.Master != nil { - // 负责人是否在团队内,若不在,则新增 - members, err := m.memberService.Members(ctx, []string{id}, []string{*input.Master}) - if err != nil { - return err - } - if len(members) == 0 { - err = m.memberService.AddMemberTo(ctx, id, *input.Master) - if err != nil { - return err - } - } - } return m.service.Save(ctx, id, &team.EditTeam{ Name: input.Name, Description: input.Description, - Master: input.Master, }) }) @@ -122,7 +130,11 @@ func (m *imlTeamModule) Delete(ctx context.Context, id string) error { if count != 0 { return fmt.Errorf("team has projects,cannot delete") } - return m.service.Delete(ctx, id) + err = m.service.Delete(ctx, id) + if err != nil { + return err + } + return nil }) return err } diff --git a/module/upstream/dto/output.go b/module/upstream/dto/output.go index bb10173..ade127c 100644 --- a/module/upstream/dto/output.go +++ b/module/upstream/dto/output.go @@ -1,6 +1,6 @@ package upstream_dto -type UpstreamConfig map[string]*Upstream +type UpstreamConfig *Upstream type Upstream struct { Type string `json:"driver"` diff --git a/module/upstream/iml.go b/module/upstream/iml.go index 2e6f573..772ec8f 100644 --- a/module/upstream/iml.go +++ b/module/upstream/iml.go @@ -5,9 +5,7 @@ import ( "errors" "fmt" - "github.com/eolinker/apipark/service/partition" - - "github.com/eolinker/go-common/utils" + "github.com/eolinker/apipark/service/cluster" "gorm.io/gorm" @@ -28,10 +26,9 @@ var ( ) type imlUpstreamModule struct { - projectService project.IProjectService `autowired:""` - partitionService partition.IPartitionService `autowired:""` - upstreamService upstream.IUpstreamService `autowired:""` - transaction store.ITransaction `autowired:""` + projectService project.IProjectService `autowired:""` + upstreamService upstream.IUpstreamService `autowired:""` + transaction store.ITransaction `autowired:""` } func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.UpstreamConfig, error) { @@ -39,26 +36,22 @@ func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.U if err != nil { return nil, err } - item, err := i.upstreamService.Get(ctx, pid) + _, err = i.upstreamService.Get(ctx, pid) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } return nil, nil } - result := make(map[string]*upstream_dto.Upstream) - for _, partitionId := range item.Partitions { - commit, err := i.upstreamService.LatestCommit(ctx, pid, partitionId) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return nil, err - } - continue + commit, err := i.upstreamService.LatestCommit(ctx, pid, cluster.DefaultClusterID) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, err } - result[partitionId] = upstream_dto.FromClusterConfig(commit.Data) + return nil, nil } - return result, nil + return upstream_dto.FromClusterConfig(commit.Data), nil } func (i *imlUpstreamModule) Save(ctx context.Context, pid string, upstreamConfig upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { @@ -66,33 +59,18 @@ func (i *imlUpstreamModule) Save(ctx context.Context, pid string, upstreamConfig if err != nil { return nil, err } - partitions, err := i.partitionService.List(ctx) - if err != nil { - return nil, err - } - partitionMap := utils.SliceToMapO(partitions, func(p *partition.Partition) (string, struct{}) { - return p.UUID, struct{}{} - }) err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - partitionIds := make([]string, 0, len(upstreamConfig)) - for id, cfg := range upstreamConfig { - if _, ok := partitionMap[id]; !ok { - continue - } - err = i.upstreamService.SaveCommit(ctx, pid, id, upstream_dto.ConvertUpstream(cfg)) - if err != nil { - return err - } - - partitionIds = append(partitionIds, id) + err = i.upstreamService.SaveCommit(ctx, pid, cluster.DefaultClusterID, upstream_dto.ConvertUpstream(upstreamConfig)) + if err != nil { + return err } + return i.upstreamService.Save(ctx, &upstream.SaveUpstream{ - UUID: pid, - Name: fmt.Sprintf("upstream-%s", pid), - Project: pid, - Team: pInfo.Team, - Partitions: partitionIds, + UUID: pid, + Name: fmt.Sprintf("upstream-%s", pid), + Project: pid, + Team: pInfo.Team, }) }) diff --git a/plugins/core/cluster.go b/plugins/core/cluster.go index a5da3ce..7708b26 100644 --- a/plugins/core/cluster.go +++ b/plugins/core/cluster.go @@ -8,8 +8,8 @@ import ( func (p *plugin) clusterApi() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partition/cluster/nodes", []string{"context", "query:partition"}, []string{"nodes"}, p.partitionController.Nodes), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/partition/cluster/reset", []string{"context", "query:partition", "body"}, []string{"nodes"}, p.partitionController.ResetCluster), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/partition/cluster/check", []string{"context", "body"}, []string{"nodes"}, p.partitionController.Check), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/cluster/nodes", []string{"context", "query:partition"}, []string{"nodes"}, p.clusterController.Nodes), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/cluster/reset", []string{"context", "query:partition", "body"}, []string{"nodes"}, p.clusterController.ResetCluster), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/cluster/check", []string{"context", "body"}, []string{"nodes"}, p.clusterController.Check), } } diff --git a/plugins/core/core.go b/plugins/core/core.go index 330c8c8..ce9a1ee 100644 --- a/plugins/core/core.go +++ b/plugins/core/core.go @@ -3,10 +3,13 @@ package core import ( "net/http" + plugin_cluster "github.com/eolinker/apipark/controller/plugin-cluster" + + "github.com/eolinker/apipark/controller/cluster" + "github.com/eolinker/ap-account/controller/role" "github.com/eolinker/apipark/controller/common" - plugin_partition "github.com/eolinker/apipark/controller/plugin-partition" "github.com/eolinker/apipark/controller/topology" @@ -31,7 +34,6 @@ import ( "github.com/eolinker/apipark/controller/my_team" "github.com/eolinker/apipark/controller/certificate" - "github.com/eolinker/apipark/controller/partition" "github.com/eolinker/apipark/controller/team_manager" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/pm3" @@ -56,13 +58,12 @@ func (d *Driver) Create() (pm3.IPlugin, error) { } type plugin struct { - partitionController partition.IPartitionController `autowired:""` - certificateController certificate.ICertificateController `autowired:""` - teamManagerController team_manager.ITeamManagerController `autowired:""` - myTeamController my_team.ITeamController `autowired:""` - appController project.IAppController `autowired:""` - projectController project.IProjectController `autowired:""` - //projectMemberController project.IProjectMemberController `autowired:""` + clusterController cluster.IClusterController `autowired:""` + certificateController certificate.ICertificateController `autowired:""` + teamManagerController team_manager.ITeamManagerController `autowired:""` + myTeamController my_team.ITeamController `autowired:""` + appController project.IAppController `autowired:""` + projectController project.IProjectController `autowired:""` serviceController service.IServiceController `autowired:""` catalogueController catalogue.ICatalogueController `autowired:""` upstreamController upstream.IUpstreamController `autowired:""` @@ -74,7 +75,7 @@ type plugin struct { subscribeApprovalController subscribe.ISubscribeApprovalController `autowired:""` dynamicModuleController dynamic_module.IDynamicModuleController `autowired:""` topologyController topology.ITopologyController `autowired:""` - pluginPartitionController plugin_partition.IPluginPartitionController `autowired:""` + pluginClusterController plugin_cluster.IPluginClusterController `autowired:""` commonController common.ICommonController `autowired:""` apis []pm3.Api } diff --git a/plugins/core/dynamic-module.go b/plugins/core/dynamic-module.go index 5aabced..483ed61 100644 --- a/plugins/core/dynamic-module.go +++ b/plugins/core/dynamic-module.go @@ -17,7 +17,7 @@ func (p *plugin) DynamicModuleApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/dynamics/:group", []string{"context", "rest:group"}, []string{"dynamics"}, p.dynamicModuleController.ModuleDrivers), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/dynamic/:name/online", []string{"context", "rest:name", "query:id", "body"}, nil, p.dynamicModuleController.Online), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/dynamic/:name/offline", []string{"context", "rest:name", "query:id", "body"}, nil, p.dynamicModuleController.Offline), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name/status", []string{"context", "rest:name", "query:keyword", "query:page", "query:page_size"}, []string{"list"}, p.dynamicModuleController.PartitionStatuses), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name", []string{"context", "rest:name", "query:id"}, []string{"info"}, p.dynamicModuleController.PartitionStatus), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name/status", []string{"context", "rest:name", "query:keyword", "query:page", "query:page_size"}, []string{"list"}, p.dynamicModuleController.PartitionStatuses), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name", []string{"context", "rest:name", "query:id"}, []string{"info"}, p.dynamicModuleController.PartitionStatus), } } diff --git a/plugins/core/my-team.go b/plugins/core/my-team.go index 5b086b4..311731b 100644 --- a/plugins/core/my-team.go +++ b/plugins/core/my-team.go @@ -17,6 +17,8 @@ func (p *plugin) MyTeamApi() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/member", []string{"context", "query:team", "query:user"}, nil, p.myTeamController.RemoveMember), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/members", []string{"context", "query:team", "query:keyword"}, []string{"members"}, p.myTeamController.Members), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/team/member/role", []string{"context", "query:team", "body"}, nil, p.myTeamController.UpdateMemberRole), + // 团队项目操作 pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/projects", []string{"context", "query:team", "query:keyword"}, []string{"projects"}, p.projectController.Search), pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/project", []string{"context", "query:team", "body"}, []string{"project"}, p.projectController.CreateProject), diff --git a/plugins/core/partition.go b/plugins/core/partition.go index 339ff15..a1a663e 100644 --- a/plugins/core/partition.go +++ b/plugins/core/partition.go @@ -1,19 +1,17 @@ package core import ( - "net/http" - "github.com/eolinker/go-common/pm3" ) func (p *plugin) partitionApi() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partitions", []string{"context", "query:keyword"}, []string{"partitions"}, p.partitionController.Search), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partition", []string{"context", "query:id"}, []string{"partition"}, p.partitionController.Info), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/partition", []string{"context", "body"}, []string{"partition", "id", "update_time"}, p.partitionController.Create), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/partition", []string{"context", "query:id", "body"}, []string{"partition"}, p.partitionController.Update), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/partition", []string{"context", "query:id"}, []string{"id"}, p.partitionController.Delete), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/partitions", []string{"context"}, []string{"partitions"}, p.partitionController.Simple), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/partitions/cluster", []string{"context"}, []string{"partitions"}, p.partitionController.SimpleWithCluster), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partitions", []string{"context", "query:keyword"}, []string{"partitions"}, p.partitionController.Search), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partition", []string{"context", "query:id"}, []string{"partition"}, p.partitionController.Info), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/partition", []string{"context", "body"}, []string{"partition", "id", "update_time"}, p.partitionController.Create), + //pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/partition", []string{"context", "query:id", "body"}, []string{"partition"}, p.partitionController.Update), + //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/partition", []string{"context", "query:id"}, []string{"id"}, p.partitionController.Delete), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/partitions", []string{"context"}, []string{"partitions"}, p.partitionController.Simple), + //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/partitions/cluster", []string{"context"}, []string{"partitions"}, p.partitionController.SimpleWithCluster), } } diff --git a/plugins/core/plugin.go b/plugins/core/plugin.go index 3351053..42e9366 100644 --- a/plugins/core/plugin.go +++ b/plugins/core/plugin.go @@ -1,16 +1,17 @@ package core import ( - "github.com/eolinker/go-common/pm3" "net/http" + + "github.com/eolinker/go-common/pm3" ) func (p *plugin) PartitionPluginApi() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/apinto/plugin/:plugin", []string{"context", "query:partition", "rest:plugin"}, []string{"plugin", "render"}, p.pluginPartitionController.Get), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/apinto/plugins", []string{"context", "query:partition"}, []string{"plugins"}, p.pluginPartitionController.List), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apinto/plugins/project", []string{"context", "query:project"}, []string{"plugins"}, p.pluginPartitionController.Option), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apinto/plugin/:name", []string{"context", "rest:name"}, []string{"plugins"}, p.pluginPartitionController.Info), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/apinto/plugin/:plugin", []string{"context", "query:partition", "rest:plugin", "body"}, []string{}, p.pluginPartitionController.Set), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/apinto/plugin/:plugin", []string{"context", "query:partition", "rest:plugin"}, []string{"plugin", "render"}, p.pluginClusterController.Get), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/apinto/plugins", []string{"context", "query:partition"}, []string{"plugins"}, p.pluginClusterController.List), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apinto/plugins/project", []string{"context", "query:project"}, []string{"plugins"}, p.pluginClusterController.Option), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apinto/plugin/:name", []string{"context", "rest:name"}, []string{"plugins"}, p.pluginClusterController.Info), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/apinto/plugin/:plugin", []string{"context", "query:partition", "rest:plugin", "body"}, []string{}, p.pluginClusterController.Set), } } diff --git a/plugins/core/service.go b/plugins/core/service.go index 2913d02..91f4fda 100644 --- a/plugins/core/service.go +++ b/plugins/core/service.go @@ -8,21 +8,8 @@ import ( func (p *plugin) serviceApi() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/services", []string{"context", "query:keyword", "query:project"}, []string{"services"}, p.serviceController.Search), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/service/info", []string{"context", "query:project", "query:service"}, []string{"service"}, p.serviceController.Get), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/service", []string{"context", "query:project", "body"}, []string{"service"}, p.serviceController.Create), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/info", []string{"context", "query:project", "query:service", "body"}, []string{"service"}, p.serviceController.Edit), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/service", []string{"context", "query:project", "query:service"}, nil, p.serviceController.Delete), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/enable", []string{"context", "query:project", "query:service"}, nil, p.serviceController.Enable), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/disable", []string{"context", "query:project", "query:service"}, nil, p.serviceController.Disable), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/service/doc", []string{"context", "query:project", "query:service"}, []string{"doc"}, p.serviceController.ServiceDoc), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/doc", []string{"context", "query:project", "query:service", "body"}, nil, p.serviceController.SaveServiceDoc), - // Service API - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/service/apis", []string{"context", "query:project", "query:service"}, []string{"apis"}, p.serviceController.ServiceApis), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/service/bind", []string{"context", "query:project", "query:service", "body"}, nil, p.serviceController.BindServiceApi), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/service/unbind", []string{"context", "query:project", "query:service", "query:apis"}, nil, p.serviceController.UnbindServiceApi), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/api/sort", []string{"context", "query:project", "query:service", "body"}, nil, p.serviceController.SortApis), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/project/services", []string{"context", "query:project"}, []string{"services"}, p.serviceController.SimpleList), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/service/doc", []string{"context", "query:project"}, []string{"doc"}, p.serviceController.ServiceDoc), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/doc", []string{"context", "query:project", "body"}, nil, p.serviceController.SaveServiceDoc), } } diff --git a/resources/access/role.yaml b/resources/access/role.yaml index e033bb4..05d8898 100644 --- a/resources/access/role.yaml +++ b/resources/access/role.yaml @@ -2,49 +2,50 @@ system: - name: supper_admin cname: 超级管理员 permits: - - system.api_market.service_classification.manager - - system.api_market.service_classification.view - - system.devops.cluster.manager - - system.devops.cluster.view - - system.devops.log_configuration.manager - - system.devops.log_configuration.view - - system.devops.ssl_certificate.manager - - system.devops.ssl_certificate.view - - system.organization.member.manager - - system.organization.member.view - - system.organization.role.view_system_role - - system.organization.role.view_team_role - - system.organization.team.manager - - system.organization.team.view - - system.workspace.api_market.view - - system.workspace.application.view_all - - system.workspace.service.view_all - - system.workspace.team.view_all + - system.api_market.service_classification.manager + - system.api_market.service_classification.view + - system.devops.cluster.manager + - system.devops.cluster.view + - system.devops.log_configuration.manager + - system.devops.log_configuration.view + - system.devops.ssl_certificate.manager + - system.devops.ssl_certificate.view + - system.organization.member.manager + - system.organization.member.view + - system.organization.role.view_system_role + - system.organization.role.view_team_role + - system.organization.team.manager + - system.organization.team.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all + supper: true - name: team_admin cname: 团队管理员 permits: - - system.organization.role.view_team_role - - system.organization.team.manager - - system.organization.team.view - - system.workspace.api_market.view - - system.workspace.application.view_all - - system.workspace.service.view_all - - system.workspace.team.view_all + - system.organization.role.view_team_role + - system.organization.team.manager + - system.organization.team.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all - name: devops_admin cname: 运维管理员 permits: - - system.api_market.service_classification.manager - - system.api_market.service_classification.view - - system.devops.cluster.manager - - system.devops.cluster.view - - system.devops.log_configuration.manager - - system.devops.log_configuration.view - - system.devops.ssl_certificate.manager - - system.devops.ssl_certificate.view - - system.workspace.api_market.view - - system.workspace.application.view_all - - system.workspace.service.view_all - - system.workspace.team.view_all + - system.api_market.service_classification.manager + - system.api_market.service_classification.view + - system.devops.cluster.manager + - system.devops.cluster.view + - system.devops.log_configuration.manager + - system.devops.log_configuration.view + - system.devops.ssl_certificate.manager + - system.devops.ssl_certificate.view + - system.workspace.api_market.view + - system.workspace.application.view_all + - system.workspace.service.view_all + - system.workspace.team.view_all - name: member cname: 普通成员 permits: @@ -54,61 +55,62 @@ team: - name: team_admin cname: 团队管理员 permits: - - team.application.application.manager - - team.application.authorization.manager - - team.application.authorization.view - - team.application.subscription.manager - - team.application.subscription.view - - team.service.api.manager - - team.service.api.view - - team.service.release.manager - - team.service.release.view - - team.service.service.manager - - team.service.subscription.manager - - team.service.subscription.view - - team.service.upstream.manager - - team.service.upstream.view - - team.team.member.manager - - team.team.member.view - - team.team.team.manager - - team.team.team.view + - team.application.application.manager + - team.application.authorization.manager + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.service.api.manager + - team.service.api.view + - team.service.release.manager + - team.service.release.view + - team.service.service.manager + - team.service.subscription.manager + - team.service.subscription.view + - team.service.upstream.manager + - team.service.upstream.view + - team.team.member.manager + - team.team.member.view + - team.team.team.manager + - team.team.team.view + supper: true - name: service_admin cname: 服务管理员 permits: - - team.service.service.manager - - team.service.upstream.manager - - team.service.upstream.view - - team.service.api.manager - - team.service.api.view - - team.service.subscription.manager - - team.service.subscription.view - - team.service.release.manager - - team.service.release.view - - team.team.member.view + - team.service.service.manager + - team.service.upstream.manager + - team.service.upstream.view + - team.service.api.manager + - team.service.api.view + - team.service.subscription.manager + - team.service.subscription.view + - team.service.release.manager + - team.service.release.view + - team.team.member.view - name: service_developer cname: 服务开发者 permits: - - team.service.upstream.manager - - team.service.upstream.view - - team.service.api.manager - - team.service.api.view - - team.service.release.manager - - team.service.release.view - - team.team.member.view + - team.service.upstream.manager + - team.service.upstream.view + - team.service.api.manager + - team.service.api.view + - team.service.release.manager + - team.service.release.view + - team.team.member.view - name: application_admin cname: 应用管理员 permits: - - team.application.application.manager - - team.application.authorization.manager - - team.application.authorization.view - - team.application.subscription.manager - - team.application.subscription.view - - team.team.member.view + - team.application.application.manager + - team.application.authorization.manager + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.team.member.view - name: application_developer cname: 应用开发者 permits: - - team.application.authorization.view - - team.application.subscription.manager - - team.application.subscription.view - - team.team.member.view + - team.application.authorization.view + - team.application.subscription.manager + - team.application.subscription.view + - team.team.member.view default: true \ No newline at end of file diff --git a/resources/plugin/plugin-load.go b/resources/plugin/plugin-load.go index 3198f2e..80a8de2 100644 --- a/resources/plugin/plugin-load.go +++ b/resources/plugin/plugin-load.go @@ -6,12 +6,13 @@ import ( _ "embed" "encoding/json" "fmt" - "gopkg.in/yaml.v3" "log" "strings" + "gopkg.in/yaml.v3" + "github.com/eolinker/apipark/model/plugin_model" - pluginModule "github.com/eolinker/apipark/module/plugin-partition" + pluginModule "github.com/eolinker/apipark/module/plugin-cluster" "github.com/eolinker/apipark/service/setting" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/store" @@ -30,9 +31,9 @@ var ( ) type pluginLoad struct { - transaction store.ITransaction `autowired:""` - module pluginModule.IPluginPartitionModule `autowired:""` - settingService setting.ISettingService `autowired:""` + transaction store.ITransaction `autowired:""` + module pluginModule.IPluginClusterModule `autowired:""` + settingService setting.ISettingService `autowired:""` version string defines []*plugin_model.Define } diff --git a/service/certificate/model.go b/service/certificate/model.go index 5c1d349..4925e1d 100644 --- a/service/certificate/model.go +++ b/service/certificate/model.go @@ -6,7 +6,7 @@ type Certificate struct { ID string `json:"id"` Name string `json:"name"` Domains []string `json:"domains"` - Partition string `json:"partition_id"` + Cluster string `json:"cluster"` NotBefore time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:not_before;comment:生效时间"` NotAfter time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:not_after;comment:失效时间"` Updater string `json:"updater"` diff --git a/service/certificate/service.go b/service/certificate/service.go index 1e8fce1..2aca0e7 100644 --- a/service/certificate/service.go +++ b/service/certificate/service.go @@ -27,8 +27,8 @@ func init() { type ICertificateService interface { Get(ctx context.Context, id string) (*Certificate, *File, error) - List(ctx context.Context, partitionID string) ([]*Certificate, error) - Save(ctx context.Context, id string, partition string, key, cert []byte) (*Certificate, error) + List(ctx context.Context, clusterId string) ([]*Certificate, error) + Save(ctx context.Context, id, clusterId string, key, cert []byte) (*Certificate, error) Delete(ctx context.Context, id string) error } @@ -67,7 +67,7 @@ func (s *imlCertificateService) Get(ctx context.Context, id string) (*Certificat } return &Certificate{ ID: ce.UUID, - Partition: ce.Partition, + Cluster: ce.Cluster, UpdateTime: ce.UpdateTime, Name: ce.Name, Domains: ce.Domains, @@ -82,8 +82,8 @@ func (s *imlCertificateService) Get(ctx context.Context, id string) (*Certificat } -func (s *imlCertificateService) List(ctx context.Context, partitionID string) ([]*Certificate, error) { - list, err := s.store.List(ctx, map[string]interface{}{"partition": partitionID}) +func (s *imlCertificateService) List(ctx context.Context, clusterId string) ([]*Certificate, error) { + list, err := s.store.List(ctx, map[string]interface{}{"cluster": clusterId}) if err != nil { return nil, err } @@ -92,7 +92,7 @@ func (s *imlCertificateService) List(ctx context.Context, partitionID string) ([ ID: i.UUID, Name: i.Name, Domains: i.Domains, - Partition: i.Partition, + Cluster: i.Cluster, NotAfter: i.NotAfter, NotBefore: i.NotBefore, Updater: i.Updater, @@ -101,7 +101,7 @@ func (s *imlCertificateService) List(ctx context.Context, partitionID string) ([ }), nil } -func (s *imlCertificateService) Save(ctx context.Context, id string, partition string, key, cert []byte) (*Certificate, error) { +func (s *imlCertificateService) Save(ctx context.Context, id, clusterId string, key, cert []byte) (*Certificate, error) { if id == "" { id = uuid.NewString() } @@ -122,7 +122,7 @@ func (s *imlCertificateService) Save(ctx context.Context, id string, partition s } ce := &certificate.Certificate{ UUID: id, - Partition: partition, + Cluster: clusterId, Name: certDERBlock.Leaf.Subject.CommonName, Domains: dnsNames, Updater: operator, @@ -152,7 +152,7 @@ func (s *imlCertificateService) Save(ctx context.Context, id string, partition s ID: ce.UUID, Name: ce.Name, Domains: ce.Domains, - Partition: ce.Partition, + Cluster: ce.Cluster, NotAfter: ce.NotAfter, NotBefore: ce.NotBefore, Updater: ce.Updater, diff --git a/service/cluster/cluster.go b/service/cluster/cluster.go index 2928d52..6b62be7 100644 --- a/service/cluster/cluster.go +++ b/service/cluster/cluster.go @@ -17,19 +17,20 @@ import ( ) var ( - _ IClusterService = (*imlClusterService)(nil) - _ auto.CompleteService = (*imlClusterService)(nil) + _ IClusterService = (*imlClusterService)(nil) + _ auto.CompleteService = (*imlClusterService)(nil) + DefaultClusterID = "default" ) type IClusterService interface { CountByPartition(ctx context.Context) (map[string]int, error) - List(ctx context.Context, partitionId ...string) ([]*Cluster, error) + List(ctx context.Context, clusterIds ...string) ([]*Cluster, error) ListByClusters(ctx context.Context, partitionId string, ids ...string) ([]*Cluster, error) Search(ctx context.Context, keyword string, partitionId ...string) ([]*Cluster, error) - Create(ctx context.Context, partitionId string, name string, resume string, address string) (*Cluster, error) + Create(ctx context.Context, name string, resume string, address string) (*Cluster, error) UpdateInfo(ctx context.Context, id string, name *string, resume *string) (*Cluster, error) UpdateAddress(ctx context.Context, id string, address string) ([]*Node, error) - Nodes(ctx context.Context, id string) ([]*Node, error) + Nodes(ctx context.Context, clusterIds ...string) ([]*Node, error) GatewayClient(ctx context.Context, id string) (gateway.IClientDriver, error) Get(ctx context.Context, id string) (*Cluster, error) Delete(ctx context.Context, id string) error @@ -125,7 +126,7 @@ func (s *imlClusterService) Get(ctx context.Context, id string) (*Cluster, error return FromEntity(v), nil } -func (s *imlClusterService) Create(ctx context.Context, partitionId string, name string, resume string, address string) (*Cluster, error) { +func (s *imlClusterService) Create(ctx context.Context, name string, resume string, address string) (*Cluster, error) { apintoInfo, err := admin.Admin(address).Info(ctx) if err != nil { return nil, err @@ -157,15 +158,14 @@ func (s *imlClusterService) Create(ctx context.Context, partitionId string, name } en := &cluster.Cluster{ - Id: 0, - UUID: apintoInfo.Cluster, - Name: name, - Partition: partitionId, - Resume: resume, - Creator: operator, - Updater: operator, - CreateAt: time.Now(), - UpdateAt: time.Now(), + Id: 0, + UUID: apintoInfo.Cluster, + Name: name, + Resume: resume, + Creator: operator, + Updater: operator, + CreateAt: time.Now(), + UpdateAt: time.Now(), } nodeEn, addrEn := s.genNodeEntity(apintoInfo.Cluster, apintoInfo.Nodes) err = s.store.Transaction(ctx, func(ctx context.Context) error { @@ -189,21 +189,21 @@ func (s *imlClusterService) Create(ctx context.Context, partitionId string, name } return FromEntity(en), nil } -func (s *imlClusterService) genNodeEntity(id string, nodes []*admin.Node) ([]*cluster.ClusterNode, []*cluster.ClusterNodeAddr) { - nodeEn := make([]*cluster.ClusterNode, 0, len(nodes)) - addrAllTemp := make([][]*cluster.ClusterNodeAddr, 0, len(nodes)) +func (s *imlClusterService) genNodeEntity(id string, nodes []*admin.Node) ([]*cluster.Node, []*cluster.NodeAddr) { + nodeEn := make([]*cluster.Node, 0, len(nodes)) + addrAllTemp := make([][]*cluster.NodeAddr, 0, len(nodes)) now := time.Now() for _, node := range nodes { - nodeEn = append(nodeEn, &cluster.ClusterNode{ + nodeEn = append(nodeEn, &cluster.Node{ Id: 0, UUID: node.Id, Name: node.Name, Cluster: id, UpdateTime: now, }) - aden := make([]*cluster.ClusterNodeAddr, 0, len(node.Peer)+len(node.Admin)+len(node.Server)) + aden := make([]*cluster.NodeAddr, 0, len(node.Peer)+len(node.Admin)+len(node.Server)) for _, addr := range node.Peer { - aden = append(aden, &cluster.ClusterNodeAddr{ + aden = append(aden, &cluster.NodeAddr{ Id: 0, Cluster: id, Node: node.Id, @@ -213,7 +213,7 @@ func (s *imlClusterService) genNodeEntity(id string, nodes []*admin.Node) ([]*cl }) } for _, addr := range node.Admin { - aden = append(aden, &cluster.ClusterNodeAddr{ + aden = append(aden, &cluster.NodeAddr{ Id: 0, Cluster: id, Node: node.Id, @@ -223,7 +223,7 @@ func (s *imlClusterService) genNodeEntity(id string, nodes []*admin.Node) ([]*cl }) } for _, addr := range node.Server { - aden = append(aden, &cluster.ClusterNodeAddr{ + aden = append(aden, &cluster.NodeAddr{ Id: 0, Cluster: id, Node: node.Id, @@ -341,22 +341,26 @@ func (s *imlClusterService) UpdateAddress(ctx context.Context, id string, addres } -func (s *imlClusterService) Nodes(ctx context.Context, id string) ([]*Node, error) { - nodeAddrs, err := s.nodeAddressStore.ListQuery(ctx, "`cluster` = ?", []interface{}{id}, "id desc") +func (s *imlClusterService) Nodes(ctx context.Context, clusterIds ...string) ([]*Node, error) { + w := make(map[string]interface{}) + if len(clusterIds) > 0 { + w["cluster"] = clusterIds + } + nodeAddrs, err := s.nodeAddressStore.List(ctx, w, "id desc") if err != nil { return nil, err } - nodes, err := s.nodeStore.ListQuery(ctx, "`cluster` = ?", []interface{}{id}, "id desc") + nodes, err := s.nodeStore.List(ctx, w, "id desc") if err != nil { return nil, err } - addrOfNode := utils.SliceToMapArray(nodeAddrs, func(i *cluster.ClusterNodeAddr) string { + addrOfNode := utils.SliceToMapArray(nodeAddrs, func(i *cluster.NodeAddr) string { return i.Node }) - return utils.SliceToSlice(nodes, func(i *cluster.ClusterNode) *Node { - addrs := utils.SliceToMapArrayO(addrOfNode[i.UUID], func(i *cluster.ClusterNodeAddr) (string, string) { + return utils.SliceToSlice(nodes, func(i *cluster.Node) *Node { + addrs := utils.SliceToMapArrayO(addrOfNode[i.UUID], func(i *cluster.NodeAddr) (string, string) { return i.Type, i.Addr }) @@ -404,15 +408,15 @@ func (s *imlClusterService) Search(ctx context.Context, keyword string, partitio } return utils.SliceToSlice(list, FromEntity), nil } -func (s *imlClusterService) List(ctx context.Context, partitionId ...string) ([]*Cluster, error) { - if len(partitionId) == 0 { +func (s *imlClusterService) List(ctx context.Context, clusterIds ...string) ([]*Cluster, error) { + if len(clusterIds) == 0 { list, err := s.store.List(ctx, make(map[string]interface{})) if err != nil { return nil, err } return utils.SliceToSlice(list, FromEntity), nil } - list, err := s.store.ListQuery(ctx, "`partition` in (?)", []interface{}{partitionId}, "update_at desc") + list, err := s.store.ListQuery(ctx, "`cluster` in (?)", []interface{}{clusterIds}, "update_at desc") if err != nil { return nil, err } diff --git a/service/cluster/model.go b/service/cluster/model.go index 732d96e..c3a9981 100644 --- a/service/cluster/model.go +++ b/service/cluster/model.go @@ -11,7 +11,6 @@ type Cluster struct { Name string Resume string Creator string - Partition string Updater string Status int CreateTime time.Time @@ -23,7 +22,6 @@ func FromEntity(entity *cluster.Cluster) *Cluster { Uuid: entity.UUID, Name: entity.Name, Resume: entity.Resume, - Partition: entity.Partition, Creator: entity.Creator, Updater: entity.Updater, CreateTime: entity.CreateAt, diff --git a/service/dynamic-module/iml.go b/service/dynamic-module/iml.go index bb55cc0..1b3b096 100644 --- a/service/dynamic-module/iml.go +++ b/service/dynamic-module/iml.go @@ -107,7 +107,6 @@ func (i *imlDynamicModulePublishService) Latest(ctx context.Context, dmID string ID: info.UUID, DynamicModule: info.DynamicModule, Module: info.Module, - Partition: info.Partition, Cluster: info.Cluster, Creator: info.Creator, Version: info.Version, @@ -129,7 +128,6 @@ func (i *imlDynamicModulePublishService) createEntityHandler(m *CreateDynamicMod UUID: m.ID, DynamicModule: m.DynamicModule, Module: m.Module, - Partition: m.Partition, Cluster: m.Cluster, Version: m.Version, CreateAt: now, diff --git a/service/dynamic-module/model.go b/service/dynamic-module/model.go index 322457f..68ecea7 100644 --- a/service/dynamic-module/model.go +++ b/service/dynamic-module/model.go @@ -27,7 +27,7 @@ type CreateDynamicModule struct { Id string Name string Driver string - //Partition string + //Cluster string Description string Config string Module string @@ -65,7 +65,6 @@ type DynamicModulePublish struct { ID string DynamicModule string Module string - Partition string Cluster string Creator string Version string @@ -77,7 +76,6 @@ func FromPublishEntity(ov *dynamic_module.DynamicModulePublish) *DynamicModulePu ID: ov.UUID, DynamicModule: ov.DynamicModule, Module: ov.Module, - Partition: ov.Partition, Cluster: ov.Cluster, Version: ov.Version, Creator: ov.Creator, @@ -89,7 +87,6 @@ type CreateDynamicModulePublish struct { ID string DynamicModule string Module string - Partition string Cluster string Version string } diff --git a/service/partition/iml.go b/service/partition/iml.go deleted file mode 100644 index 4489f74..0000000 --- a/service/partition/iml.go +++ /dev/null @@ -1,100 +0,0 @@ -package partition - -import ( - "context" - "time" - - "github.com/eolinker/go-common/utils" - - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/apipark/stores/partition" - "github.com/eolinker/go-common/auto" -) - -var ( - _ IPartitionService = (*imlPartitionService)(nil) -) - -type imlPartitionService struct { - store partition.IPartitionStore `autowired:""` - universally.IServiceGet[Partition] - universally.IServiceDelete - universally.IServiceCreate[CreatePartition] - universally.IServiceEdit[EditPartition] -} - -func (p *imlPartitionService) GetLabels(ctx context.Context, ids ...string) map[string]string { - if len(ids) == 0 { - return nil - } - list, err := p.store.ListQuery(ctx, "`uuid` in (?)", []interface{}{ids}, "id") - if err != nil { - return nil - } - return utils.SliceToMapO(list, func(i *partition.Partition) (string, string) { - return i.UUID, i.Name - }) -} - -func (p *imlPartitionService) OnComplete() { - p.IServiceGet = universally.NewGetSoftDelete[Partition, partition.Partition](p.store, toModel) - - p.IServiceDelete = universally.NewSoftDelete[partition.Partition](p.store) - - p.IServiceCreate = universally.NewCreatorSoftDelete[CreatePartition, partition.Partition](p.store, "partition", createEntityHandler, uniquestHandler, labelHandler) - - p.IServiceEdit = universally.NewEdit[EditPartition, partition.Partition](p.store, updateHandler, labelHandler) - - auto.RegisterService("partition", p) -} -func uniquestHandler(i *CreatePartition) []map[string]interface{} { - return []map[string]interface{}{{"uuid": i.Uuid}, {"name": i.Name}} - -} -func updateHandler(e *partition.Partition, i *EditPartition) { - if i.Name != nil { - e.Name = *i.Name - } - if i.Resume != nil { - e.Resume = *i.Resume - } - if i.Url != nil { - e.Url = *i.Url - } - if i.Prefix != nil { - e.Prefix = *i.Prefix - } - e.UpdateAt = time.Now() -} -func createEntityHandler(i *CreatePartition) *partition.Partition { - return &partition.Partition{ - Id: 0, - UUID: i.Uuid, - Name: i.Name, - CreateAt: time.Now(), - UpdateAt: time.Now(), - Resume: i.Resume, - Prefix: i.Prefix, - Url: i.Url, - Cluster: i.Cluster, - } -} - -func labelHandler(e *partition.Partition) []string { - return []string{e.UUID, e.Name, e.Url, e.Prefix, e.Resume} -} - -func toModel(i *partition.Partition) *Partition { - return &Partition{ - UUID: i.UUID, - Name: i.Name, - Resume: i.Resume, - Prefix: i.Prefix, - Url: i.Url, - Updater: i.Updater, - UpdateTime: i.UpdateAt, - Creator: i.Creator, - CreateTime: i.CreateAt, - Cluster: i.Cluster, - } -} diff --git a/service/partition/model.go b/service/partition/model.go deleted file mode 100644 index 8c7b50d..0000000 --- a/service/partition/model.go +++ /dev/null @@ -1,33 +0,0 @@ -package partition - -import "time" - -type Partition struct { - UUID string - Name string - Resume string - Prefix string - Url string - Updater string - UpdateTime time.Time - Creator string - CreateTime time.Time - Cluster string -} - -type CreatePartition struct { - Uuid string - Name string - Resume string - Prefix string - Url string - Cluster string -} - -type EditPartition struct { - Uuid string - Name *string - Resume *string - Prefix *string - Url *string -} diff --git a/service/partition/service.go b/service/partition/service.go deleted file mode 100644 index da58a0d..0000000 --- a/service/partition/service.go +++ /dev/null @@ -1,20 +0,0 @@ -package partition - -import ( - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/go-common/autowire" - "reflect" -) - -func init() { - autowire.Auto[IPartitionService](func() reflect.Value { - return reflect.ValueOf(new(imlPartitionService)) - }) -} - -type IPartitionService interface { - universally.IServiceGet[Partition] - universally.IServiceDelete - universally.IServiceCreate[CreatePartition] - universally.IServiceEdit[EditPartition] -} diff --git a/service/plugin-partition/iml.go b/service/plugin-cluster/iml.go similarity index 90% rename from service/plugin-partition/iml.go rename to service/plugin-cluster/iml.go index 460b033..5c69278 100644 --- a/service/plugin-partition/iml.go +++ b/service/plugin-cluster/iml.go @@ -1,14 +1,15 @@ -package plugin_partition +package plugin_cluster import ( "context" "errors" "fmt" + "time" + "github.com/eolinker/apipark/model/plugin_model" "github.com/eolinker/apipark/stores/plugin" "github.com/eolinker/go-common/utils" "gorm.io/gorm" - "time" ) var ( @@ -92,7 +93,7 @@ func (i *imlPluginService) GetDefine(ctx context.Context, name string) (*PluginD } -func (i *imlPluginService) GetConfig(ctx context.Context, partition string, name string) (*Config, *PluginDefine, error) { +func (i *imlPluginService) GetConfig(ctx context.Context, clusterId string, name string) (*Config, *PluginDefine, error) { define, err := i.defineStore.First(ctx, map[string]interface{}{ "name": name, @@ -104,7 +105,7 @@ func (i *imlPluginService) GetConfig(ctx context.Context, partition string, name return nil, nil, err } conf, _ := i.pluginPartitionStore.First(ctx, map[string]interface{}{ - "partition": partition, + "partition": clusterId, "Plugin": name, }) if conf == nil { @@ -155,7 +156,7 @@ func (i *imlPluginService) Options(ctx context.Context) []*PluginOption { }) } -func (i *imlPluginService) SetPartition(ctx context.Context, partition string, name string, status plugin_model.Status, config plugin_model.ConfigType) error { +func (i *imlPluginService) SetCluster(ctx context.Context, clusterId string, name string, status plugin_model.Status, config plugin_model.ConfigType) error { operator := utils.UserId(ctx) return i.defineStore.Transaction(ctx, func(txCtx context.Context) error { @@ -173,7 +174,7 @@ func (i *imlPluginService) SetPartition(ctx context.Context, partition string, n return fmt.Errorf("plugin not support config: %s[%s] width %s", define.Cname, name, define.Cname) } conf, err := i.pluginPartitionStore.First(ctx, map[string]interface{}{ - "partition": partition, + "partition": clusterId, "name": name, }) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { @@ -182,7 +183,7 @@ func (i *imlPluginService) SetPartition(ctx context.Context, partition string, n if conf == nil { conf = &plugin.Partition{ Id: 0, - Partition: partition, + Partition: clusterId, Plugin: define.Name, Config: config, Status: status, @@ -207,7 +208,7 @@ func (i *imlPluginService) SetPartition(ctx context.Context, partition string, n } -func (i *imlPluginService) ListPartition(ctx context.Context, partition string, kind ...plugin_model.Kind) ([]*ConfigPartition, error) { +func (i *imlPluginService) ListCluster(ctx context.Context, clusterId string, kind ...plugin_model.Kind) ([]*ConfigPartition, error) { defines, err := i.Defines(ctx, kind...) if err != nil { @@ -215,7 +216,7 @@ func (i *imlPluginService) ListPartition(ctx context.Context, partition string, } configList, err := i.pluginPartitionStore.List(ctx, map[string]interface{}{ - "partition": partition, + "partition": clusterId, }) if err != nil { return nil, err diff --git a/service/plugin-partition/model.go b/service/plugin-cluster/model.go similarity index 97% rename from service/plugin-partition/model.go rename to service/plugin-cluster/model.go index a0a6803..bf162c2 100644 --- a/service/plugin-partition/model.go +++ b/service/plugin-cluster/model.go @@ -1,9 +1,10 @@ -package plugin_partition +package plugin_cluster import ( + "time" + "github.com/eolinker/apipark/model/plugin_model" "github.com/eolinker/apipark/stores/plugin" - "time" ) type PluginOption struct { diff --git a/service/plugin-partition/service.go b/service/plugin-cluster/service.go similarity index 63% rename from service/plugin-partition/service.go rename to service/plugin-cluster/service.go index 3b7711f..3d39471 100644 --- a/service/plugin-partition/service.go +++ b/service/plugin-cluster/service.go @@ -1,18 +1,19 @@ -package plugin_partition +package plugin_cluster import ( "context" + "reflect" + "github.com/eolinker/apipark/model/plugin_model" "github.com/eolinker/go-common/autowire" - "reflect" ) type IPluginService interface { Defines(ctx context.Context, kind ...plugin_model.Kind) ([]*PluginDefine, error) Options(ctx context.Context) []*PluginOption - SetPartition(ctx context.Context, partition string, name string, status plugin_model.Status, config plugin_model.ConfigType) error - ListPartition(ctx context.Context, partition string, kind ...plugin_model.Kind) ([]*ConfigPartition, error) - GetConfig(ctx context.Context, partition string, name string) (*Config, *PluginDefine, error) + SetCluster(ctx context.Context, clusterId string, name string, status plugin_model.Status, config plugin_model.ConfigType) error + ListCluster(ctx context.Context, clusterId string, kind ...plugin_model.Kind) ([]*ConfigPartition, error) + GetConfig(ctx context.Context, clusterId string, name string) (*Config, *PluginDefine, error) GetDefine(ctx context.Context, name string) (*PluginDefine, error) SaveDefine(ctx context.Context, defines []*plugin_model.Define) error } diff --git a/service/project_diff/diff.go b/service/project_diff/diff.go index 0e9d9d9..2d66133 100644 --- a/service/project_diff/diff.go +++ b/service/project_diff/diff.go @@ -39,7 +39,7 @@ type UpstreamDiff struct { } type Diff struct { - Partitions []string `json:"partitions,omitempty"` - Apis []*ApiDiff `json:"apis"` - Upstreams []*UpstreamDiff `json:"upstreams"` + Clusters []string `json:"clusters,omitempty"` + Apis []*ApiDiff `json:"apis"` + Upstreams []*UpstreamDiff `json:"upstreams"` } diff --git a/service/publish/iml.go b/service/publish/iml.go index 5f6fad0..42bdeaf 100644 --- a/service/publish/iml.go +++ b/service/publish/iml.go @@ -26,12 +26,11 @@ type imlPublishService struct { func (s *imlPublishService) SetPublishStatus(ctx context.Context, status *Status) error { return s.statusStore.Save(ctx, &publish.Status{ - Publish: status.Publish, - Cluster: status.Cluster, - Partition: status.Partition, - Status: int(status.Status), - Error: status.Error, - UpdateAt: time.Now(), + Publish: status.Publish, + Cluster: status.Cluster, + Status: int(status.Status), + Error: status.Error, + UpdateAt: time.Now(), }) } @@ -43,12 +42,11 @@ func (s *imlPublishService) GetPublishStatus(ctx context.Context, id string) ([] return utils.SliceToSlice(list, func(s *publish.Status) *Status { return &Status{ - Publish: s.Publish, - Cluster: s.Cluster, - Partition: s.Partition, - Status: StatusType(s.Status), - Error: s.Error, - UpdateAt: s.UpdateAt, + Publish: s.Publish, + Cluster: s.Cluster, + Status: StatusType(s.Status), + Error: s.Error, + UpdateAt: s.UpdateAt, } }), nil } diff --git a/service/publish/model.go b/service/publish/model.go index a76b90a..2783b58 100644 --- a/service/publish/model.go +++ b/service/publish/model.go @@ -39,10 +39,10 @@ func FromEntity(e *publish.Publish) *Publish { } type Status struct { - Publish string - Cluster string - Partition string - Status StatusType - Error string - UpdateAt time.Time + Publish string + Cluster string + //Partition string + Status StatusType + Error string + UpdateAt time.Time } diff --git a/service/release/iml.go b/service/release/iml.go index 8b0c6b0..3f26d05 100644 --- a/service/release/iml.go +++ b/service/release/iml.go @@ -210,22 +210,22 @@ func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, projec //func (s *imlReleaseService) DiffUpstreams(ctx context.Context, baseUpstreams []*UpstreamCommit, targetUpstreams []*UpstreamCommit) []*UpstreamDiff { // Upstreams := make([]*UpstreamDiff, 0, len(targetUpstreams)+len(baseUpstreams)) // baseUpstreamMap := utils.SliceToMap(baseUpstreams, func(v *UpstreamCommit) string { -// return fmt.Sprintf("%s-%s", v.UpstreamCommit, v.Partition) +// return fmt.Sprintf("%s-%s", v.UpstreamCommit, v.Cluster) // }) // for _, targetUpstream := range targetUpstreams { -// key := fmt.Sprintf("%s-%s", targetUpstream.UpstreamCommit, targetUpstream.Partition) +// key := fmt.Sprintf("%s-%s", targetUpstream.UpstreamCommit, targetUpstream.Cluster) // if baseUpstream, ok := baseUpstreamMap[key]; ok { // if baseUpstream.Commit != targetUpstream.Commit { // Upstreams = append(Upstreams, &UpstreamDiff{ // UpstreamCommit: targetUpstream.UpstreamCommit, -// Partition: targetUpstream.Partition, +// Cluster: targetUpstream.Cluster, // Commit: targetUpstream.Commit, // Change: project_diff.ChangeTypeUpdate, // }) // } else { // Upstreams = append(Upstreams, &UpstreamDiff{ // UpstreamCommit: targetUpstream.UpstreamCommit, -// Partition: targetUpstream.Partition, +// Cluster: targetUpstream.Cluster, // Commit: targetUpstream.Commit, // Change: project_diff.ChangeTypeNone, // }) @@ -234,7 +234,7 @@ func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, projec // } else { // Upstreams = append(Upstreams, &UpstreamDiff{ // UpstreamCommit: targetUpstream.UpstreamCommit, -// Partition: targetUpstream.Partition, +// Cluster: targetUpstream.Cluster, // Commit: targetUpstream.Commit, // Change: project_diff.ChangeTypeNew, // }) @@ -243,7 +243,7 @@ func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, projec // for _, baseUpstream := range baseUpstreamMap { // Upstreams = append(Upstreams, &UpstreamDiff{ // UpstreamCommit: baseUpstream.UpstreamCommit, -// Partition: baseUpstream.Partition, +// Cluster: baseUpstream.Cluster, // Commit: baseUpstream.Commit, // Change: project_diff.ChangeTypeDelete, // }) diff --git a/service/release/model.go b/service/release/model.go index 776b2f3..1e80dc5 100644 --- a/service/release/model.go +++ b/service/release/model.go @@ -1,8 +1,9 @@ package release import ( - "github.com/eolinker/apipark/stores/release" "time" + + "github.com/eolinker/apipark/stores/release" ) type Release struct { @@ -63,7 +64,7 @@ type ProjectCommits struct { // //type UpstreamDiff struct { // UpstreamCommit string `json:"upstream,omitempty"` -// Partition string `json:"partition,omitempty"` +// Cluster string `json:"partition,omitempty"` // Commit string `json:"commit,omitempty"` // Change project_diff.ChangeType `json:"change,omitempty"` //} diff --git a/service/team/iml.go b/service/team/iml.go index ad9e9a7..d497477 100644 --- a/service/team/iml.go +++ b/service/team/iml.go @@ -59,7 +59,6 @@ func createEntityHandler(i *CreateTeam) *team.Team { UUID: i.Id, Name: i.Name, Description: i.Description, - Master: i.Master, CreateAt: time.Now(), UpdateAt: time.Now(), } @@ -71,9 +70,6 @@ func updateHandler(e *team.Team, i *EditTeam) { if i.Description != nil { e.Description = *i.Description } - if i.Master != nil { - e.Master = *i.Master - } e.UpdateAt = time.Now() } diff --git a/service/team/model.go b/service/team/model.go index 51ee360..d97f26b 100644 --- a/service/team/model.go +++ b/service/team/model.go @@ -7,10 +7,10 @@ import ( ) type Team struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Master string `json:"master"` + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + //Master string `json:"master"` Organization string `json:"organization"` CreateTime time.Time `json:"create_time"` UpdateTime time.Time `json:"update_time"` @@ -23,11 +23,11 @@ func FromEntity(e *team.Team) *Team { Id: e.UUID, Name: e.Name, Description: e.Description, - Master: e.Master, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, - Creator: e.Creator, - Updater: e.Updater, + //Master: e.Master, + CreateTime: e.CreateAt, + UpdateTime: e.UpdateAt, + Creator: e.Creator, + Updater: e.Updater, } } @@ -35,10 +35,10 @@ type CreateTeam struct { Id string `json:"id" ` Name string `json:"name" ` Description string `json:"description"` - Master string `json:"master" ` + //Master string `json:"master" ` } type EditTeam struct { Name *string `json:"name" ` Description *string `json:"description"` - Master *string `json:"master" ` + //Master *string `json:"master" ` } diff --git a/service/upstream/iml.go b/service/upstream/iml.go index 2c7a642..796198b 100644 --- a/service/upstream/iml.go +++ b/service/upstream/iml.go @@ -75,7 +75,6 @@ func (i *imlUpstreamService) Get(ctx context.Context, id string) (*Upstream, err Updater: t.Updater, CreateTime: t.CreateAt, UpdateTime: t.UpdateAt, - Partitions: t.Partitions, }, }, nil } @@ -84,16 +83,15 @@ func (i *imlUpstreamService) Save(ctx context.Context, u *SaveUpstream) error { now := time.Now() userId := utils.UserId(ctx) return i.store.Save(ctx, &upstream.Upstream{ - UUID: u.UUID, - Name: u.Name, - Project: u.Project, - Team: u.Team, - Remark: u.Remark, - Creator: userId, - Updater: userId, - CreateAt: now, - UpdateAt: now, - Partitions: u.Partitions, + UUID: u.UUID, + Name: u.Name, + Project: u.Project, + Team: u.Team, + Remark: u.Remark, + Creator: userId, + Updater: userId, + CreateAt: now, + UpdateAt: now, }) } diff --git a/service/upstream/model.go b/service/upstream/model.go index 4ce5616..5e9ee87 100644 --- a/service/upstream/model.go +++ b/service/upstream/model.go @@ -13,7 +13,6 @@ type Item struct { Creator string Updater string Remark string - Partitions []string CreateTime time.Time UpdateTime time.Time } @@ -28,8 +27,7 @@ type SaveUpstream struct { Project string Team string //Type string - Remark string - Partitions []string + Remark string } type ProxyHeader struct { diff --git a/stores/certificate/model.go b/stores/certificate/model.go index e47a67c..bf42b6a 100644 --- a/stores/certificate/model.go +++ b/stores/certificate/model.go @@ -5,8 +5,8 @@ import "time" type Certificate struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Partition string `gorm:"size:36;not null;column:partition;comment:分区;index:partition"` // 分区id Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Cluster string `gorm:"type:varchar(36);not null;column:cluster;comment:集群;index:cluster"` Domains []string `gorm:"type:text;not null;column:domains;comment:域名;serializer:json"` NotBefore time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:not_before;comment:生效时间"` NotAfter time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:not_after;comment:失效时间"` diff --git a/stores/cluster/model.go b/stores/cluster/model.go index f3ded44..abd3e45 100644 --- a/stores/cluster/model.go +++ b/stores/cluster/model.go @@ -3,15 +3,15 @@ package cluster import "time" type Cluster struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Partition string `gorm:"type:varchar(36);not null;column:partition;comment:partition"` - Resume string `gorm:"type:varchar(255);not null;column:resume;comment:resume"` - Creator string `gorm:"type:varchar(36);not null;column:creator;comment:creator" aovalue:"creator"` - Updater string `gorm:"type:varchar(36);not null;column:updater;comment:updater" aovalue:"updater"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + //Cluster string `gorm:"type:varchar(36);not null;column:partition;comment:partition"` + Resume string `gorm:"type:varchar(255);not null;column:resume;comment:resume"` + Creator string `gorm:"type:varchar(36);not null;column:creator;comment:creator" aovalue:"creator"` + Updater string `gorm:"type:varchar(36);not null;column:updater;comment:updater" aovalue:"updater"` + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` } func (c *Cluster) IdValue() int64 { @@ -21,7 +21,7 @@ func (c *Cluster) TableName() string { return "cluster" } -type ClusterNode struct { +type Node struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"size:36;not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` Name string `gorm:"size:100;not null;column:name;comment:name"` @@ -29,14 +29,14 @@ type ClusterNode struct { UpdateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` } -func (c *ClusterNode) IdValue() int64 { +func (c *Node) IdValue() int64 { return c.Id } -func (c *ClusterNode) TableName() string { +func (c *Node) TableName() string { return "cluster_node" } -type ClusterNodeAddr struct { +type NodeAddr struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` Cluster string `gorm:"column:cluster;type:varchar(36);NOT NULL;comment:cluster id;"` Node string `gorm:"column:node;type:varchar(36);NOT NULL;comment:node id;"` @@ -45,9 +45,9 @@ type ClusterNodeAddr struct { UpdateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` } -func (c *ClusterNodeAddr) IdValue() int64 { +func (c *NodeAddr) IdValue() int64 { return c.Id } -func (c *ClusterNodeAddr) TableName() string { +func (c *NodeAddr) TableName() string { return "cluster_node_addr" } diff --git a/stores/cluster/store.go b/stores/cluster/store.go index 36989e7..2c2e97b 100644 --- a/stores/cluster/store.go +++ b/stores/cluster/store.go @@ -1,22 +1,23 @@ package cluster import ( + "reflect" + "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/store" - "reflect" ) type IClusterNodeStore interface { - store.IBaseStore[ClusterNode] + store.IBaseStore[Node] } type storeClusterNode struct { - store.Store[ClusterNode] // 用struct方式继承,会自动填充并初始化表 + store.Store[Node] // 用struct方式继承,会自动填充并初始化表 } type IClusterNodeAddressStore interface { - store.IBaseStore[ClusterNodeAddr] + store.IBaseStore[NodeAddr] } type storeClusterNodeAddr struct { - store.Store[ClusterNodeAddr] // 用struct方式继承,会自动填充并初始化表 + store.Store[NodeAddr] // 用struct方式继承,会自动填充并初始化表 } func init() { diff --git a/stores/dynamic-module/model.go b/stores/dynamic-module/model.go index 385a181..54bf80e 100644 --- a/stores/dynamic-module/model.go +++ b/stores/dynamic-module/model.go @@ -31,7 +31,6 @@ type DynamicModulePublish struct { UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` DynamicModule string `gorm:"column:dynamic_module;type:VARCHAR(255);NOT NULL;comment:动态模块ID"` Module string `gorm:"column:module;type:VARCHAR(255);NOT NULL;comment:模块"` - Partition string `gorm:"column:partition;type:VARCHAR(255);NOT NULL;comment:分区"` Cluster string `gorm:"column:cluster;type:VARCHAR(255);NOT NULL;comment:集群"` Version string `gorm:"column:version;type:VARCHAR(32);NOT NULL;comment:版本"` Creator string `gorm:"type:varchar(36);not null;column:creator;comment:creator" aovalue:"creator"` diff --git a/stores/publish/model.go b/stores/publish/model.go index a94cfe4..e21defd 100644 --- a/stores/publish/model.go +++ b/stores/publish/model.go @@ -52,13 +52,12 @@ func (t *Latest) TableName() string { } type Status struct { - Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` - Publish string `gorm:"type:varchar(36);not null;column:publish;comment:publish id;uniqueIndex:unique"` - Cluster string `gorm:"type:varchar(36);not null;column:cluster;comment:cluster;uniqueIndex:unique"` - Partition string `gorm:"type:varchar(36);not null;column:partition;comment:partition;uniqueIndex:unique"` - Status int `gorm:"type:int(11);not null;column:status;index:status; comment:状态, 0: 申请中, 1: 审批中, 2: 审批通过, 3: 审批拒绝, 4: 已发布 5: 已中止 6: 已关闭 7: 发布中 8:发布失败"` - Error string `gorm:"type:text;not null;column:error;comment:错误信息"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` + Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` + Publish string `gorm:"type:varchar(36);not null;column:publish;comment:publish id;uniqueIndex:unique"` + Cluster string `gorm:"type:varchar(36);not null;column:cluster;comment:cluster;uniqueIndex:unique"` + Status int `gorm:"type:int(11);not null;column:status;index:status; comment:状态, 0: 申请中, 1: 审批中, 2: 审批通过, 3: 审批拒绝, 4: 已发布 5: 已中止 6: 已关闭 7: 发布中 8:发布失败"` + Error string `gorm:"type:text;not null;column:error;comment:错误信息"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` } func (t *Status) IdValue() int64 { diff --git a/stores/team/model.go b/stores/team/model.go index 41e2d35..4a920fb 100644 --- a/stores/team/model.go +++ b/stores/team/model.go @@ -5,16 +5,16 @@ import ( ) type Team struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"size:255;not null;column:description;comment:description"` - Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id - Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id - Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Description string `gorm:"size:255;not null;column:description;comment:description"` + //Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id + Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id + Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` + IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` } func (t *Team) IdValue() int64 { diff --git a/stores/upstream/model.go b/stores/upstream/model.go index d2fd02d..19383c7 100644 --- a/stores/upstream/model.go +++ b/stores/upstream/model.go @@ -5,18 +5,16 @@ import ( ) type Upstream struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"size:255;not null;column:name;comment:名称"` - Project string `gorm:"size:36;not null;column:project;comment:项目;index:project;"` // 项目id - Team string `gorm:"size:36;not null;column:team;comment:团队;index:team;"` // 团队id - //Type string `gorm:"type:varchar(100);not null;column:type;comment:type"` - Remark string `gorm:"size:255;not null;column:remark;comment:备注"` - Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator;"` // 创建人 - Updater string `gorm:"size:36;not null;column:updater;comment:更新人;index:updater;"` // 更新人 - Partitions []string `gorm:"type:text;column:partitions;comment:分区ID;serializer:json"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"size:255;not null;column:name;comment:名称"` + Project string `gorm:"size:36;not null;column:project;comment:项目;index:project;"` // 项目id + Team string `gorm:"size:36;not null;column:team;comment:团队;index:team;"` // 团队id + Remark string `gorm:"size:255;not null;column:remark;comment:备注"` + Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator;"` // 创建人 + Updater string `gorm:"size:36;not null;column:updater;comment:更新人;index:updater;"` // 更新人 + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` } func (u *Upstream) IdValue() int64 { From 588bb60d972b3f1d48726843e0847a84621aa09c Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 1 Aug 2024 09:27:55 +0800 Subject: [PATCH 05/19] =?UTF-8?q?project=E9=87=8D=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=B8=BAservice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/api/api.go | 27 +- controller/api/iml.go | 48 +- .../authorization.go | 32 + controller/application-authorization/iml.go | 37 ++ .../project-authorization/authorization.go | 31 - controller/project-authorization/iml.go | 38 -- controller/project/iml.go | 108 ---- controller/project/project.go | 65 -- controller/service/iml.go | 75 ++- controller/service/service.go | 40 +- controller/topology/iml.go | 22 - controller/topology/topology.go | 21 - controller/upstream/iml.go | 4 +- module/api/api.go | 24 +- module/api/dto/output.go | 3 +- module/api/iml.go | 122 ++-- .../auth-driver/aksk/aksk.go | 8 +- .../auth-driver/apikey/apikey.go | 8 +- .../auth-driver/auth.go | 4 +- .../auth-driver/basic/basic.go | 8 +- .../auth-driver/jwt/jwt.go | 14 +- .../auth-driver/manager.go | 0 .../auth-driver/oauth2/hash.go | 0 .../auth-driver/oauth2/oauth2.go | 8 +- .../authorization.go | 41 ++ .../dto/input.go | 2 +- .../dto/output.go | 2 +- .../iml.go | 151 +++-- module/catalogue/dto/output.go | 2 +- module/catalogue/iml.go | 295 +++++---- module/my-team/dto/output.go | 10 +- module/my-team/iml.go | 15 +- module/permit/project/iml.go | 6 +- module/project-authorization/authorization.go | 40 -- module/project/dto/input.go | 41 -- module/project/dto/output.go | 99 --- module/project/iml.go | 554 ----------------- module/project/project.go | 70 --- module/project_diff/iml.go | 4 +- module/project_diff/out.go | 2 +- module/publish/iml.go | 28 +- module/release/iml.go | 14 +- module/service/dto/input.go | 53 +- module/service/dto/output.go | 121 +++- module/service/iml.go | 581 +++++++++++++++++- module/service/module.go | 56 ++ module/service/service.go | 24 - module/subscribe/iml.go | 113 ++-- module/team/dto/output.go | 14 +- module/team/iml.go | 24 +- module/topology/dto/input.go | 1 - module/topology/dto/output.go | 22 - module/topology/iml.go | 104 ---- module/topology/topology.go | 21 - module/upstream/iml.go | 9 +- plugins/core/api.go | 24 +- plugins/core/core.go | 50 +- plugins/core/my-team.go | 8 +- plugins/core/project-authorization.go | 12 +- plugins/core/project.go | 38 -- plugins/core/service.go | 23 +- plugins/core/topology.go | 14 - service/api/iml.go | 65 +- service/api/model.go | 36 +- service/api/service.go | 13 +- service/application-authorization/iml.go | 106 ++++ .../model.go | 16 +- service/application-authorization/service.go | 23 + service/project-authorization/iml.go | 106 ---- service/project-authorization/service.go | 23 - service/project/iml.go | 129 ---- service/project/model.go | 57 -- service/project/service.go | 26 - service/service-doc/iml.go | 60 ++ service/service-doc/model.go | 19 + service/service-doc/service.go | 19 + service/service-tag/iml.go | 54 ++ service/service-tag/model.go | 11 + service/service-tag/service.go | 20 + service/service/iml.go | 347 ++--------- service/service/model.go | 119 ++-- service/service/service.go | 55 +- service/subscribe/iml.go | 1 - service/subscribe/model.go | 1 - stores/api/model.go | 29 +- stores/project/model.go | 50 -- stores/project/store.go | 47 -- stores/service/model.go | 77 ++- stores/service/store.go | 31 +- 89 files changed, 2055 insertions(+), 2920 deletions(-) create mode 100644 controller/application-authorization/authorization.go create mode 100644 controller/application-authorization/iml.go delete mode 100644 controller/project-authorization/authorization.go delete mode 100644 controller/project-authorization/iml.go delete mode 100644 controller/project/iml.go delete mode 100644 controller/project/project.go delete mode 100644 controller/topology/iml.go delete mode 100644 controller/topology/topology.go rename module/{project-authorization => application-authorization}/auth-driver/aksk/aksk.go (70%) rename module/{project-authorization => application-authorization}/auth-driver/apikey/apikey.go (67%) rename module/{project-authorization => application-authorization}/auth-driver/auth.go (91%) rename module/{project-authorization => application-authorization}/auth-driver/basic/basic.go (70%) rename module/{project-authorization => application-authorization}/auth-driver/jwt/jwt.go (82%) rename module/{project-authorization => application-authorization}/auth-driver/manager.go (100%) rename module/{project-authorization => application-authorization}/auth-driver/oauth2/hash.go (100%) rename module/{project-authorization => application-authorization}/auth-driver/oauth2/oauth2.go (81%) create mode 100644 module/application-authorization/authorization.go rename module/{project-authorization => application-authorization}/dto/input.go (95%) rename module/{project-authorization => application-authorization}/dto/output.go (96%) rename module/{project-authorization => application-authorization}/iml.go (51%) delete mode 100644 module/project-authorization/authorization.go delete mode 100644 module/project/dto/input.go delete mode 100644 module/project/dto/output.go delete mode 100644 module/project/iml.go delete mode 100644 module/project/project.go create mode 100644 module/service/module.go delete mode 100644 module/service/service.go delete mode 100644 module/topology/dto/input.go delete mode 100644 module/topology/dto/output.go delete mode 100644 module/topology/iml.go delete mode 100644 module/topology/topology.go delete mode 100644 plugins/core/project.go delete mode 100644 plugins/core/topology.go create mode 100644 service/application-authorization/iml.go rename service/{project-authorization => application-authorization}/model.go (79%) create mode 100644 service/application-authorization/service.go delete mode 100644 service/project-authorization/iml.go delete mode 100644 service/project-authorization/service.go delete mode 100644 service/project/iml.go delete mode 100644 service/project/model.go delete mode 100644 service/project/service.go create mode 100644 service/service-doc/iml.go create mode 100644 service/service-doc/model.go create mode 100644 service/service-doc/service.go create mode 100644 service/service-tag/iml.go create mode 100644 service/service-tag/model.go create mode 100644 service/service-tag/service.go delete mode 100644 stores/project/model.go delete mode 100644 stores/project/store.go diff --git a/controller/api/api.go b/controller/api/api.go index b35071b..dd3f64f 100644 --- a/controller/api/api.go +++ b/controller/api/api.go @@ -1,9 +1,10 @@ package api import ( - "github.com/gin-gonic/gin" "reflect" + "github.com/gin-gonic/gin" + "github.com/eolinker/go-common/autowire" api_dto "github.com/eolinker/apipark/module/api/dto" @@ -11,28 +12,28 @@ import ( type IAPIController interface { // Detail 获取API详情 - Detail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiDetail, error) + Detail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiDetail, error) // SimpleDetail 获取API简要详情 - SimpleDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiSimpleDetail, error) + SimpleDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiSimpleDetail, error) // Search 获取API列表 - Search(ctx *gin.Context, keyword string, pid string) ([]*api_dto.ApiItem, error) + Search(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiItem, error) // SimpleSearch 获取API简要列表 - SimpleSearch(ctx *gin.Context, keyword string, pid string) ([]*api_dto.ApiSimpleItem, error) - SimpleList(ctx *gin.Context, partitionId string, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) + SimpleSearch(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiSimpleItem, error) + SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) // Create 创建API - Create(ctx *gin.Context, pid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) + Create(ctx *gin.Context, serviceId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // Edit 编辑API - Edit(ctx *gin.Context, pid string, aid string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) + Edit(ctx *gin.Context, serviceId string, apiId string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) // Delete 删除API - Delete(ctx *gin.Context, pid string, aid string) error + Delete(ctx *gin.Context, serviceId string, apiId string) error // Copy 复制API - Copy(ctx *gin.Context, pid string, aid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) + Copy(ctx *gin.Context, serviceId string, apiId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // ApiDocDetail 获取API文档详情 - ApiDocDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiDocDetail, error) + ApiDocDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiDocDetail, error) // ApiProxyDetail 获取API代理详情 - ApiProxyDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiProxyDetail, error) + ApiProxyDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiProxyDetail, error) // Prefix 获取API前缀 - Prefix(ctx *gin.Context, pid string) (string, bool, error) + Prefix(ctx *gin.Context, serviceId string) (string, bool, error) } func init() { diff --git a/controller/api/iml.go b/controller/api/iml.go index 403e3f4..d3ed567 100644 --- a/controller/api/iml.go +++ b/controller/api/iml.go @@ -12,52 +12,52 @@ type imlAPIController struct { module api.IApiModule `autowired:""` } -func (i *imlAPIController) SimpleList(ctx *gin.Context, partitionId string, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) { - return i.module.SimpleList(ctx, input) +func (i *imlAPIController) SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) { + return i.module.SimpleList(ctx, serviceId) } -func (i *imlAPIController) Detail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiDetail, error) { - return i.module.Detail(ctx, pid, aid) +func (i *imlAPIController) Detail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiDetail, error) { + return i.module.Detail(ctx, serviceId, apiId) } -func (i *imlAPIController) SimpleDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiSimpleDetail, error) { - return i.module.SimpleDetail(ctx, pid, aid) +func (i *imlAPIController) SimpleDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiSimpleDetail, error) { + return i.module.SimpleDetail(ctx, serviceId, apiId) } -func (i *imlAPIController) Search(ctx *gin.Context, keyword string, pid string) ([]*api_dto.ApiItem, error) { - return i.module.Search(ctx, keyword, pid) +func (i *imlAPIController) Search(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiItem, error) { + return i.module.Search(ctx, keyword, serviceId) } -func (i *imlAPIController) SimpleSearch(ctx *gin.Context, keyword string, pid string) ([]*api_dto.ApiSimpleItem, error) { - return i.module.SimpleSearch(ctx, keyword, pid) +func (i *imlAPIController) SimpleSearch(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiSimpleItem, error) { + return i.module.SimpleSearch(ctx, keyword, serviceId) } -func (i *imlAPIController) Create(ctx *gin.Context, pid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { - return i.module.Create(ctx, pid, dto) +func (i *imlAPIController) Create(ctx *gin.Context, serviceId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { + return i.module.Create(ctx, serviceId, dto) } -func (i *imlAPIController) Edit(ctx *gin.Context, pid string, aid string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) { - return i.module.Edit(ctx, pid, aid, dto) +func (i *imlAPIController) Edit(ctx *gin.Context, serviceId string, apiId string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) { + return i.module.Edit(ctx, serviceId, apiId, dto) } -func (i *imlAPIController) Delete(ctx *gin.Context, pid string, aid string) error { - return i.module.Delete(ctx, pid, aid) +func (i *imlAPIController) Delete(ctx *gin.Context, serviceId string, apiId string) error { + return i.module.Delete(ctx, serviceId, apiId) } -func (i *imlAPIController) Copy(ctx *gin.Context, pid string, aid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { - return i.module.Copy(ctx, pid, aid, dto) +func (i *imlAPIController) Copy(ctx *gin.Context, serviceId string, apiId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { + return i.module.Copy(ctx, serviceId, apiId, dto) } -func (i *imlAPIController) ApiDocDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiDocDetail, error) { - return i.module.ApiDocDetail(ctx, pid, aid) +func (i *imlAPIController) ApiDocDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiDocDetail, error) { + return i.module.ApiDocDetail(ctx, serviceId, apiId) } -func (i *imlAPIController) ApiProxyDetail(ctx *gin.Context, pid string, aid string) (*api_dto.ApiProxyDetail, error) { - return i.module.ApiProxyDetail(ctx, pid, aid) +func (i *imlAPIController) ApiProxyDetail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiProxyDetail, error) { + return i.module.ApiProxyDetail(ctx, serviceId, apiId) } -func (i *imlAPIController) Prefix(ctx *gin.Context, pid string) (string, bool, error) { - prefix, err := i.module.Prefix(ctx, pid) +func (i *imlAPIController) Prefix(ctx *gin.Context, serviceId string) (string, bool, error) { + prefix, err := i.module.Prefix(ctx, serviceId) if err != nil { return "", false, err } diff --git a/controller/application-authorization/authorization.go b/controller/application-authorization/authorization.go new file mode 100644 index 0000000..86795c1 --- /dev/null +++ b/controller/application-authorization/authorization.go @@ -0,0 +1,32 @@ +package application_authorization + +import ( + "reflect" + + "github.com/gin-gonic/gin" + + "github.com/eolinker/go-common/autowire" + + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" +) + +type IAuthorizationController interface { + // AddAuthorization 添加项目鉴权信息 + AddAuthorization(ctx *gin.Context, pid string, info *application_authorization_dto.CreateAuthorization) (*application_authorization_dto.Authorization, error) + // EditAuthorization 修改项目鉴权信息 + EditAuthorization(ctx *gin.Context, pid string, aid string, info *application_authorization_dto.EditAuthorization) (*application_authorization_dto.Authorization, error) + // DeleteAuthorization 删除项目鉴权 + DeleteAuthorization(ctx *gin.Context, pid string, aid string) error + // Authorizations 获取项目鉴权列表 + Authorizations(ctx *gin.Context, pid string) ([]*application_authorization_dto.AuthorizationItem, error) + // Detail 获取项目鉴权详情(弹窗用) + Detail(ctx *gin.Context, pid string, aid string) ([]application_authorization_dto.DetailItem, error) + // Info 获取项目鉴权详情 + Info(ctx *gin.Context, pid string, aid string) (*application_authorization_dto.Authorization, error) +} + +func init() { + autowire.Auto[IAuthorizationController](func() reflect.Value { + return reflect.ValueOf(new(imlAuthorizationController)) + }) +} diff --git a/controller/application-authorization/iml.go b/controller/application-authorization/iml.go new file mode 100644 index 0000000..abdbec8 --- /dev/null +++ b/controller/application-authorization/iml.go @@ -0,0 +1,37 @@ +package application_authorization + +import ( + application_authorization "github.com/eolinker/apipark/module/application-authorization" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" + "github.com/gin-gonic/gin" +) + +var _ IAuthorizationController = (*imlAuthorizationController)(nil) + +type imlAuthorizationController struct { + module application_authorization.IAuthorizationModule `autowired:""` +} + +func (i *imlAuthorizationController) AddAuthorization(ctx *gin.Context, pid string, info *application_authorization_dto.CreateAuthorization) (*application_authorization_dto.Authorization, error) { + return i.module.AddAuthorization(ctx, pid, info) +} + +func (i *imlAuthorizationController) EditAuthorization(ctx *gin.Context, pid string, aid string, info *application_authorization_dto.EditAuthorization) (*application_authorization_dto.Authorization, error) { + return i.module.EditAuthorization(ctx, pid, aid, info) +} + +func (i *imlAuthorizationController) DeleteAuthorization(ctx *gin.Context, pid string, aid string) error { + return i.module.DeleteAuthorization(ctx, pid, aid) +} + +func (i *imlAuthorizationController) Authorizations(ctx *gin.Context, pid string) ([]*application_authorization_dto.AuthorizationItem, error) { + return i.module.Authorizations(ctx, pid) +} + +func (i *imlAuthorizationController) Detail(ctx *gin.Context, pid string, aid string) ([]application_authorization_dto.DetailItem, error) { + return i.module.Detail(ctx, pid, aid) +} + +func (i *imlAuthorizationController) Info(ctx *gin.Context, pid string, aid string) (*application_authorization_dto.Authorization, error) { + return i.module.Info(ctx, pid, aid) +} diff --git a/controller/project-authorization/authorization.go b/controller/project-authorization/authorization.go deleted file mode 100644 index 2b3f8c3..0000000 --- a/controller/project-authorization/authorization.go +++ /dev/null @@ -1,31 +0,0 @@ -package project_authorization - -import ( - "github.com/gin-gonic/gin" - "reflect" - - "github.com/eolinker/go-common/autowire" - - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" -) - -type IProjectAuthorizationController interface { - // AddAuthorization 添加项目鉴权信息 - AddAuthorization(ctx *gin.Context, pid string, info *project_authorization_dto.CreateAuthorization) (*project_authorization_dto.Authorization, error) - // EditAuthorization 修改项目鉴权信息 - EditAuthorization(ctx *gin.Context, pid string, aid string, info *project_authorization_dto.EditAuthorization) (*project_authorization_dto.Authorization, error) - // DeleteAuthorization 删除项目鉴权 - DeleteAuthorization(ctx *gin.Context, pid string, aid string) error - // Authorizations 获取项目鉴权列表 - Authorizations(ctx *gin.Context, pid string) ([]*project_authorization_dto.AuthorizationItem, error) - // Detail 获取项目鉴权详情(弹窗用) - Detail(ctx *gin.Context, pid string, aid string) ([]project_authorization_dto.DetailItem, error) - // Info 获取项目鉴权详情 - Info(ctx *gin.Context, pid string, aid string) (*project_authorization_dto.Authorization, error) -} - -func init() { - autowire.Auto[IProjectAuthorizationController](func() reflect.Value { - return reflect.ValueOf(new(imlProjectAuthorizationController)) - }) -} diff --git a/controller/project-authorization/iml.go b/controller/project-authorization/iml.go deleted file mode 100644 index 59dd904..0000000 --- a/controller/project-authorization/iml.go +++ /dev/null @@ -1,38 +0,0 @@ -package project_authorization - -import ( - project_authorization "github.com/eolinker/apipark/module/project-authorization" - "github.com/gin-gonic/gin" - - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" -) - -var _ IProjectAuthorizationController = (*imlProjectAuthorizationController)(nil) - -type imlProjectAuthorizationController struct { - module project_authorization.IProjectAuthorizationModule `autowired:""` -} - -func (i *imlProjectAuthorizationController) AddAuthorization(ctx *gin.Context, pid string, info *project_authorization_dto.CreateAuthorization) (*project_authorization_dto.Authorization, error) { - return i.module.AddAuthorization(ctx, pid, info) -} - -func (i *imlProjectAuthorizationController) EditAuthorization(ctx *gin.Context, pid string, aid string, info *project_authorization_dto.EditAuthorization) (*project_authorization_dto.Authorization, error) { - return i.module.EditAuthorization(ctx, pid, aid, info) -} - -func (i *imlProjectAuthorizationController) DeleteAuthorization(ctx *gin.Context, pid string, aid string) error { - return i.module.DeleteAuthorization(ctx, pid, aid) -} - -func (i *imlProjectAuthorizationController) Authorizations(ctx *gin.Context, pid string) ([]*project_authorization_dto.AuthorizationItem, error) { - return i.module.Authorizations(ctx, pid) -} - -func (i *imlProjectAuthorizationController) Detail(ctx *gin.Context, pid string, aid string) ([]project_authorization_dto.DetailItem, error) { - return i.module.Detail(ctx, pid, aid) -} - -func (i *imlProjectAuthorizationController) Info(ctx *gin.Context, pid string, aid string) (*project_authorization_dto.Authorization, error) { - return i.module.Info(ctx, pid, aid) -} diff --git a/controller/project/iml.go b/controller/project/iml.go deleted file mode 100644 index 53c159e..0000000 --- a/controller/project/iml.go +++ /dev/null @@ -1,108 +0,0 @@ -package project - -import ( - "github.com/eolinker/apipark/module/project" - project_dto "github.com/eolinker/apipark/module/project/dto" - "github.com/gin-gonic/gin" -) - -var ( - _ IProjectController = (*imlProjectController)(nil) - //_ IProjectMemberController = (*imlProjectMemberController)(nil) - _ IAppController = (*imlAppController)(nil) -) - -type imlProjectController struct { - module project.IProjectModule `autowired:""` -} - -func (i *imlProjectController) SearchMyProjects(ctx *gin.Context, teamId string, keyword string) ([]*project_dto.ProjectItem, error) { - return i.module.SearchMyProjects(ctx, teamId, keyword) -} - -func (i *imlProjectController) SimpleProjects(ctx *gin.Context, keyword string, partition string) ([]*project_dto.SimpleProjectItem, error) { - return i.module.SimpleProjects(ctx, keyword) -} - -func (i *imlProjectController) MySimpleProjects(ctx *gin.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { - return i.module.MySimpleProjects(ctx, keyword) -} - -func (i *imlProjectController) GetProject(ctx *gin.Context, id string) (*project_dto.Project, error) { - return i.module.GetProject(ctx, id) -} - -func (i *imlProjectController) Search(ctx *gin.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) { - return i.module.Search(ctx, teamID, keyword) -} - -func (i *imlProjectController) CreateProject(ctx *gin.Context, teamID string, project *project_dto.CreateProject) (*project_dto.Project, error) { - return i.module.CreateProject(ctx, teamID, project) -} - -func (i *imlProjectController) EditProject(ctx *gin.Context, id string, project *project_dto.EditProject) (*project_dto.Project, error) { - return i.module.EditProject(ctx, id, project) -} - -func (i *imlProjectController) DeleteProject(ctx *gin.Context, id string) error { - return i.module.DeleteProject(ctx, id) -} - -//type imlProjectMemberController struct { -// module project.IProjectMemberModule `autowired:""` -//} -// -//func (i *imlProjectMemberController) SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) { -// return i.module.SimpleMembersToAdd(ctx, pid, keyword) -//} -// -//func (i *imlProjectMemberController) SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) { -// return i.module.SimpleMembers(ctx, pid) -//} -// -//func (i *imlProjectMemberController) Members(ctx *gin.Context, id string, keyword string) ([]*project_dto.MemberItem, error) { -// return i.module.Members(ctx, id, keyword) -//} -// -//func (i *imlProjectMemberController) AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error { -// return i.module.AddMember(ctx, pid, users.Users) -//} -// -//func (i *imlProjectMemberController) RemoveMember(ctx *gin.Context, pid string, uid string) error { -// return i.module.RemoveMember(ctx, pid, []string{uid}) -//} -// -//func (i *imlProjectMemberController) EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error { -// return i.module.EditProjectMember(ctx, pid, uid, edit.Roles) -//} - -type imlAppController struct { - module project.IAppModule `autowired:""` -} - -func (i *imlAppController) CreateApp(ctx *gin.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) { - return i.module.CreateApp(ctx, teamID, input) -} -func (i *imlAppController) UpdateApp(ctx *gin.Context, appId string, input *project_dto.UpdateApp) (*project_dto.App, error) { - return i.module.UpdateApp(ctx, appId, input) -} - -func (i *imlAppController) SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*project_dto.AppItem, error) { - return i.module.SearchMyApps(ctx, teamId, keyword) -} - -func (i *imlAppController) SimpleApps(ctx *gin.Context, keyword string) ([]*project_dto.SimpleAppItem, error) { - return i.module.SimpleApps(ctx, keyword) -} - -func (i *imlAppController) MySimpleApps(ctx *gin.Context, keyword string) ([]*project_dto.SimpleAppItem, error) { - return i.module.MySimpleApps(ctx, keyword) -} - -func (i *imlAppController) GetApp(ctx *gin.Context, appId string) (*project_dto.App, error) { - return i.module.GetApp(ctx, appId) -} - -func (i *imlAppController) DeleteApp(ctx *gin.Context, appId string) error { - return i.module.DeleteApp(ctx, appId) -} diff --git a/controller/project/project.go b/controller/project/project.go deleted file mode 100644 index a3de0cc..0000000 --- a/controller/project/project.go +++ /dev/null @@ -1,65 +0,0 @@ -package project - -import ( - "reflect" - - project_dto "github.com/eolinker/apipark/module/project/dto" - "github.com/gin-gonic/gin" - - "github.com/eolinker/go-common/autowire" -) - -type IProjectController interface { - // GetProject 获取项目信息 - GetProject(ctx *gin.Context, id string) (*project_dto.Project, error) - // SearchMyProjects 搜索项目 - SearchMyProjects(ctx *gin.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) - Search(ctx *gin.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) - // CreateProject 创建项目 - CreateProject(ctx *gin.Context, teamID string, project *project_dto.CreateProject) (*project_dto.Project, error) - // EditProject 编辑项目 - EditProject(ctx *gin.Context, id string, project *project_dto.EditProject) (*project_dto.Project, error) - // DeleteProject 删除项目 - DeleteProject(ctx *gin.Context, id string) error - // SimpleProjects 获取简易项目列表 - SimpleProjects(ctx *gin.Context, keyword string, partition string) ([]*project_dto.SimpleProjectItem, error) - // MySimpleProjects 获取我的简易项目列表 - MySimpleProjects(ctx *gin.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) -} - -//type IProjectMemberController interface { -// // Members 获取项目成员列表 -// Members(ctx *gin.Context, pid string, keyword string) ([]*project_dto.MemberItem, error) -// // AddMember 添加项目成员 -// AddMember(ctx *gin.Context, pid string, users *project_dto.Users) error -// // RemoveMember 移除项目成员 -// RemoveMember(ctx *gin.Context, pid string, uid string) error -// // EditProjectMember 修改成员信息 -// EditProjectMember(ctx *gin.Context, pid string, uid string, edit *project_dto.EditProjectMember) error -// // SimpleMembers 简易系统成员列表 -// SimpleMembers(ctx *gin.Context, pid string) ([]*project_dto.SimpleMemberItem, error) -// SimpleMembersToAdd(ctx *gin.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) -//} - -type IAppController interface { - // CreateApp 创建应用 - CreateApp(ctx *gin.Context, teamID string, project *project_dto.CreateApp) (*project_dto.App, error) - - UpdateApp(ctx *gin.Context, appId string, project *project_dto.UpdateApp) (*project_dto.App, error) - SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*project_dto.AppItem, error) - // SimpleApps 获取简易项目列表 - SimpleApps(ctx *gin.Context, keyword string) ([]*project_dto.SimpleAppItem, error) - MySimpleApps(ctx *gin.Context, keyword string) ([]*project_dto.SimpleAppItem, error) - GetApp(ctx *gin.Context, appId string) (*project_dto.App, error) - DeleteApp(ctx *gin.Context, appId string) error -} - -func init() { - autowire.Auto[IProjectController](func() reflect.Value { - return reflect.ValueOf(new(imlProjectController)) - }) - - autowire.Auto[IAppController](func() reflect.Value { - return reflect.ValueOf(new(imlAppController)) - }) -} diff --git a/controller/service/iml.go b/controller/service/iml.go index 0bd3d9f..0f5b26f 100644 --- a/controller/service/iml.go +++ b/controller/service/iml.go @@ -1,24 +1,87 @@ package service import ( - "github.com/gin-gonic/gin" - "github.com/eolinker/apipark/module/service" service_dto "github.com/eolinker/apipark/module/service/dto" + "github.com/gin-gonic/gin" ) var ( _ IServiceController = (*imlServiceController)(nil) + _ IAppController = (*imlAppController)(nil) ) type imlServiceController struct { module service.IServiceModule `autowired:""` } -func (i *imlServiceController) ServiceDoc(ctx *gin.Context, pid string) (*service_dto.ServiceDoc, error) { - return i.module.ServiceDoc(ctx, pid) +func (i *imlServiceController) SearchMyServices(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.ServiceItem, error) { + return i.module.SearchMyServices(ctx, teamId, keyword) +} + +func (i *imlServiceController) Simple(ctx *gin.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) { + return i.module.Simple(ctx, keyword) +} + +func (i *imlServiceController) MySimple(ctx *gin.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) { + return i.module.MySimple(ctx, keyword) +} + +func (i *imlServiceController) Get(ctx *gin.Context, id string) (*service_dto.Service, error) { + return i.module.Get(ctx, id) +} + +func (i *imlServiceController) Search(ctx *gin.Context, teamID string, keyword string) ([]*service_dto.ServiceItem, error) { + return i.module.Search(ctx, teamID, keyword) +} + +func (i *imlServiceController) Create(ctx *gin.Context, teamID string, input *service_dto.CreateService) (*service_dto.Service, error) { + return i.module.Create(ctx, teamID, input) +} + +func (i *imlServiceController) Edit(ctx *gin.Context, id string, input *service_dto.EditService) (*service_dto.Service, error) { + return i.module.Edit(ctx, id, input) +} + +func (i *imlServiceController) Delete(ctx *gin.Context, id string) error { + return i.module.Delete(ctx, id) +} + +func (i *imlServiceController) ServiceDoc(ctx *gin.Context, id string) (*service_dto.ServiceDoc, error) { + return i.module.ServiceDoc(ctx, id) +} + +func (i *imlServiceController) SaveServiceDoc(ctx *gin.Context, id string, input *service_dto.SaveServiceDoc) error { + return i.module.SaveServiceDoc(ctx, id, input) +} + +type imlAppController struct { + module service.IAppModule `autowired:""` +} + +func (i *imlAppController) CreateApp(ctx *gin.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) { + return i.module.CreateApp(ctx, teamID, input) +} +func (i *imlAppController) UpdateApp(ctx *gin.Context, appId string, input *service_dto.UpdateApp) (*service_dto.App, error) { + return i.module.UpdateApp(ctx, appId, input) +} + +func (i *imlAppController) SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) { + return i.module.SearchMyApps(ctx, teamId, keyword) +} + +func (i *imlAppController) SimpleApps(ctx *gin.Context, keyword string) ([]*service_dto.SimpleAppItem, error) { + return i.module.SimpleApps(ctx, keyword) +} + +func (i *imlAppController) MySimpleApps(ctx *gin.Context, keyword string) ([]*service_dto.SimpleAppItem, error) { + return i.module.MySimpleApps(ctx, keyword) +} + +func (i *imlAppController) GetApp(ctx *gin.Context, appId string) (*service_dto.App, error) { + return i.module.GetApp(ctx, appId) } -func (i *imlServiceController) SaveServiceDoc(ctx *gin.Context, pid string, input *service_dto.SaveServiceDoc) error { - return i.module.SaveServiceDoc(ctx, pid, input) +func (i *imlAppController) DeleteApp(ctx *gin.Context, appId string) error { + return i.module.DeleteApp(ctx, appId) } diff --git a/controller/service/service.go b/controller/service/service.go index 23fc1e5..5b057b0 100644 --- a/controller/service/service.go +++ b/controller/service/service.go @@ -3,20 +3,52 @@ package service import ( "reflect" - "github.com/gin-gonic/gin" - service_dto "github.com/eolinker/apipark/module/service/dto" + "github.com/gin-gonic/gin" + "github.com/eolinker/go-common/autowire" ) type IServiceController interface { - ServiceDoc(ctx *gin.Context, pid string) (*service_dto.ServiceDoc, error) - SaveServiceDoc(ctx *gin.Context, pid string, input *service_dto.SaveServiceDoc) error + // Get 获取 + Get(ctx *gin.Context, id string) (*service_dto.Service, error) + // SearchMyServices 搜索服务 + SearchMyServices(ctx *gin.Context, teamID string, keyword string) ([]*service_dto.ServiceItem, error) + Search(ctx *gin.Context, teamID string, keyword string) ([]*service_dto.ServiceItem, error) + // Create 创建 + Create(ctx *gin.Context, teamID string, input *service_dto.CreateService) (*service_dto.Service, error) + // Edit 编辑 + Edit(ctx *gin.Context, id string, input *service_dto.EditService) (*service_dto.Service, error) + // Delete 删除 + Delete(ctx *gin.Context, id string) error + // Simple 获取简易列表 + Simple(ctx *gin.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) + // MySimple 获取我的简易列表 + MySimple(ctx *gin.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) + ServiceDoc(ctx *gin.Context, id string) (*service_dto.ServiceDoc, error) + SaveServiceDoc(ctx *gin.Context, id string, input *service_dto.SaveServiceDoc) error +} + +type IAppController interface { + // CreateApp 创建应用 + CreateApp(ctx *gin.Context, teamID string, project *service_dto.CreateApp) (*service_dto.App, error) + + UpdateApp(ctx *gin.Context, appId string, project *service_dto.UpdateApp) (*service_dto.App, error) + SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) + // SimpleApps 获取简易项目列表 + SimpleApps(ctx *gin.Context, keyword string) ([]*service_dto.SimpleAppItem, error) + MySimpleApps(ctx *gin.Context, keyword string) ([]*service_dto.SimpleAppItem, error) + GetApp(ctx *gin.Context, appId string) (*service_dto.App, error) + DeleteApp(ctx *gin.Context, appId string) error } func init() { autowire.Auto[IServiceController](func() reflect.Value { return reflect.ValueOf(new(imlServiceController)) }) + + autowire.Auto[IAppController](func() reflect.Value { + return reflect.ValueOf(new(imlAppController)) + }) } diff --git a/controller/topology/iml.go b/controller/topology/iml.go deleted file mode 100644 index 8fcd50b..0000000 --- a/controller/topology/iml.go +++ /dev/null @@ -1,22 +0,0 @@ -package topology - -import ( - "github.com/gin-gonic/gin" - - "github.com/eolinker/apipark/module/topology" - topology_dto "github.com/eolinker/apipark/module/topology/dto" -) - -var _ ITopologyController = (*imlTopologyController)(nil) - -type imlTopologyController struct { - module topology.ITopologyModule `autowired:""` -} - -func (i *imlTopologyController) SystemTopology(ctx *gin.Context) ([]*topology_dto.ProjectItem, []*topology_dto.ServiceItem, error) { - return i.module.SystemTopology(ctx) -} - -func (i *imlTopologyController) ProjectTopology(ctx *gin.Context, projectID string) ([]*topology_dto.ServiceItem, []*topology_dto.TopologyItem, []*topology_dto.TopologyItem, error) { - return i.module.ProjectTopology(ctx, projectID) -} diff --git a/controller/topology/topology.go b/controller/topology/topology.go deleted file mode 100644 index 736d7ab..0000000 --- a/controller/topology/topology.go +++ /dev/null @@ -1,21 +0,0 @@ -package topology - -import ( - "github.com/gin-gonic/gin" - "reflect" - - "github.com/eolinker/go-common/autowire" - - topology_dto "github.com/eolinker/apipark/module/topology/dto" -) - -type ITopologyController interface { - SystemTopology(ctx *gin.Context) ([]*topology_dto.ProjectItem, []*topology_dto.ServiceItem, error) - ProjectTopology(ctx *gin.Context, projectID string) ([]*topology_dto.ServiceItem, []*topology_dto.TopologyItem, []*topology_dto.TopologyItem, error) -} - -func init() { - autowire.Auto[ITopologyController](func() reflect.Value { - return reflect.ValueOf(new(imlTopologyController)) - }) -} diff --git a/controller/upstream/iml.go b/controller/upstream/iml.go index 936ebb4..41fb391 100644 --- a/controller/upstream/iml.go +++ b/controller/upstream/iml.go @@ -2,7 +2,7 @@ package upstream import ( "github.com/eolinker/apipark/module/cluster" - "github.com/eolinker/apipark/module/project" + "github.com/eolinker/apipark/module/service" "github.com/eolinker/apipark/module/upstream" upstream_dto "github.com/eolinker/apipark/module/upstream/dto" "github.com/gin-gonic/gin" @@ -14,7 +14,7 @@ var ( type imlUpstreamController struct { upstreamModule upstream.IUpstreamModule `autowired:""` - projectModule project.IProjectModule `autowired:""` + projectModule service.IServiceModule `autowired:""` partitionModule cluster.IClusterModule `autowired:""` } diff --git a/module/api/api.go b/module/api/api.go index 524d471..0dcc903 100644 --- a/module/api/api.go +++ b/module/api/api.go @@ -11,28 +11,28 @@ import ( type IApiModule interface { // Detail 获取API详情 - Detail(ctx context.Context, pid string, aid string) (*api_dto.ApiDetail, error) + Detail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiDetail, error) // SimpleDetail 获取API简要详情 - SimpleDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiSimpleDetail, error) + SimpleDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiSimpleDetail, error) // Search 获取API列表 - Search(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiItem, error) + Search(ctx context.Context, keyword string, serviceId string) ([]*api_dto.ApiItem, error) // SimpleSearch 获取API简要列表 - SimpleSearch(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiSimpleItem, error) - SimpleList(ctx context.Context, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) + SimpleSearch(ctx context.Context, keyword string, serviceId string) ([]*api_dto.ApiSimpleItem, error) + SimpleList(ctx context.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) // Create 创建API - Create(ctx context.Context, pid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) + Create(ctx context.Context, serviceId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // Edit 编辑API - Edit(ctx context.Context, pid string, aid string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) + Edit(ctx context.Context, serviceId string, apiId string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) // Delete 删除API - Delete(ctx context.Context, pid string, aid string) error + Delete(ctx context.Context, serviceId string, apiId string) error // Copy 复制API - Copy(ctx context.Context, pid string, aid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) + Copy(ctx context.Context, serviceId string, apiId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // ApiDocDetail 获取API文档详情 - ApiDocDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiDocDetail, error) + ApiDocDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiDocDetail, error) // ApiProxyDetail 获取API代理详情 - ApiProxyDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiProxyDetail, error) + ApiProxyDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiProxyDetail, error) // Prefix 获取API前缀 - Prefix(ctx context.Context, pid string) (string, error) + Prefix(ctx context.Context, serviceId string) (string, error) } func init() { diff --git a/module/api/dto/output.go b/module/api/dto/output.go index ead25af..277643c 100644 --- a/module/api/dto/output.go +++ b/module/api/dto/output.go @@ -2,6 +2,7 @@ package api_dto import ( "encoding/json" + "github.com/eolinker/go-common/utils" "github.com/eolinker/apipark/service/api" @@ -33,7 +34,7 @@ type ApiDetail struct { Doc map[string]interface{} `json:"doc"` } -func GenApiSimpleDetail(api *api.APIInfo) *ApiSimpleDetail { +func GenApiSimpleDetail(api *api.Info) *ApiSimpleDetail { match := make([]Match, 0) if api.Match == "" { api.Match = "[]" diff --git a/module/api/iml.go b/module/api/iml.go index d56df96..e3c7481 100644 --- a/module/api/iml.go +++ b/module/api/iml.go @@ -7,6 +7,7 @@ import ( "fmt" "strings" + "github.com/eolinker/apipark/service/service" "github.com/eolinker/apipark/service/upstream" "gorm.io/gorm" @@ -18,8 +19,6 @@ import ( "github.com/eolinker/go-common/auto" "github.com/eolinker/go-common/utils" - "github.com/eolinker/apipark/service/project" - "github.com/eolinker/go-common/store" "github.com/eolinker/apipark/service/api" @@ -29,26 +28,22 @@ import ( var _ IApiModule = (*imlApiModule)(nil) var ( - projectMustAsServer = map[string]bool{ + asServer = map[string]bool{ "as_server": true, } ) type imlApiModule struct { teamService team.ITeamService `autowired:""` - projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` apiService api.IAPIService `autowired:""` upstreamService upstream.IUpstreamService `autowired:""` transaction store.ITransaction `autowired:""` } -func (i *imlApiModule) SimpleList(ctx context.Context, input *api_dto.ListInput) ([]*api_dto.ApiSimpleItem, error) { - projectIds := input.Projects - w := make(map[string]interface{}) - if len(projectIds) > 0 { - w["project"] = projectIds - } - list, err := i.apiService.Search(ctx, "", w) +func (i *imlApiModule) SimpleList(ctx context.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) { + + list, err := i.apiService.ListForService(ctx, serviceId) apiInfos, err := i.apiService.ListInfo(ctx, utils.SliceToSlice(list, func(s *api.API) string { return s.UUID })...) @@ -56,7 +51,7 @@ func (i *imlApiModule) SimpleList(ctx context.Context, input *api_dto.ListInput) return nil, err } - out := utils.SliceToSlice(apiInfos, func(item *api.APIInfo) *api_dto.ApiSimpleItem { + out := utils.SliceToSlice(apiInfos, func(item *api.Info) *api_dto.ApiSimpleItem { return &api_dto.ApiSimpleItem{ Id: item.UUID, Name: item.Name, @@ -67,13 +62,13 @@ func (i *imlApiModule) SimpleList(ctx context.Context, input *api_dto.ListInput) return out, nil } -func (i *imlApiModule) Detail(ctx context.Context, pid string, aid string) (*api_dto.ApiDetail, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Detail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiDetail, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - detail, err := i.apiService.GetInfo(ctx, aid) + detail, err := i.apiService.GetInfo(ctx, apiId) if err != nil { return nil, err } @@ -81,7 +76,7 @@ func (i *imlApiModule) Detail(ctx context.Context, pid string, aid string) (*api apiDetail := &api_dto.ApiDetail{ ApiSimpleDetail: *api_dto.GenApiSimpleDetail(detail), } - proxy, err := i.apiService.LatestProxy(ctx, aid) + proxy, err := i.apiService.LatestProxy(ctx, apiId) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err @@ -92,7 +87,7 @@ func (i *imlApiModule) Detail(ctx context.Context, pid string, aid string) (*api apiDetail.Proxy = api_dto.FromServiceProxy(proxy.Data) } - document, err := i.apiService.LatestDocument(ctx, aid) + document, err := i.apiService.LatestDocument(ctx, apiId) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err @@ -110,13 +105,13 @@ func (i *imlApiModule) Detail(ctx context.Context, pid string, aid string) (*api return apiDetail, nil } -func (i *imlApiModule) SimpleDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiSimpleDetail, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) SimpleDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiSimpleDetail, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - detail, err := i.apiService.GetInfo(ctx, aid) + detail, err := i.apiService.GetInfo(ctx, apiId) if err != nil { return nil, err } @@ -124,14 +119,14 @@ func (i *imlApiModule) SimpleDetail(ctx context.Context, pid string, aid string) return api_dto.GenApiSimpleDetail(detail), nil } -func (i *imlApiModule) Search(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiItem, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Search(ctx context.Context, keyword string, serviceId string) ([]*api_dto.ApiItem, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } list, err := i.apiService.Search(ctx, keyword, map[string]interface{}{ - "project": pid, + "service": serviceId, }) if err != nil { return nil, err @@ -142,10 +137,10 @@ func (i *imlApiModule) Search(ctx context.Context, keyword string, pid string) ( if err != nil { return nil, err } - utils.Sort(apiInfos, func(a, b *api.APIInfo) bool { + utils.Sort(apiInfos, func(a, b *api.Info) bool { return a.UpdateAt.After(b.UpdateAt) }) - out := utils.SliceToSlice(apiInfos, func(item *api.APIInfo) *api_dto.ApiItem { + out := utils.SliceToSlice(apiInfos, func(item *api.Info) *api_dto.ApiItem { return &api_dto.ApiItem{ Id: item.UUID, Name: item.Name, @@ -162,22 +157,25 @@ func (i *imlApiModule) Search(ctx context.Context, keyword string, pid string) ( return out, nil } -func (i *imlApiModule) SimpleSearch(ctx context.Context, keyword string, pid string) ([]*api_dto.ApiSimpleItem, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) SimpleSearch(ctx context.Context, keyword string, serviceId string) ([]*api_dto.ApiSimpleItem, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } list, err := i.apiService.Search(ctx, keyword, map[string]interface{}{ - "project": pid, + "service": serviceId, }) + if err != nil { + return nil, err + } apiInfos, err := i.apiService.ListInfo(ctx, utils.SliceToSlice(list, func(s *api.API) string { return s.UUID })...) if err != nil { return nil, err } - out := utils.SliceToSlice(apiInfos, func(item *api.APIInfo) *api_dto.ApiSimpleItem { + out := utils.SliceToSlice(apiInfos, func(item *api.Info) *api_dto.ApiSimpleItem { return &api_dto.ApiSimpleItem{ Id: item.UUID, Name: item.Name, @@ -188,12 +186,12 @@ func (i *imlApiModule) SimpleSearch(ctx context.Context, keyword string, pid str return out, nil } -func (i *imlApiModule) Create(ctx context.Context, pid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { - info, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Create(ctx context.Context, serviceId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { + info, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - prefix, err := i.Prefix(ctx, pid) + prefix, err := i.Prefix(ctx, serviceId) if err != nil { return nil, err } @@ -226,7 +224,7 @@ func (i *imlApiModule) Create(ctx context.Context, pid string, dto *api_dto.Crea UUID: dto.Id, Name: dto.Name, Description: dto.Description, - Project: pid, + Service: serviceId, Team: info.Team, Method: dto.Method, Path: path, @@ -237,11 +235,11 @@ func (i *imlApiModule) Create(ctx context.Context, pid string, dto *api_dto.Crea if err != nil { return nil, err } - return i.SimpleDetail(ctx, pid, dto.Id) + return i.SimpleDetail(ctx, serviceId, dto.Id) } -func (i *imlApiModule) Edit(ctx context.Context, pid string, aid string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Edit(ctx context.Context, serviceId string, apiId string, dto *api_dto.EditApi) (*api_dto.ApiSimpleDetail, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } @@ -249,7 +247,7 @@ func (i *imlApiModule) Edit(ctx context.Context, pid string, aid string, dto *ap err = i.transaction.Transaction(ctx, func(ctx context.Context) error { var up *string if dto.Proxy != nil { - err = i.apiService.SaveProxy(ctx, aid, api_dto.ToServiceProxy(dto.Proxy)) + err = i.apiService.SaveProxy(ctx, apiId, api_dto.ToServiceProxy(dto.Proxy)) if err != nil { return err } @@ -257,7 +255,7 @@ func (i *imlApiModule) Edit(ctx context.Context, pid string, aid string, dto *ap // up = &dto.Proxy.Upstream //} } - err = i.apiService.Save(ctx, aid, &api.EditAPI{ + err = i.apiService.Save(ctx, apiId, &api.EditAPI{ Name: dto.Info.Name, Description: dto.Info.Description, Upstream: up, @@ -267,7 +265,7 @@ func (i *imlApiModule) Edit(ctx context.Context, pid string, aid string, dto *ap } if dto.Doc != nil { - err = i.apiService.SaveDocument(ctx, aid, api_dto.ToServiceDocument(*dto.Doc)) + err = i.apiService.SaveDocument(ctx, apiId, api_dto.ToServiceDocument(*dto.Doc)) if err != nil { return err } @@ -278,27 +276,27 @@ func (i *imlApiModule) Edit(ctx context.Context, pid string, aid string, dto *ap if err != nil { return nil, err } - return i.SimpleDetail(ctx, pid, aid) + return i.SimpleDetail(ctx, serviceId, apiId) } -func (i *imlApiModule) Delete(ctx context.Context, pid string, aid string) error { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Delete(ctx context.Context, serviceId string, apiId string) error { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return err } - return i.apiService.Delete(ctx, aid) + return i.apiService.Delete(ctx, apiId) } -func (i *imlApiModule) Copy(ctx context.Context, pid string, aid string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { - info, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Copy(ctx context.Context, serviceId string, apiId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) { + info, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - oldApi, err := i.apiService.Get(ctx, aid) + oldApi, err := i.apiService.Get(ctx, apiId) if err != nil { return nil, err } - prefix, err := i.Prefix(ctx, pid) + prefix, err := i.Prefix(ctx, serviceId) if err != nil { return nil, err } @@ -312,7 +310,7 @@ func (i *imlApiModule) Copy(ctx context.Context, pid string, aid string, dto *ap } path := fmt.Sprintf("%s/%s", strings.TrimSuffix(prefix, "/"), strings.TrimPrefix(dto.Path, "/")) - err = i.apiService.Exist(ctx, pid, &api.ExistAPI{Path: path, Method: dto.Method}) + err = i.apiService.Exist(ctx, serviceId, &api.ExistAPI{Path: path, Method: dto.Method}) if err != nil { return err } @@ -348,7 +346,7 @@ func (i *imlApiModule) Copy(ctx context.Context, pid string, aid string, dto *ap return i.apiService.Create(ctx, &api.CreateAPI{ UUID: dto.Id, Name: dto.Name, - Project: pid, + Service: serviceId, Team: info.Team, Method: dto.Method, Path: path, @@ -360,16 +358,16 @@ func (i *imlApiModule) Copy(ctx context.Context, pid string, aid string, dto *ap if err != nil { return nil, err } - return i.SimpleDetail(ctx, pid, dto.Id) + return i.SimpleDetail(ctx, serviceId, dto.Id) } -func (i *imlApiModule) ApiDocDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiDocDetail, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) ApiDocDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiDocDetail, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - apiBase, err := i.apiService.Get(ctx, aid) + apiBase, err := i.apiService.Get(ctx, apiId) if err != nil { return nil, err } @@ -381,7 +379,7 @@ func (i *imlApiModule) ApiDocDetail(ctx context.Context, pid string, aid string) if err != nil { return nil, err } - document, err := i.apiService.LatestDocument(ctx, aid) + document, err := i.apiService.LatestDocument(ctx, apiId) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err @@ -401,23 +399,23 @@ func (i *imlApiModule) ApiDocDetail(ctx context.Context, pid string, aid string) }, nil } -func (i *imlApiModule) ApiProxyDetail(ctx context.Context, pid string, aid string) (*api_dto.ApiProxyDetail, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) ApiProxyDetail(ctx context.Context, serviceId string, apiId string) (*api_dto.ApiProxyDetail, error) { + _, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - apiBase, err := i.apiService.Get(ctx, aid) + apiBase, err := i.apiService.Get(ctx, apiId) if err != nil { return nil, err } if apiBase.IsDelete { return nil, errors.New("api is delete") } - if apiBase.Project != pid { + if apiBase.Service != serviceId { return nil, errors.New("api is not in project") } - detail, err := i.apiService.GetInfo(ctx, aid) + detail, err := i.apiService.GetInfo(ctx, apiId) if err != nil { return nil, err } @@ -425,7 +423,7 @@ func (i *imlApiModule) ApiProxyDetail(ctx context.Context, pid string, aid strin apiDetail := &api_dto.ApiProxyDetail{ ApiSimpleDetail: *api_dto.GenApiSimpleDetail(detail), } - proxy, err := i.apiService.LatestProxy(ctx, aid) + proxy, err := i.apiService.LatestProxy(ctx, apiId) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err @@ -438,8 +436,8 @@ func (i *imlApiModule) ApiProxyDetail(ctx context.Context, pid string, aid strin } -func (i *imlApiModule) Prefix(ctx context.Context, pid string) (string, error) { - pInfo, err := i.projectService.CheckProject(ctx, pid, projectMustAsServer) +func (i *imlApiModule) Prefix(ctx context.Context, serviceId string) (string, error) { + pInfo, err := i.serviceService.Check(ctx, serviceId, asServer) if err != nil { return "", err } diff --git a/module/project-authorization/auth-driver/aksk/aksk.go b/module/application-authorization/auth-driver/aksk/aksk.go similarity index 70% rename from module/project-authorization/auth-driver/aksk/aksk.go rename to module/application-authorization/auth-driver/aksk/aksk.go index 0b37354..801c9f9 100644 --- a/module/project-authorization/auth-driver/aksk/aksk.go +++ b/module/application-authorization/auth-driver/aksk/aksk.go @@ -4,9 +4,9 @@ import ( "encoding/json" "fmt" - auth_driver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + auth_driver "github.com/eolinker/apipark/module/application-authorization/auth-driver" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) var _ auth_driver.IAuthConfig = &Config{} @@ -40,8 +40,8 @@ func (a *Config) Valid() ([]byte, error) { return json.Marshal(a) } -func (a *Config) Detail() []project_authorization_dto.DetailItem { - return []project_authorization_dto.DetailItem{ +func (a *Config) Detail() []application_authorization_dto.DetailItem { + return []application_authorization_dto.DetailItem{ { Key: "Access Key", Value: a.Ak, diff --git a/module/project-authorization/auth-driver/apikey/apikey.go b/module/application-authorization/auth-driver/apikey/apikey.go similarity index 67% rename from module/project-authorization/auth-driver/apikey/apikey.go rename to module/application-authorization/auth-driver/apikey/apikey.go index 90c662a..b102efb 100644 --- a/module/project-authorization/auth-driver/apikey/apikey.go +++ b/module/application-authorization/auth-driver/apikey/apikey.go @@ -4,11 +4,11 @@ import ( "encoding/json" "fmt" - auth_driver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + auth_driver "github.com/eolinker/apipark/module/application-authorization/auth-driver" "github.com/eolinker/go-common/utils" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) const ( @@ -37,8 +37,8 @@ func (a *Config) Valid() ([]byte, error) { return json.Marshal(a) } -func (a *Config) Detail() []project_authorization_dto.DetailItem { - return []project_authorization_dto.DetailItem{ +func (a *Config) Detail() []application_authorization_dto.DetailItem { + return []application_authorization_dto.DetailItem{ { Key: "Apikey", Value: a.Apikey, diff --git a/module/project-authorization/auth-driver/auth.go b/module/application-authorization/auth-driver/auth.go similarity index 91% rename from module/project-authorization/auth-driver/auth.go rename to module/application-authorization/auth-driver/auth.go index dcae6a2..d6bd332 100644 --- a/module/project-authorization/auth-driver/auth.go +++ b/module/application-authorization/auth-driver/auth.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) type IAuth interface { @@ -16,7 +16,7 @@ type IAuth interface { type IAuthConfig interface { ID() string Valid() ([]byte, error) - Detail() []project_authorization_dto.DetailItem + Detail() []application_authorization_dto.DetailItem } type Auth struct { diff --git a/module/project-authorization/auth-driver/basic/basic.go b/module/application-authorization/auth-driver/basic/basic.go similarity index 70% rename from module/project-authorization/auth-driver/basic/basic.go rename to module/application-authorization/auth-driver/basic/basic.go index 873ae7a..4e53684 100644 --- a/module/project-authorization/auth-driver/basic/basic.go +++ b/module/application-authorization/auth-driver/basic/basic.go @@ -4,9 +4,9 @@ import ( "encoding/json" "fmt" - auth_driver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + auth_driver "github.com/eolinker/apipark/module/application-authorization/auth-driver" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) var _ auth_driver.IAuthConfig = &Config{} @@ -39,9 +39,9 @@ func (cfg *Config) Valid() ([]byte, error) { return json.Marshal(cfg) } -func (cfg *Config) Detail() []project_authorization_dto.DetailItem { +func (cfg *Config) Detail() []application_authorization_dto.DetailItem { - return []project_authorization_dto.DetailItem{ + return []application_authorization_dto.DetailItem{ {Key: "用户名", Value: cfg.UserName}, {Key: "密码", Value: cfg.Password}, } diff --git a/module/project-authorization/auth-driver/jwt/jwt.go b/module/application-authorization/auth-driver/jwt/jwt.go similarity index 82% rename from module/project-authorization/auth-driver/jwt/jwt.go rename to module/application-authorization/auth-driver/jwt/jwt.go index 5a3e8a5..0c3f06e 100644 --- a/module/project-authorization/auth-driver/jwt/jwt.go +++ b/module/application-authorization/auth-driver/jwt/jwt.go @@ -7,11 +7,11 @@ import ( "strconv" "strings" - auth_driver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + auth_driver "github.com/eolinker/apipark/module/application-authorization/auth-driver" "github.com/eolinker/go-common/utils" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) const ( @@ -93,9 +93,9 @@ func (cfg *Config) Valid() ([]byte, error) { return json.Marshal(cfg) } -func (cfg *Config) Detail() []project_authorization_dto.DetailItem { +func (cfg *Config) Detail() []application_authorization_dto.DetailItem { - items := []project_authorization_dto.DetailItem{ + items := []application_authorization_dto.DetailItem{ {Key: "Iss", Value: cfg.Iss}, {Key: "签名算法", Value: cfg.Algorithm}, {Key: "用户名", Value: cfg.User}, @@ -105,14 +105,14 @@ func (cfg *Config) Detail() []project_authorization_dto.DetailItem { switch cfg.Algorithm { case "HS256", "HS384", "HS512": - items = append(items, project_authorization_dto.DetailItem{Key: "Secret", Value: cfg.Secret}) + items = append(items, application_authorization_dto.DetailItem{Key: "Secret", Value: cfg.Secret}) base64 := "false" if cfg.SignatureIsBase64 { base64 = "true" } - items = append(items, project_authorization_dto.DetailItem{Key: "Secret", Value: base64}) + items = append(items, application_authorization_dto.DetailItem{Key: "Secret", Value: base64}) default: - items = append(items, project_authorization_dto.DetailItem{Key: "RSA公钥", Value: cfg.PublicKey}) + items = append(items, application_authorization_dto.DetailItem{Key: "RSA公钥", Value: cfg.PublicKey}) } return items diff --git a/module/project-authorization/auth-driver/manager.go b/module/application-authorization/auth-driver/manager.go similarity index 100% rename from module/project-authorization/auth-driver/manager.go rename to module/application-authorization/auth-driver/manager.go diff --git a/module/project-authorization/auth-driver/oauth2/hash.go b/module/application-authorization/auth-driver/oauth2/hash.go similarity index 100% rename from module/project-authorization/auth-driver/oauth2/hash.go rename to module/application-authorization/auth-driver/oauth2/hash.go diff --git a/module/project-authorization/auth-driver/oauth2/oauth2.go b/module/application-authorization/auth-driver/oauth2/oauth2.go similarity index 81% rename from module/project-authorization/auth-driver/oauth2/oauth2.go rename to module/application-authorization/auth-driver/oauth2/oauth2.go index 2345361..065e0f5 100644 --- a/module/project-authorization/auth-driver/oauth2/oauth2.go +++ b/module/application-authorization/auth-driver/oauth2/oauth2.go @@ -4,9 +4,9 @@ import ( "encoding/json" "strconv" - auth_driver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + auth_driver "github.com/eolinker/apipark/module/application-authorization/auth-driver" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) const ( @@ -47,11 +47,11 @@ func (cfg *Config) Valid() ([]byte, error) { return json.Marshal(cfg) } -func (cfg *Config) Detail() []project_authorization_dto.DetailItem { +func (cfg *Config) Detail() []application_authorization_dto.DetailItem { redirectURLs, _ := json.Marshal(cfg.RedirectUrls) - return []project_authorization_dto.DetailItem{ + return []application_authorization_dto.DetailItem{ {Key: "客户端ID", Value: cfg.ClientId}, {Key: "客户端密钥", Value: cfg.ClientSecret}, {Key: "客户端类型", Value: cfg.ClientType}, diff --git a/module/application-authorization/authorization.go b/module/application-authorization/authorization.go new file mode 100644 index 0000000..313736f --- /dev/null +++ b/module/application-authorization/authorization.go @@ -0,0 +1,41 @@ +package application_authorization + +import ( + "context" + "reflect" + + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" + + "github.com/eolinker/apipark/gateway" + + "github.com/eolinker/go-common/autowire" + + _ "github.com/eolinker/apipark/module/application-authorization/auth-driver/aksk" + _ "github.com/eolinker/apipark/module/application-authorization/auth-driver/apikey" + _ "github.com/eolinker/apipark/module/application-authorization/auth-driver/basic" + _ "github.com/eolinker/apipark/module/application-authorization/auth-driver/jwt" + _ "github.com/eolinker/apipark/module/application-authorization/auth-driver/oauth2" +) + +type IAuthorizationModule interface { + // AddAuthorization 添加项目鉴权信息 + AddAuthorization(ctx context.Context, appId string, info *application_authorization_dto.CreateAuthorization) (*application_authorization_dto.Authorization, error) + // EditAuthorization 修改项目鉴权信息 + EditAuthorization(ctx context.Context, appId string, aid string, info *application_authorization_dto.EditAuthorization) (*application_authorization_dto.Authorization, error) + // DeleteAuthorization 删除项目鉴权 + DeleteAuthorization(ctx context.Context, appId string, aid string) error + // Authorizations 获取项目鉴权列表 + Authorizations(ctx context.Context, appId string) ([]*application_authorization_dto.AuthorizationItem, error) + // Detail 获取项目鉴权详情(弹窗用) + Detail(ctx context.Context, appId string, aid string) ([]application_authorization_dto.DetailItem, error) + // Info 获取项目鉴权详情 + Info(ctx context.Context, appId string, aid string) (*application_authorization_dto.Authorization, error) +} + +func init() { + autowire.Auto[IAuthorizationModule](func() reflect.Value { + m := new(imlAuthorizationModule) + gateway.RegisterInitHandleFunc(m.initGateway) + return reflect.ValueOf(m) + }) +} diff --git a/module/project-authorization/dto/input.go b/module/application-authorization/dto/input.go similarity index 95% rename from module/project-authorization/dto/input.go rename to module/application-authorization/dto/input.go index 9464dd1..a325335 100644 --- a/module/project-authorization/dto/input.go +++ b/module/application-authorization/dto/input.go @@ -1,4 +1,4 @@ -package project_authorization_dto +package application_authorization_dto type CreateAuthorization struct { UUID string `json:"uuid"` diff --git a/module/project-authorization/dto/output.go b/module/application-authorization/dto/output.go similarity index 96% rename from module/project-authorization/dto/output.go rename to module/application-authorization/dto/output.go index 4f6d042..505b31b 100644 --- a/module/project-authorization/dto/output.go +++ b/module/application-authorization/dto/output.go @@ -1,4 +1,4 @@ -package project_authorization_dto +package application_authorization_dto import "github.com/eolinker/go-common/auto" diff --git a/module/project-authorization/iml.go b/module/application-authorization/iml.go similarity index 51% rename from module/project-authorization/iml.go rename to module/application-authorization/iml.go index 79718a5..4ce5ad3 100644 --- a/module/project-authorization/iml.go +++ b/module/application-authorization/iml.go @@ -1,4 +1,4 @@ -package project_authorization +package application_authorization import ( "context" @@ -7,15 +7,18 @@ import ( "fmt" "time" + application_authorization "github.com/eolinker/apipark/service/application-authorization" + "github.com/eolinker/eosc/log" - authDriver "github.com/eolinker/apipark/module/project-authorization/auth-driver" + authDriver "github.com/eolinker/apipark/module/application-authorization/auth-driver" "github.com/eolinker/go-common/utils" "github.com/eolinker/apipark/gateway" "github.com/eolinker/apipark/service/cluster" + "github.com/eolinker/apipark/service/service" "github.com/eolinker/go-common/auto" @@ -23,47 +26,44 @@ import ( "github.com/eolinker/go-common/store" - "github.com/eolinker/apipark/service/project" - projectAuthorization "github.com/eolinker/apipark/service/project-authorization" - - projectAuthorizationDto "github.com/eolinker/apipark/module/project-authorization/dto" + application_authorization_dto "github.com/eolinker/apipark/module/application-authorization/dto" ) -var _ IProjectAuthorizationModule = (*imlProjectAuthorizationModule)(nil) +var _ IAuthorizationModule = (*imlAuthorizationModule)(nil) -type imlProjectAuthorizationModule struct { - projectService project.IProjectService `autowired:""` - projectAuthorizationService projectAuthorization.IProjectAuthorizationService `autowired:""` - clusterService cluster.IClusterService `autowired:""` - transaction store.ITransaction `autowired:""` +type imlAuthorizationModule struct { + serviceService service.IServiceService `autowired:""` + authorizationService application_authorization.IAuthorizationService `autowired:""` + clusterService cluster.IClusterService `autowired:""` + transaction store.ITransaction `autowired:""` } -func (i *imlProjectAuthorizationModule) getApplications(ctx context.Context, projectIds []string, projectMap map[string]*project.Project) ([]*gateway.ApplicationRelease, error) { - authorizations, err := i.projectAuthorizationService.ListByProject(ctx, projectIds...) +func (i *imlAuthorizationModule) getApplications(ctx context.Context, appIds []string, appMap map[string]*service.Service) ([]*gateway.ApplicationRelease, error) { + authorizations, err := i.authorizationService.ListByApp(ctx, appIds...) if err != nil { return nil, err } - authMap := utils.SliceToMapArray(authorizations, func(a *projectAuthorization.Authorization) string { - return a.Project + authMap := utils.SliceToMapArray(authorizations, func(a *application_authorization.Authorization) string { + return a.Application }) - return utils.SliceToSlice(projectIds, func(projectId string) *gateway.ApplicationRelease { - auths := authMap[projectId] + return utils.SliceToSlice(appIds, func(id string) *gateway.ApplicationRelease { + auths := authMap[id] description := "" - projectInfo, ok := projectMap[projectId] + info, ok := appMap[id] if ok { - description = projectInfo.Description + description = info.Description } return &gateway.ApplicationRelease{ BasicItem: &gateway.BasicItem{ - ID: projectId, + ID: id, Description: description, Version: time.Now().Format("20060102150405"), MatchLabels: map[string]string{ - "project": projectId, + "service": id, }, }, - Authorizations: utils.SliceToSlice(auths, func(a *projectAuthorization.Authorization) *gateway.Authorization { + Authorizations: utils.SliceToSlice(auths, func(a *application_authorization.Authorization) *gateway.Authorization { authCfg := make(map[string]interface{}) _ = json.Unmarshal([]byte(a.Config), &authCfg) return &gateway.Authorization{ @@ -79,45 +79,45 @@ func (i *imlProjectAuthorizationModule) getApplications(ctx context.Context, pro }), nil } -func (i *imlProjectAuthorizationModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projects, err := i.projectService.List(ctx) +func (i *imlAuthorizationModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { + services, err := i.serviceService.List(ctx) if err != nil { return err } - projectIds := make([]string, 0, len(projects)) - projectMap := make(map[string]*project.Project) - for _, p := range projects { - projectIds = append(projectIds, p.Id) - projectMap[p.Id] = p + serviceIds := make([]string, 0, len(services)) + serviceMap := make(map[string]*service.Service) + for _, p := range services { + serviceIds = append(serviceIds, p.Id) + serviceMap[p.Id] = p } - applications, err := i.getApplications(ctx, projectIds, projectMap) + applications, err := i.getApplications(ctx, serviceIds, serviceMap) if err != nil { return err } return clientDriver.Application().Online(ctx, applications...) } -func (i *imlProjectAuthorizationModule) online(ctx context.Context, projectInfo *project.Project) error { +func (i *imlAuthorizationModule) online(ctx context.Context, s *service.Service) error { clusters, err := i.clusterService.List(ctx) if err != nil { return err } - authorizations, err := i.projectAuthorizationService.ListByProject(ctx, projectInfo.Id) + authorizations, err := i.authorizationService.ListByApp(ctx, s.Id) if err != nil { return err } app := &gateway.ApplicationRelease{ BasicItem: &gateway.BasicItem{ - ID: projectInfo.Id, - Description: projectInfo.Description, + ID: s.Id, + Description: s.Description, Version: time.Now().Format("20060102150405"), MatchLabels: map[string]string{ - "project": projectInfo.Id, + "service": s.Id, }, }, - Authorizations: utils.SliceToSlice(authorizations, func(a *projectAuthorization.Authorization) *gateway.Authorization { + Authorizations: utils.SliceToSlice(authorizations, func(a *application_authorization.Authorization) *gateway.Authorization { authCfg := make(map[string]interface{}) _ = json.Unmarshal([]byte(a.Config), &authCfg) return &gateway.Authorization{ @@ -134,12 +134,12 @@ func (i *imlProjectAuthorizationModule) online(ctx context.Context, projectInfo for _, c := range clusters { err := i.doOnline(ctx, c.Uuid, app) if err != nil { - log.Warnf("project authorization online for cluster[%s] %v", c.Name, err) + log.Warnf("service authorization online for cluster[%s] %v", c.Name, err) } } return nil } -func (i *imlProjectAuthorizationModule) doOnline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error { +func (i *imlAuthorizationModule) doOnline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error { client, err := i.clusterService.GatewayClient(ctx, clusterId) if err != nil { return err @@ -150,7 +150,7 @@ func (i *imlProjectAuthorizationModule) doOnline(ctx context.Context, clusterId return client.Application().Online(ctx, app) } -func (i *imlProjectAuthorizationModule) AddAuthorization(ctx context.Context, pid string, info *projectAuthorizationDto.CreateAuthorization) (*projectAuthorizationDto.Authorization, error) { +func (i *imlAuthorizationModule) AddAuthorization(ctx context.Context, appId string, info *application_authorization_dto.CreateAuthorization) (*application_authorization_dto.Authorization, error) { authFactory, has := authDriver.GetAuthFactory(info.Driver) if !has { return nil, fmt.Errorf("unknown driver %s", info.Driver) @@ -164,7 +164,7 @@ func (i *imlProjectAuthorizationModule) AddAuthorization(ctx context.Context, pi return nil, err } - projectInfo, err := i.projectService.Get(ctx, pid) + s, err := i.serviceService.Get(ctx, appId) if err != nil { return nil, err } @@ -174,11 +174,10 @@ func (i *imlProjectAuthorizationModule) AddAuthorization(ctx context.Context, pi } // 缺少配置查重操作 - //cfg, _ := json.Marshal(info.Config) err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.projectAuthorizationService.Create(ctx, &projectAuthorization.CreateAuthorization{ + err = i.authorizationService.Create(ctx, &application_authorization.Create{ UUID: info.UUID, - Project: pid, + Application: appId, Name: info.Name, Type: info.Driver, Position: info.Position, @@ -192,17 +191,17 @@ func (i *imlProjectAuthorizationModule) AddAuthorization(ctx context.Context, pi return err } - return i.online(ctx, projectInfo) + return i.online(ctx, s) }) if err != nil { return nil, err } - return i.Info(ctx, pid, info.UUID) + return i.Info(ctx, appId, info.UUID) } -func (i *imlProjectAuthorizationModule) EditAuthorization(ctx context.Context, pid string, aid string, info *projectAuthorizationDto.EditAuthorization) (*projectAuthorizationDto.Authorization, error) { - authInfo, err := i.projectAuthorizationService.Get(ctx, aid) +func (i *imlAuthorizationModule) EditAuthorization(ctx context.Context, appId string, aid string, info *application_authorization_dto.EditAuthorization) (*application_authorization_dto.Authorization, error) { + authInfo, err := i.authorizationService.Get(ctx, aid) if err != nil { return nil, err } @@ -219,7 +218,7 @@ func (i *imlProjectAuthorizationModule) EditAuthorization(ctx context.Context, p return nil, err } - projectInfo, err := i.projectService.Get(ctx, pid) + appInfo, err := i.serviceService.Get(ctx, appId) if err != nil { return nil, err } @@ -227,7 +226,7 @@ func (i *imlProjectAuthorizationModule) EditAuthorization(ctx context.Context, p err = i.transaction.Transaction(ctx, func(ctx context.Context) error { authId := auth.GenerateID(authInfo.Position, authInfo.TokenName) cfgStr := string(cfg) - err = i.projectAuthorizationService.Save(ctx, aid, &projectAuthorization.EditAuthorization{ + err = i.authorizationService.Save(ctx, aid, &application_authorization.Edit{ Name: info.Name, Position: info.Position, TokenName: info.TokenName, @@ -239,23 +238,23 @@ func (i *imlProjectAuthorizationModule) EditAuthorization(ctx context.Context, p if err != nil { return err } - return i.online(ctx, projectInfo) + return i.online(ctx, appInfo) }) if err != nil { return nil, err } - return i.Info(ctx, pid, aid) + return i.Info(ctx, appId, aid) } -func (i *imlProjectAuthorizationModule) DeleteAuthorization(ctx context.Context, pid string, aid string) error { - _, err := i.projectService.Get(ctx, pid) +func (i *imlAuthorizationModule) DeleteAuthorization(ctx context.Context, pid string, aid string) error { + _, err := i.serviceService.Get(ctx, pid) if err != nil { return err } return i.transaction.Transaction(ctx, func(ctx context.Context) error { - err = i.projectAuthorizationService.Delete(ctx, aid) + err = i.authorizationService.Delete(ctx, aid) if err != nil { return err } @@ -271,13 +270,13 @@ func (i *imlProjectAuthorizationModule) DeleteAuthorization(ctx context.Context, for _, c := range clusters { err := i.doOffline(ctx, c.Uuid, app) if err != nil { - log.Warnf("project authorization offline for cluster[%s] %v", c.Name, err) + log.Warnf("service authorization offline for cluster[%s] %v", c.Name, err) } } return nil }) } -func (i *imlProjectAuthorizationModule) doOffline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error { +func (i *imlAuthorizationModule) doOffline(ctx context.Context, clusterId string, app *gateway.ApplicationRelease) error { client, err := i.clusterService.GatewayClient(ctx, clusterId) if err != nil { return err @@ -288,18 +287,18 @@ func (i *imlProjectAuthorizationModule) doOffline(ctx context.Context, clusterId return client.Application().Offline(ctx, app) } -func (i *imlProjectAuthorizationModule) Authorizations(ctx context.Context, pid string) ([]*projectAuthorizationDto.AuthorizationItem, error) { - _, err := i.projectService.Get(ctx, pid) +func (i *imlAuthorizationModule) Authorizations(ctx context.Context, pid string) ([]*application_authorization_dto.AuthorizationItem, error) { + _, err := i.serviceService.Get(ctx, pid) if err != nil { return nil, err } - authorizations, err := i.projectAuthorizationService.ListByProject(ctx, pid) + authorizations, err := i.authorizationService.ListByApp(ctx, pid) if err != nil { return nil, err } - result := make([]*projectAuthorizationDto.AuthorizationItem, 0, len(authorizations)) + result := make([]*application_authorization_dto.AuthorizationItem, 0, len(authorizations)) for _, a := range authorizations { - result = append(result, &projectAuthorizationDto.AuthorizationItem{ + result = append(result, &application_authorization_dto.AuthorizationItem{ Id: a.UUID, Name: a.Name, Driver: a.Type, @@ -316,12 +315,12 @@ func (i *imlProjectAuthorizationModule) Authorizations(ctx context.Context, pid return result, nil } -func (i *imlProjectAuthorizationModule) Detail(ctx context.Context, pid string, aid string) ([]projectAuthorizationDto.DetailItem, error) { - _, err := i.projectService.Get(ctx, pid) +func (i *imlAuthorizationModule) Detail(ctx context.Context, pid string, aid string) ([]application_authorization_dto.DetailItem, error) { + _, err := i.serviceService.Get(ctx, pid) if err != nil { return nil, err } - authInfo, err := i.projectAuthorizationService.Get(ctx, aid) + authInfo, err := i.authorizationService.Get(ctx, aid) if err != nil { return nil, err } @@ -334,32 +333,32 @@ func (i *imlProjectAuthorizationModule) Detail(ctx context.Context, pid string, return nil, err } cfgItems := auth.AuthConfig().Detail() - details := make([]projectAuthorizationDto.DetailItem, 0, 6+len(cfgItems)) - details = append(details, projectAuthorizationDto.DetailItem{Key: "名称", Value: authInfo.Name}) - details = append(details, projectAuthorizationDto.DetailItem{Key: "鉴权类型", Value: authInfo.Type}) - details = append(details, projectAuthorizationDto.DetailItem{Key: "参数位置", Value: authInfo.Position}) - details = append(details, projectAuthorizationDto.DetailItem{Key: "参数名", Value: authInfo.TokenName}) + details := make([]application_authorization_dto.DetailItem, 0, 6+len(cfgItems)) + details = append(details, application_authorization_dto.DetailItem{Key: "名称", Value: authInfo.Name}) + details = append(details, application_authorization_dto.DetailItem{Key: "鉴权类型", Value: authInfo.Type}) + details = append(details, application_authorization_dto.DetailItem{Key: "参数位置", Value: authInfo.Position}) + details = append(details, application_authorization_dto.DetailItem{Key: "参数名", Value: authInfo.TokenName}) details = append(details, cfgItems...) dateStr := "永久" if authInfo.ExpireTime != 0 { dateStr = time.Unix(authInfo.ExpireTime, 0).Format("2006-01-02") } - details = append(details, projectAuthorizationDto.DetailItem{Key: "过期日期", Value: dateStr}) + details = append(details, application_authorization_dto.DetailItem{Key: "过期日期", Value: dateStr}) hideAuthStr := "是" if !authInfo.HideCredential { hideAuthStr = "否" } - details = append(details, projectAuthorizationDto.DetailItem{Key: "隐藏鉴权信息", Value: hideAuthStr}) + details = append(details, application_authorization_dto.DetailItem{Key: "隐藏鉴权信息", Value: hideAuthStr}) return details, nil } -func (i *imlProjectAuthorizationModule) Info(ctx context.Context, pid string, aid string) (*projectAuthorizationDto.Authorization, error) { - _, err := i.projectService.Get(ctx, pid) +func (i *imlAuthorizationModule) Info(ctx context.Context, pid string, aid string) (*application_authorization_dto.Authorization, error) { + _, err := i.serviceService.Get(ctx, pid) if err != nil { return nil, err } - auth, err := i.projectAuthorizationService.Get(ctx, aid) + auth, err := i.authorizationService.Get(ctx, aid) if err != nil { return nil, err } @@ -368,7 +367,7 @@ func (i *imlProjectAuthorizationModule) Info(ctx context.Context, pid string, ai _ = json.Unmarshal([]byte(auth.Config), &cfg) } - return &projectAuthorizationDto.Authorization{ + return &application_authorization_dto.Authorization{ UUID: auth.UUID, Name: auth.Name, Driver: auth.Type, diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index 0e5280f..d991b03 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -29,7 +29,7 @@ type ServiceDetail struct { } type ServiceBasic struct { - Project auto.Label `json:"project" aolabel:"project"` + //Service auto.Label `json:"service" aolabel:"service"` Team auto.Label `json:"team" aolabel:"team"` ApiNum int `json:"api_num"` SubscriberNum int `json:"subscriber_num"` diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index 3854052..7320ae0 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -2,13 +2,13 @@ package catalogue import ( "context" - "encoding/json" "errors" "fmt" "math" - "sort" - "github.com/eolinker/apipark/service/project" + service_doc "github.com/eolinker/apipark/service/service-doc" + + service_tag "github.com/eolinker/apipark/service/service-tag" "github.com/eolinker/apipark/service/subscribe" @@ -40,19 +40,17 @@ var ( ) type imlCatalogueModule struct { - catalogueService catalogue.ICatalogueService `autowired:""` - projectService project.IProjectService `autowired:""` - apiService api.IAPIService `autowired:""` - serviceService service.IServiceService `autowired:""` - serviceApiService service.IApiService `autowired:""` - serviceTagService service.ITagService `autowired:""` - servicePartitionService service.IPartitionsService `autowired:""` - serviceDocService service.IDocService `autowired:""` - tagService tag.ITagService `autowired:""` - releaseService release.IReleaseService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - transaction store.ITransaction `autowired:""` + catalogueService catalogue.ICatalogueService `autowired:""` + projectService service.IServiceService `autowired:""` + apiService api.IAPIService `autowired:""` + serviceService service.IServiceService `autowired:""` + serviceTagService service_tag.ITagService `autowired:""` + serviceDocService service_doc.IDocService `autowired:""` + tagService tag.ITagService `autowired:""` + releaseService release.IReleaseService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` + transaction store.ITransaction `autowired:""` root *Root } @@ -73,7 +71,7 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal projects := make([]string, 0, len(subscribeInfo.Applications)) for _, pid := range subscribeInfo.Applications { - if pid == s.Project { + if pid == s.Id { // 不能订阅自己 continue } @@ -91,7 +89,6 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal err = i.subscribeApplyService.Create(ctx, &subscribe.CreateApply{ Uuid: applyID, Service: subscribeInfo.Service, - Project: s.Project, Team: s.Team, Application: pid, ApplyTeam: pInfo.Team, @@ -111,7 +108,6 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ Uuid: uuid.New().String(), Service: subscribeInfo.Service, - Project: s.Project, Application: pid, ApplyStatus: subscribe.ApplyStatusReview, From: subscribe.FromSubscribe, @@ -129,7 +125,6 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ Uuid: uuid.New().String(), Service: subscribeInfo.Service, - Project: s.Project, Application: pid, ApplyStatus: subscribe.ApplyStatusReview, From: subscribe.FromSubscribe, @@ -172,7 +167,7 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca docStr = doc.Doc } - r, err := i.releaseService.GetRunning(ctx, s.Project) + r, err := i.releaseService.GetRunning(ctx, s.Id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return &catalogue_dto.ServiceDetail{ @@ -180,9 +175,9 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Description: s.Description, Document: docStr, Basic: &catalogue_dto.ServiceBasic{ - Project: auto.UUID(s.Project), - Team: auto.UUID(s.Team), - ApiNum: 0, + //Service: auto.UUID(s.Id), + Team: auto.UUID(s.Team), + ApiNum: 0, }, }, nil } @@ -197,77 +192,79 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca apiMap := utils.SliceToMap(docCommits, func(t *release.APIDocumentCommit) string { return t.API }) - - apiList, err := i.serviceApiService.List(ctx, sid) - if err != nil { - return nil, err - } - apis := make([]*catalogue_dto.ServiceApi, 0, len(apiList)) - disableApis := make([]*catalogue_dto.ServiceApiBasic, 0, len(apiList)) - for _, a := range apiList { - - apiInfo, err := i.apiService.GetInfo(ctx, a.Aid) - if err != nil { - return nil, err - } - basicApi := &catalogue_dto.ServiceApiBasic{ - Id: apiInfo.UUID, - Name: apiInfo.Name, - Description: apiInfo.Description, - Method: apiInfo.Method, - Path: apiInfo.Path, - Creator: auto.UUID(apiInfo.Creator), - Updater: auto.UUID(apiInfo.Updater), - CreateTime: auto.TimeLabel(apiInfo.CreateAt), - UpdateTime: auto.TimeLabel(apiInfo.UpdateAt), - } - v, ok := apiMap[a.Aid] - if !ok { - disableApis = append(disableApis, basicApi) - continue - } - commit, err := i.apiService.GetDocumentCommit(ctx, v.Commit) - if err != nil { - return nil, err - } - tmp := make(map[string]interface{}) - if commit.Data != nil { - err = json.Unmarshal([]byte(commit.Data.Content), &tmp) - if err != nil { - return nil, err - } - } - - apis = append(apis, &catalogue_dto.ServiceApi{ - ServiceApiBasic: basicApi, - Doc: tmp, - }) - } - subscribers, err := i.subscribeService.ListByServices(ctx, sid) - if err != nil { - return nil, err - } - subscribeCount := map[string]int{} - tmp := map[string]struct{}{} - for _, s := range subscribers { - key := fmt.Sprintf("%s-%s", s.Service, s.Application) - if _, ok := tmp[key]; !ok { - tmp[key] = struct{}{} - subscribeCount[s.Service]++ - } - } - return &catalogue_dto.ServiceDetail{ - Name: s.Name, - Description: s.Description, - Document: docStr, - Basic: &catalogue_dto.ServiceBasic{ - Project: auto.UUID(s.Project), - Team: auto.UUID(s.Team), - ApiNum: len(apis), - SubscriberNum: subscribeCount[s.Id], - }, - Apis: apis, - }, nil + fmt.Println("apiMap", apiMap) + + //apiList, err := i.serviceApiService.List(ctx, sid) + //if err != nil { + // return nil, err + //} + //apis := make([]*catalogue_dto.ServiceApi, 0, len(apiList)) + //disableApis := make([]*catalogue_dto.ServiceApiBasic, 0, len(apiList)) + //for _, a := range apiList { + // + // apiInfo, err := i.apiService.GetInfo(ctx, a.Aid) + // if err != nil { + // return nil, err + // } + // basicApi := &catalogue_dto.ServiceApiBasic{ + // Id: apiInfo.UUID, + // Name: apiInfo.Name, + // Description: apiInfo.Description, + // Method: apiInfo.Method, + // Path: apiInfo.Path, + // Creator: auto.UUID(apiInfo.Creator), + // Updater: auto.UUID(apiInfo.Updater), + // CreateTime: auto.TimeLabel(apiInfo.CreateAt), + // UpdateTime: auto.TimeLabel(apiInfo.UpdateAt), + // } + // v, ok := apiMap[a.Aid] + // if !ok { + // disableApis = append(disableApis, basicApi) + // continue + // } + // commit, err := i.apiService.GetDocumentCommit(ctx, v.Commit) + // if err != nil { + // return nil, err + // } + // tmp := make(map[string]interface{}) + // if commit.Data != nil { + // err = json.Unmarshal([]byte(commit.Data.Content), &tmp) + // if err != nil { + // return nil, err + // } + // } + // + // apis = append(apis, &catalogue_dto.ServiceApi{ + // ServiceApiBasic: basicApi, + // Doc: tmp, + // }) + //} + //subscribers, err := i.subscribeService.ListByServices(ctx, sid) + //if err != nil { + // return nil, err + //} + //subscribeCount := map[string]int{} + //tmp := map[string]struct{}{} + //for _, s := range subscribers { + // key := fmt.Sprintf("%s-%s", s.Service, s.Application) + // if _, ok := tmp[key]; !ok { + // tmp[key] = struct{}{} + // subscribeCount[s.Service]++ + // } + //} + //return &catalogue_dto.ServiceDetail{ + // Name: s.Name, + // Description: s.Description, + // Document: docStr, + // Basic: &catalogue_dto.ServiceBasic{ + // //Service: auto.UUID(s.Project), + // Team: auto.UUID(s.Team), + // ApiNum: len(apis), + // SubscriberNum: subscribeCount[s.Id], + // }, + // Apis: apis, + //}, nil + return nil, nil } func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*catalogue_dto.ServiceItem, error) { @@ -276,7 +273,7 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c if err != nil { return nil, err } - serviceTagMap := utils.SliceToMapArrayO(serviceTags, func(t *service.Tag) (string, string) { + serviceTagMap := utils.SliceToMapArrayO(serviceTags, func(t *service_tag.Tag) (string, string) { return t.Sid, t.Tid }) @@ -284,58 +281,60 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c if err != nil { return nil, err } - serviceApiCountMap, err := i.serviceApiService.CountBySids(ctx) - if err != nil { - return nil, err - } - subscribers, err := i.subscribeService.ListByServices(ctx) - if err != nil { - return nil, err - } - subscribeCount := map[string]int64{} - tmp := map[string]struct{}{} - for _, s := range subscribers { - if s.ApplyStatus != subscribe.ApplyStatusSubscribe { - continue - } - key := fmt.Sprintf("%s-%s", s.Service, s.Application) - if _, ok := tmp[key]; !ok { - tmp[key] = struct{}{} - subscribeCount[s.Service]++ - } - } - result := make([]*catalogue_dto.ServiceItem, 0, len(items)) - for _, v := range items { - apiNum, ok := serviceApiCountMap[v.Id] - if !ok || apiNum < 1 { - continue - } - //ps := utils.Intersection(servicePartitionMap[v.Id], projectPartitionMap[v.Project]) - //if len(ps) < 1 { - // continue - //} - result = append(result, &catalogue_dto.ServiceItem{ - Id: v.Id, - Name: v.Name, - Tags: auto.List(serviceTagMap[v.Id]), - Catalogue: auto.UUID(v.Catalogue), - //Cluster: auto.List(ps), - ApiNum: apiNum, - SubscriberNum: subscribeCount[v.Id], - Description: v.Description, - Logo: v.Logo, - }) - } - sort.Slice(result, func(i, j int) bool { - if result[i].SubscriberNum != result[j].SubscriberNum { - return result[i].SubscriberNum > result[j].SubscriberNum - } - if result[i].ApiNum != result[j].ApiNum { - return result[i].ApiNum > result[j].ApiNum - } - return result[i].Name < result[j].Name - }) - return result, nil + fmt.Println("items", items, serviceTagMap) + //serviceApiCountMap, err := i.serviceApiService.CountBySids(ctx) + //if err != nil { + // return nil, err + //} + //subscribers, err := i.subscribeService.ListByServices(ctx) + //if err != nil { + // return nil, err + //} + //subscribeCount := map[string]int64{} + //tmp := map[string]struct{}{} + //for _, s := range subscribers { + // if s.ApplyStatus != subscribe.ApplyStatusSubscribe { + // continue + // } + // key := fmt.Sprintf("%s-%s", s.Service, s.Application) + // if _, ok := tmp[key]; !ok { + // tmp[key] = struct{}{} + // subscribeCount[s.Service]++ + // } + //} + //result := make([]*catalogue_dto.ServiceItem, 0, len(items)) + //for _, v := range items { + // apiNum, ok := serviceApiCountMap[v.Id] + // if !ok || apiNum < 1 { + // continue + // } + // //ps := utils.Intersection(servicePartitionMap[v.Id], projectPartitionMap[v.Service]) + // //if len(ps) < 1 { + // // continue + // //} + // result = append(result, &catalogue_dto.ServiceItem{ + // Id: v.Id, + // Name: v.Name, + // Tags: auto.List(serviceTagMap[v.Id]), + // Catalogue: auto.UUID(v.Catalogue), + // //Cluster: auto.List(ps), + // ApiNum: apiNum, + // SubscriberNum: subscribeCount[v.Id], + // Description: v.Description, + // Logo: v.Logo, + // }) + //} + //sort.Slice(result, func(i, j int) bool { + // if result[i].SubscriberNum != result[j].SubscriberNum { + // return result[i].SubscriberNum > result[j].SubscriberNum + // } + // if result[i].ApiNum != result[j].ApiNum { + // return result[i].ApiNum > result[j].ApiNum + // } + // return result[i].Name < result[j].Name + //}) + //return result, nil + return nil, nil } func (i *imlCatalogueModule) recurseUpdateSort(ctx context.Context, parent string, sorts []*catalogue_dto.SortItem) error { diff --git a/module/my-team/dto/output.go b/module/my-team/dto/output.go index ca3c35d..2b7a56a 100644 --- a/module/my-team/dto/output.go +++ b/module/my-team/dto/output.go @@ -12,19 +12,21 @@ type Item struct { Description string `json:"description"` CreateTime auto.TimeLabel `json:"create_time"` UpdateTime auto.TimeLabel `json:"update_time"` - ProjectNum int64 `json:"system_num"` + ServiceNum int64 `json:"service_num"` + AppNum int64 `json:"app_num"` CanDelete bool `json:"can_delete"` } -func ToItem(model *team.Team, projectNum int64) *Item { +func ToItem(model *team.Team, serviceNum int64, appNum int64) *Item { return &Item{ Id: model.Id, Name: model.Name, Description: model.Description, CreateTime: auto.TimeLabel(model.CreateTime), UpdateTime: auto.TimeLabel(model.UpdateTime), - ProjectNum: projectNum, - CanDelete: projectNum == 0, + ServiceNum: serviceNum, + AppNum: appNum, + CanDelete: serviceNum == 0 && appNum == 0, } } diff --git a/module/my-team/iml.go b/module/my-team/iml.go index cd8030c..5077af3 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -9,8 +9,6 @@ import ( "gorm.io/gorm" - "github.com/eolinker/apipark/service/project" - department_member "github.com/eolinker/ap-account/service/department-member" "github.com/eolinker/go-common/auto" @@ -18,6 +16,7 @@ import ( "github.com/eolinker/go-common/store" + "github.com/eolinker/apipark/service/service" team_member "github.com/eolinker/apipark/service/team-member" team_dto "github.com/eolinker/apipark/module/my-team/dto" @@ -36,7 +35,7 @@ type imlTeamModule struct { roleMemberService role.IRoleMemberService `autowired:""` userService user.IUserService `autowired:""` departmentMemberService department_member.IMemberService `autowired:""` - projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -99,14 +98,18 @@ func (m *imlTeamModule) Search(ctx context.Context, keyword string) ([]*team_dto if err != nil { return nil, err } - projectNumMap, err := m.projectService.CountByTeam(ctx, keyword) + serviceNumMap, err := m.serviceService.ServiceCountByTeam(ctx, keyword) + if err != nil { + return nil, err + } + appNumMap, err := m.serviceService.AppCountByTeam(ctx, keyword) if err != nil { return nil, err } outList := make([]*team_dto.Item, 0, len(list)) for _, v := range list { - outList = append(outList, team_dto.ToItem(v, projectNumMap[v.Id])) + outList = append(outList, team_dto.ToItem(v, serviceNumMap[v.Id], appNumMap[v.Id])) } return outList, nil } @@ -155,7 +158,7 @@ func (m *imlTeamModule) SimpleTeams(ctx context.Context, keyword string) ([]*tea return nil, err } - projects, err := m.projectService.Search(ctx, "", map[string]interface{}{ + projects, err := m.serviceService.Search(ctx, "", map[string]interface{}{ "team": teamIDs, }) projectCount := make(map[string]int64) diff --git a/module/permit/project/iml.go b/module/permit/project/iml.go index ced8642..361cf23 100644 --- a/module/permit/project/iml.go +++ b/module/permit/project/iml.go @@ -12,7 +12,7 @@ import ( permit_identity "github.com/eolinker/apipark/middleware/permit/identity" permit_dto "github.com/eolinker/apipark/module/permit/dto" permit_type "github.com/eolinker/apipark/service/permit-type" - "github.com/eolinker/apipark/service/project" + "github.com/eolinker/apipark/service/service" "github.com/eolinker/apipark/service/team" team_member "github.com/eolinker/apipark/service/team-member" "github.com/eolinker/eosc/log" @@ -45,7 +45,7 @@ var ( ) type imlProjectPermitModule struct { - projectService project.IProjectService `autowired:""` + projectService service.IServiceService `autowired:""` teamProject team.ITeamService `autowired:""` permitService permit.IPermit `autowired:""` //projectMemberService project_member.IMemberService `autowired:""` @@ -140,7 +140,7 @@ func (m *imlProjectPermitModule) IdentifyProject(ctx context.Context, project st return identities, nil } -func (m *imlProjectPermitModule) getIdentity(ctx context.Context, p *project.Project, uid string) ([]string, error) { +func (m *imlProjectPermitModule) getIdentity(ctx context.Context, p *service.Service, uid string) ([]string, error) { members, err := m.projectMemberService.Members(ctx, []string{p.Id}, []string{uid}) if err != nil { log.Info("get project member error", err) diff --git a/module/project-authorization/authorization.go b/module/project-authorization/authorization.go deleted file mode 100644 index f129883..0000000 --- a/module/project-authorization/authorization.go +++ /dev/null @@ -1,40 +0,0 @@ -package project_authorization - -import ( - "context" - "reflect" - - "github.com/eolinker/apipark/gateway" - - "github.com/eolinker/go-common/autowire" - - _ "github.com/eolinker/apipark/module/project-authorization/auth-driver/aksk" - _ "github.com/eolinker/apipark/module/project-authorization/auth-driver/apikey" - _ "github.com/eolinker/apipark/module/project-authorization/auth-driver/basic" - _ "github.com/eolinker/apipark/module/project-authorization/auth-driver/jwt" - _ "github.com/eolinker/apipark/module/project-authorization/auth-driver/oauth2" - project_authorization_dto "github.com/eolinker/apipark/module/project-authorization/dto" -) - -type IProjectAuthorizationModule interface { - // AddAuthorization 添加项目鉴权信息 - AddAuthorization(ctx context.Context, pid string, info *project_authorization_dto.CreateAuthorization) (*project_authorization_dto.Authorization, error) - // EditAuthorization 修改项目鉴权信息 - EditAuthorization(ctx context.Context, pid string, aid string, info *project_authorization_dto.EditAuthorization) (*project_authorization_dto.Authorization, error) - // DeleteAuthorization 删除项目鉴权 - DeleteAuthorization(ctx context.Context, pid string, aid string) error - // Authorizations 获取项目鉴权列表 - Authorizations(ctx context.Context, pid string) ([]*project_authorization_dto.AuthorizationItem, error) - // Detail 获取项目鉴权详情(弹窗用) - Detail(ctx context.Context, pid string, aid string) ([]project_authorization_dto.DetailItem, error) - // Info 获取项目鉴权详情 - Info(ctx context.Context, pid string, aid string) (*project_authorization_dto.Authorization, error) -} - -func init() { - autowire.Auto[IProjectAuthorizationModule](func() reflect.Value { - m := new(imlProjectAuthorizationModule) - gateway.RegisterInitHandleFunc(m.initGateway) - return reflect.ValueOf(m) - }) -} diff --git a/module/project/dto/input.go b/module/project/dto/input.go deleted file mode 100644 index 67738a7..0000000 --- a/module/project/dto/input.go +++ /dev/null @@ -1,41 +0,0 @@ -package project_dto - -type CreateProject struct { - Id string `json:"id"` - Name string `json:"name"` - Prefix string `json:"prefix"` - //Master string `json:"master"` - Partition []string `json:"partition" aocheck:"partition"` - Description string `json:"description"` - AsApp *bool `json:"as_app"` - AsServer *bool `json:"as_server"` -} - -type EditProject struct { - Name *string `json:"name"` - Description *string `json:"description"` - //Master *string `json:"master" aocheck:"user"` -} - -type CreateApp struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` -} - -type UpdateApp struct { - Name *string `json:"name"` - Description *string `json:"description"` -} - -type EditMemberRole struct { - Roles []string `json:"roles"` -} - -type Users struct { - Users []string `json:"users" aocheck:"user"` -} - -type EditProjectMember struct { - Roles []string `json:"roles" aocheck:"role"` -} diff --git a/module/project/dto/output.go b/module/project/dto/output.go deleted file mode 100644 index 4c58336..0000000 --- a/module/project/dto/output.go +++ /dev/null @@ -1,99 +0,0 @@ -package project_dto - -import ( - "github.com/eolinker/apipark/service/project" - "github.com/eolinker/go-common/auto" -) - -type ProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - Team auto.Label `json:"team" aolabel:"team"` - ApiNum int64 `json:"api_num"` - Description string `json:"description"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - CanDelete bool `json:"can_delete"` -} - -type AppItem struct { - Id string `json:"id"` - Name string `json:"name"` - Team auto.Label `json:"team" aolabel:"team"` - SubscribeNum int64 `json:"subscribe_num"` - SubscribeVerifyNum int64 `json:"subscribe_verify_num"` - Description string `json:"description"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - CanDelete bool `json:"can_delete"` -} - -type SimpleProjectItem struct { - Id string `json:"id"` - Name string `json:"name"` - Team auto.Label `json:"team" aolabel:"team"` - Description string `json:"description"` -} - -type SimpleAppItem struct { - Id string `json:"id"` - Name string `json:"name"` - Team auto.Label `json:"team" aolabel:"team"` - Description string `json:"description"` -} - -type Project struct { - Id string `json:"id"` - Name string `json:"name"` - Prefix string `json:"prefix,omitempty"` - Description string `json:"description"` - Team auto.Label `json:"team" aolabel:"team"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - AsServer bool `json:"as_server"` - AsApp bool `json:"as_app"` -} - -type App struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Team auto.Label `json:"team" aolabel:"team"` - CreateTime auto.TimeLabel `json:"create_time"` - UpdateTime auto.TimeLabel `json:"update_time"` - AsApp bool `json:"as_app"` -} - -func ToProject(model *project.Project) *Project { - return &Project{ - Id: model.Id, - Name: model.Name, - Prefix: model.Prefix, - Description: model.Description, - Team: auto.UUID(model.Team), - //Master: auto.UUID(model.Master), - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - AsServer: model.AsServer, - AsApp: model.AsApp, - } -} - -type MemberItem struct { - User auto.Label `json:"user" aolabel:"user"` - Email string `json:"email"` - Roles []auto.Label `json:"roles" aolabel:"role"` - CanDelete bool `json:"can_delete"` -} - -type SimpleMemberItem struct { - Id string `json:"id"` - Name string `json:"name"` -} - -type TeamMemberToAdd struct { - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Email string `json:"email,omitempty"` - Department auto.Label `json:"department" aolabel:"department"` -} diff --git a/module/project/iml.go b/module/project/iml.go deleted file mode 100644 index 42805d5..0000000 --- a/module/project/iml.go +++ /dev/null @@ -1,554 +0,0 @@ -package project - -import ( - "context" - "errors" - "fmt" - "sort" - "strings" - - "github.com/eolinker/apipark/service/tag" - - "github.com/eolinker/apipark/service/service" - - "github.com/eolinker/apipark/service/subscribe" - "gorm.io/gorm" - - "github.com/eolinker/apipark/service/api" - - "github.com/eolinker/go-common/auto" - - team_member "github.com/eolinker/apipark/service/team-member" - - "github.com/eolinker/go-common/store" - - "github.com/google/uuid" - - "github.com/eolinker/go-common/utils" - - "github.com/eolinker/apipark/service/team" - - "github.com/eolinker/apipark/service/project" - - project_dto "github.com/eolinker/apipark/module/project/dto" -) - -var ( - _ IProjectModule = (*imlProjectModule)(nil) -) - -type imlProjectModule struct { - projectService project.IProjectService `autowired:""` - teamService team.ITeamService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - tagService tag.ITagService `autowired:""` - serviceService service.IServiceService `autowired:""` - apiService api.IAPIService `autowired:""` - transaction store.ITransaction `autowired:""` -} - -func (i *imlProjectModule) searchMyProjects(ctx context.Context, teamId string, keyword string) ([]*project.Project, error) { - - userID := utils.UserId(ctx) - condition := make(map[string]interface{}) - condition["as_server"] = true - if teamId != "" { - _, err := i.teamService.Get(ctx, teamId) - if err != nil { - return nil, err - } - condition["team"] = teamId - return i.projectService.Search(ctx, keyword, condition, "update_at desc") - } else { - membersForUser, err := i.teamMemberService.FilterMembersForUser(ctx, userID) - if err != nil { - return nil, err - } - teamIds := membersForUser[userID] - condition["team"] = teamIds - return i.projectService.Search(ctx, keyword, condition, "update_at desc") - } - -} - -func (i *imlProjectModule) SearchMyProjects(ctx context.Context, teamId string, keyword string) ([]*project_dto.ProjectItem, error) { - projects, err := i.searchMyProjects(ctx, teamId, keyword) - if err != nil { - return nil, err - } - projectIDs := utils.SliceToSlice(projects, func(p *project.Project) string { - return p.Id - }) - apiCountMap, err := i.apiService.CountByGroup(ctx, "", map[string]interface{}{"project": projectIDs}, "project") - if err != nil { - return nil, err - } - - items := make([]*project_dto.ProjectItem, 0, len(projects)) - for _, model := range projects { - if teamId != "" && model.Team != teamId { - continue - } - apiCount := apiCountMap[model.Id] - items = append(items, &project_dto.ProjectItem{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - CanDelete: apiCount == 0, - }) - } - return items, nil -} - -func (i *imlProjectModule) SimpleAPPS(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { - w := make(map[string]interface{}) - w["as_app"] = true - projects, err := i.projectService.Search(ctx, keyword, w) - if err != nil { - return nil, err - } - return utils.SliceToSlice(projects, func(p *project.Project) *project_dto.SimpleProjectItem { - return &project_dto.SimpleProjectItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - - Team: auto.UUID(p.Team), - } - }), nil -} - -func (i *imlProjectModule) SimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { - w := make(map[string]interface{}) - w["as_server"] = true - //if partition != "" { - // pp, err := i.projectPartitionService.ListByPartition(ctx, partition) - // if err != nil { - // return nil, err - // } - // w["uuid"] = utils.SliceToSlice(pp, func(p *project.Cluster) string { - // return p.Project - // }) - //} - projects, err := i.projectService.Search(ctx, keyword, w) - if err != nil { - return nil, err - } - - items := make([]*project_dto.SimpleProjectItem, 0, len(projects)) - for _, p := range projects { - - items = append(items, &project_dto.SimpleProjectItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Team: auto.UUID(p.Team), - }) - } - return items, nil -} - -func (i *imlProjectModule) MySimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) { - projects, err := i.searchMyProjects(ctx, "", keyword) - - if err != nil { - return nil, err - } - - items := make([]*project_dto.SimpleProjectItem, 0, len(projects)) - for _, p := range projects { - - items = append(items, &project_dto.SimpleProjectItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Team: auto.UUID(p.Team), - }) - } - return items, nil -} - -func (i *imlProjectModule) GetProject(ctx context.Context, id string) (*project_dto.Project, error) { - projectInfo, err := i.projectService.Get(ctx, id) - if err != nil { - return nil, err - } - - return project_dto.ToProject(projectInfo), nil -} - -func (i *imlProjectModule) Search(ctx context.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) { - var list []*project.Project - var err error - if teamID != "" { - _, err = i.teamService.Get(ctx, teamID) - if err != nil { - return nil, err - } - list, err = i.projectService.Search(ctx, keyword, map[string]interface{}{"team": teamID}, "update_at desc") - } else { - list, err = i.projectService.Search(ctx, keyword, nil, "update_at desc") - } - if err != nil { - return nil, err - } - - projectIds := utils.SliceToSlice(list, func(s *project.Project) string { - return s.Id - }) - - apiCountMap, err := i.apiService.CountByGroup(ctx, "", map[string]interface{}{"project": projectIds}, "project") - if err != nil { - return nil, err - } - serviceCountMap, err := i.serviceService.CountByGroup(ctx, "", map[string]interface{}{"project": projectIds}, "project") - if err != nil { - return nil, err - } - - items := make([]*project_dto.ProjectItem, 0, len(list)) - for _, model := range list { - apiCount := apiCountMap[model.Id] - serviceCount := serviceCountMap[model.Id] - items = append(items, &project_dto.ProjectItem{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - ApiNum: apiCount, - CanDelete: apiCount == 0 && serviceCount == 0, - }) - } - return items, nil -} - -func (i *imlProjectModule) CreateProject(ctx context.Context, teamID string, input *project_dto.CreateProject) (*project_dto.Project, error) { - - if input.Id == "" { - input.Id = uuid.New().String() - } - mo := &project.CreateProject{ - Id: input.Id, - Name: input.Name, - Description: input.Description, - Team: teamID, - Prefix: input.Prefix, - } - if input.AsApp == nil { - // 默认值为false - mo.AsApp = false - } else { - mo.AsApp = *input.AsApp - } - if input.AsServer == nil { - // 默认值为true - mo.AsServer = true - } else { - mo.AsServer = *input.AsServer - } - input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") - err := i.transaction.Transaction(ctx, func(ctx context.Context) error { - return i.projectService.Create(ctx, mo) - }) - if err != nil { - return nil, err - } - return i.GetProject(ctx, input.Id) -} - -func (i *imlProjectModule) EditProject(ctx context.Context, id string, input *project_dto.EditProject) (*project_dto.Project, error) { - _, err := i.projectService.Get(ctx, id) - if err != nil { - return nil, err - } - err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - - return i.projectService.Save(ctx, id, &project.EditProject{ - Name: input.Name, - Description: input.Description, - }) - }) - - if err != nil { - return nil, err - } - return i.GetProject(ctx, id) -} - -func (i *imlProjectModule) DeleteProject(ctx context.Context, id string) error { - - err := i.transaction.Transaction(ctx, func(ctx context.Context) error { - count, err := i.apiService.CountByProject(ctx, id) - if err != nil { - return err - } - if count > 0 { - return fmt.Errorf("project has apis, can not delete") - } - - return i.projectService.Delete(ctx, id) - }) - return err -} - -func (i *imlProjectModule) getTagUuids(ctx context.Context, tags []string) ([]string, error) { - list, err := i.tagService.Search(ctx, "", map[string]interface{}{"name": tags}) - if err != nil { - return nil, err - } - tagMap := make(map[string]string) - for _, t := range list { - tagMap[t.Name] = t.Id - } - tagList := make([]string, 0, len(tags)) - repeatTag := make(map[string]struct{}) - for _, t := range tags { - if _, ok := repeatTag[t]; ok { - continue - } - repeatTag[t] = struct{}{} - v := &tag.CreateTag{ - Name: t, - } - id, ok := tagMap[t] - if !ok { - v.Id = uuid.New().String() - err = i.tagService.Create(ctx, v) - if err != nil { - return nil, err - } - tagMap[t] = v.Id - } else { - v.Id = id - } - tagList = append(tagList, v.Id) - } - return tagList, nil -} - -var _ IAppModule = &imlAppModule{} - -type imlAppModule struct { - teamService team.ITeamService `autowired:""` - projectService project.IProjectService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - transaction store.ITransaction `autowired:""` -} - -func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) { - - if input.Id == "" { - input.Id = uuid.New().String() - } - userId := utils.UserId(ctx) - mo := &project.CreateProject{ - Id: input.Id, - Name: input.Name, - Description: input.Description, - Team: teamID, - AsApp: true, - } - // 判断用户是否在团队内 - members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{userId}) - if err != nil { - return nil, err - } - if len(members) == 0 { - return nil, fmt.Errorf("master is not in team") - } - - err = i.transaction.Transaction(ctx, func(ctx context.Context) error { - - return i.projectService.Create(ctx, mo) - - }) - if err != nil { - return nil, err - } - return i.GetApp(ctx, input.Id) -} - -func (i *imlAppModule) UpdateApp(ctx context.Context, appId string, input *project_dto.UpdateApp) (*project_dto.App, error) { - //userId := utils.UserId(ctx) - info, err := i.projectService.Get(ctx, appId) - if err != nil { - return nil, err - } - if !info.AsApp { - return nil, fmt.Errorf("not app") - } - //if info.Master != userId { - // return nil, fmt.Errorf("user is not app master, can not update") - //} - - err = i.projectService.Save(ctx, appId, &project.EditProject{ - Name: input.Name, - Description: input.Description, - }) - if err != nil { - return nil, err - } - return i.GetApp(ctx, info.Id) -} - -func (i *imlAppModule) searchMyApps(ctx context.Context, teamId string, keyword string) ([]*project.Project, error) { - userID := utils.UserId(ctx) - condition := make(map[string]interface{}) - condition["as_app"] = true - if teamId != "" { - _, err := i.teamService.Get(ctx, teamId) - if err != nil { - return nil, err - } - condition["team"] = teamId - return i.projectService.Search(ctx, keyword, condition, "update_at desc") - } else { - membersForUser, err := i.teamMemberService.FilterMembersForUser(ctx, userID) - if err != nil { - return nil, err - } - teamIds := membersForUser[userID] - condition["team"] = teamIds - - return i.projectService.Search(ctx, keyword, condition, "update_at desc") - } -} - -func (i *imlAppModule) SearchMyApps(ctx context.Context, teamId string, keyword string) ([]*project_dto.AppItem, error) { - projects, err := i.searchMyApps(ctx, teamId, keyword) - if err != nil { - return nil, err - } - projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { - return p.Id - }) - - subscribers, err := i.subscribeService.SubscriptionsByApplication(ctx, projectIds...) - if err != nil { - return nil, err - } - - subscribeCount := map[string]int64{} - subscribeVerifyCount := map[string]int64{} - verifyTmp := map[string]struct{}{} - subscribeTmp := map[string]struct{}{} - for _, s := range subscribers { - key := fmt.Sprintf("%s-%s", s.Service, s.Application) - switch s.ApplyStatus { - case subscribe.ApplyStatusSubscribe: - if _, ok := subscribeTmp[key]; !ok { - subscribeTmp[key] = struct{}{} - subscribeCount[s.Application]++ - } - case subscribe.ApplyStatusReview: - if _, ok := verifyTmp[key]; !ok { - verifyTmp[key] = struct{}{} - subscribeVerifyCount[s.Application]++ - } - default: - - } - } - items := make([]*project_dto.AppItem, 0, len(projects)) - for _, model := range projects { - subscribeNum := subscribeCount[model.Id] - verifyNum := subscribeVerifyCount[model.Id] - items = append(items, &project_dto.AppItem{ - Id: model.Id, - Name: model.Name, - Description: model.Description, - CreateTime: auto.TimeLabel(model.CreateTime), - UpdateTime: auto.TimeLabel(model.UpdateTime), - Team: auto.UUID(model.Team), - SubscribeNum: subscribeNum, - SubscribeVerifyNum: verifyNum, - CanDelete: subscribeNum == 0, - }) - } - sort.Slice(items, func(i, j int) bool { - if items[i].SubscribeNum != items[j].SubscribeNum { - return items[i].SubscribeNum > items[j].SubscribeNum - } - if items[i].SubscribeVerifyNum != items[j].SubscribeVerifyNum { - return items[i].SubscribeVerifyNum > items[j].SubscribeVerifyNum - } - return items[i].Name < items[j].Name - }) - return items, nil -} - -func (i *imlAppModule) SimpleApps(ctx context.Context, keyword string) ([]*project_dto.SimpleAppItem, error) { - w := make(map[string]interface{}) - w["as_app"] = true - projects, err := i.projectService.Search(ctx, keyword, w) - if err != nil { - return nil, err - } - return utils.SliceToSlice(projects, func(p *project.Project) *project_dto.SimpleAppItem { - return &project_dto.SimpleAppItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Team: auto.UUID(p.Team), - } - }), nil -} - -func (i *imlAppModule) MySimpleApps(ctx context.Context, keyword string) ([]*project_dto.SimpleAppItem, error) { - projects, err := i.searchMyApps(ctx, "", keyword) - if err != nil { - return nil, err - } - items := make([]*project_dto.SimpleAppItem, 0, len(projects)) - for _, p := range projects { - - items = append(items, &project_dto.SimpleAppItem{ - Id: p.Id, - Name: p.Name, - Description: p.Description, - Team: auto.UUID(p.Team), - }) - } - return items, nil -} - -func (i *imlAppModule) GetApp(ctx context.Context, appId string) (*project_dto.App, error) { - info, err := i.projectService.Get(ctx, appId) - if err != nil { - return nil, err - } - if !info.AsApp { - return nil, errors.New("not app") - } - return &project_dto.App{ - Id: info.Id, - Name: info.Name, - Description: info.Description, - Team: auto.UUID(info.Team), - CreateTime: auto.TimeLabel(info.CreateTime), - UpdateTime: auto.TimeLabel(info.UpdateTime), - AsApp: info.AsApp, - }, nil -} - -func (i *imlAppModule) DeleteApp(ctx context.Context, appId string) error { - info, err := i.projectService.Get(ctx, appId) - if err != nil { - if !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - return nil - } - if !info.AsApp { - return errors.New("not app, can not delete") - } - - return i.projectService.Delete(ctx, appId) -} diff --git a/module/project/project.go b/module/project/project.go deleted file mode 100644 index a8b457b..0000000 --- a/module/project/project.go +++ /dev/null @@ -1,70 +0,0 @@ -package project - -import ( - "context" - "reflect" - - project_dto "github.com/eolinker/apipark/module/project/dto" - - "github.com/eolinker/go-common/autowire" -) - -type IProjectModule interface { - // GetProject 获取项目信息 - GetProject(ctx context.Context, id string) (*project_dto.Project, error) - // Search 搜索项目 - Search(ctx context.Context, teamID string, keyword string) ([]*project_dto.ProjectItem, error) - // SearchMyProjects 搜索我的项目列表 - SearchMyProjects(ctx context.Context, teamId string, keyword string) ([]*project_dto.ProjectItem, error) - // CreateProject 创建项目 - CreateProject(ctx context.Context, teamID string, input *project_dto.CreateProject) (*project_dto.Project, error) - // EditProject 编辑项目 - EditProject(ctx context.Context, id string, input *project_dto.EditProject) (*project_dto.Project, error) - // DeleteProject 删除项目 - DeleteProject(ctx context.Context, id string) error - // SimpleProjects 获取简易项目列表 - SimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) - - // MySimpleProjects 获取我的简易项目列表 - MySimpleProjects(ctx context.Context, keyword string) ([]*project_dto.SimpleProjectItem, error) -} - -type IAppModule interface { - CreateApp(ctx context.Context, teamID string, input *project_dto.CreateApp) (*project_dto.App, error) - UpdateApp(ctx context.Context, appId string, input *project_dto.UpdateApp) (*project_dto.App, error) - SearchMyApps(ctx context.Context, teamId string, keyword string) ([]*project_dto.AppItem, error) - // SimpleApps 获取简易项目列表 - SimpleApps(ctx context.Context, keyword string) ([]*project_dto.SimpleAppItem, error) - MySimpleApps(ctx context.Context, keyword string) ([]*project_dto.SimpleAppItem, error) - GetApp(ctx context.Context, appId string) (*project_dto.App, error) - DeleteApp(ctx context.Context, appId string) error -} - -//type IProjectMemberModule interface { -// // Members 获取项目成员列表 -// Members(ctx context.Context, id string, keyword string) ([]*project_dto.MemberItem, error) -// // AddMember 添加项目成员 -// AddMember(ctx context.Context, id string, userIDs []string) error -// // RemoveMember 移除项目成员 -// RemoveMember(ctx context.Context, id string, userIDs []string) error -// // EditProjectMember 修改成员信息 -// EditProjectMember(ctx context.Context, pid string, uid string, roles []string) error -// // SimpleMembers 简易成员列表 -// SimpleMembers(ctx context.Context, pid string) ([]*project_dto.SimpleMemberItem, error) -// SimpleMembersToAdd(ctx context.Context, pid string, keyword string) ([]*project_dto.TeamMemberToAdd, error) -//} - -func init() { - autowire.Auto[IProjectModule](func() reflect.Value { - m := new(imlProjectModule) - return reflect.ValueOf(m) - }) - //autowire.Auto[IProjectMemberModule](func() reflect.Value { - // return reflect.ValueOf(new(imlProjectMemberModule)) - //}) - - autowire.Auto[IAppModule](func() reflect.Value { - return reflect.ValueOf(new(imlAppModule)) - }) - -} diff --git a/module/project_diff/iml.go b/module/project_diff/iml.go index f0c562d..13bca22 100644 --- a/module/project_diff/iml.go +++ b/module/project_diff/iml.go @@ -77,7 +77,7 @@ func (m *imlProjectDiff) getBaseInfo(ctx context.Context, projectId, baseRelease } func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, baseRelease string) (*project_diff.Diff, bool, error) { - apis, err := m.apiService.ListForProject(ctx, projectId) + apis, err := m.apiService.ListForService(ctx, projectId) if err != nil { return nil, false, err } @@ -178,7 +178,7 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p Upstreams: nil, //Clusters: partitions, } - baseApis := utils.NewSet(utils.SliceToSlice(base.apis, func(i *api.APIInfo) string { + baseApis := utils.NewSet(utils.SliceToSlice(base.apis, func(i *api.Info) string { return i.UUID })...) baseApiProxy := utils.SliceToMap(base.apiCommits, func(i *commit.Commit[api.Proxy]) string { diff --git a/module/project_diff/out.go b/module/project_diff/out.go index f07a4ff..dcfb92a 100644 --- a/module/project_diff/out.go +++ b/module/project_diff/out.go @@ -62,7 +62,7 @@ type UpstreamDiffOut struct { type projectInfo struct { id string - apis []*api.APIInfo + apis []*api.Info apiCommits []*commit.Commit[api.Proxy] apiDocs []*commit.Commit[api.Document] upstreamCommits []*commit.Commit[upstream.Config] diff --git a/module/publish/iml.go b/module/publish/iml.go index f65f698..e307626 100644 --- a/module/publish/iml.go +++ b/module/publish/iml.go @@ -6,6 +6,8 @@ import ( "fmt" "time" + "github.com/eolinker/apipark/service/service" + "github.com/eolinker/apipark/service/universally/commit" "github.com/eolinker/apipark/service/api" @@ -17,8 +19,6 @@ import ( "github.com/eolinker/eosc/log" - "github.com/eolinker/apipark/service/project" - projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/publish/dto" "github.com/eolinker/apipark/service/cluster" @@ -43,16 +43,16 @@ type imlPublishModule struct { upstreamService upstream.IUpstreamService `autowired:""` releaseService release.IReleaseService `autowired:""` clusterService cluster.IClusterService `autowired:""` - projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` } func (m *imlPublishModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { - projects, err := m.projectService.List(ctx) + projects, err := m.serviceService.List(ctx) if err != nil { return err } - projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { + projectIds := utils.SliceToSlice(projects, func(p *service.Service) string { return p.Id }) for _, projectId := range projectIds { @@ -279,7 +279,7 @@ func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releas } func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, id string) ([]*dto.PublishStatus, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, err } @@ -315,7 +315,7 @@ func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, // ctx context.Context, project string, input *dto.ApplyInput // *dto.Publish, error func (m *imlPublishModule) Apply(ctx context.Context, project string, input *dto.ApplyInput) (*dto.Publish, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, err } @@ -360,7 +360,7 @@ func (m *imlPublishModule) Apply(ctx context.Context, project string, input *dto } func (m *imlPublishModule) CheckPublish(ctx context.Context, project string, releaseId string) (*dto.DiffOut, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, err } @@ -425,7 +425,7 @@ func (m *imlPublishModule) Close(ctx context.Context, project, id string) error } func (m *imlPublishModule) Stop(ctx context.Context, project string, id string) error { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return err } @@ -448,7 +448,7 @@ func (m *imlPublishModule) Stop(ctx context.Context, project string, id string) } func (m *imlPublishModule) Refuse(ctx context.Context, project string, id string, commits string) error { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return err } @@ -456,7 +456,7 @@ func (m *imlPublishModule) Refuse(ctx context.Context, project string, id string } func (m *imlPublishModule) Accept(ctx context.Context, project string, id string, commits string) error { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return err } @@ -507,7 +507,7 @@ func (m *imlPublishModule) publish(ctx context.Context, id string, clusterId str } func (m *imlPublishModule) Publish(ctx context.Context, project string, id string) error { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return err } @@ -555,7 +555,7 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin } func (m *imlPublishModule) List(ctx context.Context, project string, page, pageSize int) ([]*dto.Publish, int64, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, 0, err } @@ -570,7 +570,7 @@ func (m *imlPublishModule) List(ctx context.Context, project string, page, pageS } func (m *imlPublishModule) Detail(ctx context.Context, project string, id string) (*dto.PublishDetail, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, err } diff --git a/module/release/iml.go b/module/release/iml.go index 93de49d..6698bd6 100644 --- a/module/release/iml.go +++ b/module/release/iml.go @@ -6,11 +6,11 @@ import ( "fmt" "github.com/eolinker/apipark/service/cluster" + "github.com/eolinker/apipark/service/service" projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/release/dto" "github.com/eolinker/apipark/service/api" - "github.com/eolinker/apipark/service/project" "github.com/eolinker/apipark/service/project_diff" "github.com/eolinker/apipark/service/publish" "github.com/eolinker/apipark/service/release" @@ -36,13 +36,13 @@ type imlReleaseModule struct { upstreamService upstream.IUpstreamService `autowired:""` publishService publish.IPublishService `autowired:""` transaction store.ITransaction `autowired:""` - projectService project.IProjectService `autowired:""` + projectService service.IServiceService `autowired:""` clusterService cluster.IClusterService `autowired:""` } func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input *dto.CreateInput) (string, error) { - proInfo, err := m.projectService.CheckProject(ctx, projectId, projectRuleMustServer) + proInfo, err := m.projectService.Check(ctx, projectId, projectRuleMustServer) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return "", errors.New("project not found") @@ -54,7 +54,7 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * return "", fmt.Errorf("cluster not set:%w", err) } - apis, err := m.apiService.ListForProject(ctx, proInfo.Id) + apis, err := m.apiService.ListForService(ctx, proInfo.Id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return "", errors.New("api not found") @@ -157,7 +157,7 @@ func (m *imlReleaseModule) Detail(ctx context.Context, project string, id string } func (m *imlReleaseModule) List(ctx context.Context, project string) ([]*dto.Release, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.projectService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, err } @@ -221,7 +221,7 @@ func (m *imlReleaseModule) List(ctx context.Context, project string) ([]*dto.Rel } func (m *imlReleaseModule) Delete(ctx context.Context, project string, id string) error { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.projectService.Check(ctx, project, projectRuleMustServer) if err != nil { return err } @@ -258,7 +258,7 @@ func (m *imlReleaseModule) Delete(ctx context.Context, project string, id string } func (m *imlReleaseModule) Preview(ctx context.Context, project string) (*dto.Release, *project_diff.Diff, bool, error) { - _, err := m.projectService.CheckProject(ctx, project, projectRuleMustServer) + _, err := m.projectService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, nil, false, err } diff --git a/module/service/dto/input.go b/module/service/dto/input.go index acc33e2..cdfa683 100644 --- a/module/service/dto/input.go +++ b/module/service/dto/input.go @@ -1,25 +1,46 @@ package service_dto type CreateService struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Logo string `json:"logo"` - Tags []string `json:"tags"` - ServiceType string `json:"service_type"` - Partition []string `json:"partition" aocheck:"partition"` - Catalogue *string `json:"group" aocheck:"catalogue"` + Id string `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix"` + Description string `json:"description"` + ServiceType string `json:"service_type"` + AsApp *bool `json:"as_app"` + AsServer *bool `json:"as_server"` } type EditService struct { - Name *string `json:"name"` - Description *string `json:"description"` - Logo *string `json:"logo"` - Tags []string `json:"tags"` - ServiceType *string `json:"service_type"` - Catalogue *string `json:"group" aocheck:"catalogue"` + Name *string `json:"name"` + Description *string `json:"description"` + ServiceType *string `json:"service_type"` + Logo *string `json:"logo"` + Tags *[]string `json:"tags"` } -type BindApis struct { - Apis []string `json:"apis" aocheck:"api"` +type CreateApp struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` +} + +type UpdateApp struct { + Name *string `json:"name"` + Description *string `json:"description"` +} + +type EditMemberRole struct { + Roles []string `json:"roles"` +} + +type Users struct { + Users []string `json:"users" aocheck:"user"` +} + +type EditProjectMember struct { + Roles []string `json:"roles" aocheck:"role"` +} + +type SaveServiceDoc struct { + Doc string `json:"doc"` } diff --git a/module/service/dto/output.go b/module/service/dto/output.go index a826e58..b14fbc2 100644 --- a/module/service/dto/output.go +++ b/module/service/dto/output.go @@ -1,56 +1,113 @@ package service_dto -import "github.com/eolinker/go-common/auto" +import ( + "github.com/eolinker/apipark/service/service" + "github.com/eolinker/go-common/auto" +) type ServiceItem struct { Id string `json:"id"` Name string `json:"name"` - Partition []auto.Label `json:"partition" aolabel:"partition"` - ServiceType string `json:"service_type"` + Team auto.Label `json:"team" aolabel:"team"` ApiNum int64 `json:"api_num"` - Status string `json:"status"` + Description string `json:"description"` CreateTime auto.TimeLabel `json:"create_time"` UpdateTime auto.TimeLabel `json:"update_time"` CanDelete bool `json:"can_delete"` } +type AppItem struct { + Id string `json:"id"` + Name string `json:"name"` + Team auto.Label `json:"team" aolabel:"team"` + SubscribeNum int64 `json:"subscribe_num"` + SubscribeVerifyNum int64 `json:"subscribe_verify_num"` + Description string `json:"description"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + CanDelete bool `json:"can_delete"` +} + +type SimpleServiceItem struct { + Id string `json:"id"` + Name string `json:"name"` + Team auto.Label `json:"team" aolabel:"team"` + Description string `json:"description"` +} + +type SimpleAppItem struct { + Id string `json:"id"` + Name string `json:"name"` + Team auto.Label `json:"team" aolabel:"team"` + Description string `json:"description"` +} + type Service struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Logo string `json:"logo"` - ServiceType string `json:"service_type"` - Team auto.Label `json:"team" aolabel:"team"` - Project auto.Label `json:"project" aolabel:"project"` - Catalogue auto.Label `json:"group" aolabel:"catalogue"` - Partition []auto.Label `json:"partition" aolabel:"partition"` - Tags []auto.Label `json:"tags" aolabel:"tag"` - Status string `json:"status"` + Id string `json:"id"` + Name string `json:"name"` + Prefix string `json:"prefix,omitempty"` + Description string `json:"description"` + Team auto.Label `json:"team" aolabel:"team"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + ServiceType string `json:"service_type"` + Tags []auto.Label `json:"tags" aolabel:"tag"` + Logo string `json:"logo"` + AsServer bool `json:"as_server"` + AsApp bool `json:"as_app"` } -type ServiceDoc struct { - Id string `json:"id"` - Name string `json:"name"` - Doc string `json:"doc"` - Creator auto.Label `json:"creator" aolabel:"user"` - CreateTime auto.TimeLabel `json:"create_time"` - Updater auto.Label `json:"updater" aolabel:"user"` - UpdateTime auto.TimeLabel `json:"update_time"` +type App struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Team auto.Label `json:"team" aolabel:"team"` + CreateTime auto.TimeLabel `json:"create_time"` + UpdateTime auto.TimeLabel `json:"update_time"` + AsApp bool `json:"as_app"` } -type SaveServiceDoc struct { - Doc string `json:"doc"` +func ToService(model *service.Service) *Service { + return &Service{ + Id: model.Id, + Name: model.Name, + Prefix: model.Prefix, + Description: model.Description, + Team: auto.UUID(model.Team), + ServiceType: model.ServiceType.String(), + Logo: model.Logo, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + AsServer: model.AsServer, + AsApp: model.AsApp, + } } -type ServiceApi struct { - Id string `json:"id"` - Name string `json:"name"` - Method string `json:"method"` - Path string `json:"path"` - Description string `json:"description"` +type MemberItem struct { + User auto.Label `json:"user" aolabel:"user"` + Email string `json:"email"` + Roles []auto.Label `json:"roles" aolabel:"role"` + CanDelete bool `json:"can_delete"` } -type SimpleItem struct { +type SimpleMemberItem struct { Id string `json:"id"` Name string `json:"name"` } + +type TeamMemberToAdd struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Email string `json:"email,omitempty"` + Department auto.Label `json:"department" aolabel:"department"` +} + +type ServiceDoc struct { + Id string `json:"id"` + Name string `json:"name"` + Doc string `json:"doc"` + Creator auto.Label `json:"creator" aolabel:"user"` + CreateTime auto.TimeLabel `json:"create_time"` + Updater auto.Label `json:"updater" aolabel:"user"` + UpdateTime auto.TimeLabel `json:"update_time"` +} diff --git a/module/service/iml.go b/module/service/iml.go index df46a90..cadd493 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -3,38 +3,370 @@ package service import ( "context" "errors" + "fmt" + "sort" + "strings" - "github.com/eolinker/apipark/service/project" - "gorm.io/gorm" + service_tag "github.com/eolinker/apipark/service/service-tag" - "github.com/eolinker/go-common/auto" + service_doc "github.com/eolinker/apipark/service/service-doc" serviceDto "github.com/eolinker/apipark/module/service/dto" + + "github.com/eolinker/apipark/service/tag" + "github.com/eolinker/apipark/service/service" + + "github.com/eolinker/apipark/service/subscribe" + "gorm.io/gorm" + + "github.com/eolinker/apipark/service/api" + + "github.com/eolinker/go-common/auto" + + team_member "github.com/eolinker/apipark/service/team-member" + "github.com/eolinker/go-common/store" + + "github.com/google/uuid" + + "github.com/eolinker/go-common/utils" + + "github.com/eolinker/apipark/service/team" + + service_dto "github.com/eolinker/apipark/module/service/dto" ) var ( - _ IServiceModule = (*imlServiceModule)(nil) - projectRuleMustServer = map[string]bool{ - "as_server": true, - } + _ IServiceModule = (*imlServiceModule)(nil) ) type imlServiceModule struct { - projectService project.IProjectService `autowired:""` - serviceDocService service.IDocService `autowired:""` + serviceService service.IServiceService `autowired:""` + teamService team.ITeamService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + tagService tag.ITagService `autowired:""` + serviceDocService service_doc.IDocService `autowired:""` + serviceTagService service_tag.ITagService `autowired:""` + apiService api.IAPIService `autowired:""` + transaction store.ITransaction `autowired:""` +} + +func (i *imlServiceModule) searchMyServices(ctx context.Context, teamId string, keyword string) ([]*service.Service, error) { + + userID := utils.UserId(ctx) + condition := make(map[string]interface{}) + condition["as_server"] = true + if teamId != "" { + _, err := i.teamService.Get(ctx, teamId) + if err != nil { + return nil, err + } + condition["team"] = teamId + return i.serviceService.Search(ctx, keyword, condition, "update_at desc") + } else { + membersForUser, err := i.teamMemberService.FilterMembersForUser(ctx, userID) + if err != nil { + return nil, err + } + teamIds := membersForUser[userID] + condition["team"] = teamIds + return i.serviceService.Search(ctx, keyword, condition, "update_at desc") + } + +} + +func (i *imlServiceModule) SearchMyServices(ctx context.Context, teamId string, keyword string) ([]*service_dto.ServiceItem, error) { + services, err := i.searchMyServices(ctx, teamId, keyword) + if err != nil { + return nil, err + } + serviceIds := utils.SliceToSlice(services, func(p *service.Service) string { + return p.Id + }) + apiCountMap, err := i.apiService.CountByGroup(ctx, "", map[string]interface{}{"service": serviceIds}, "service") + if err != nil { + return nil, err + } + + items := make([]*service_dto.ServiceItem, 0, len(services)) + for _, model := range services { + if teamId != "" && model.Team != teamId { + continue + } + apiCount := apiCountMap[model.Id] + items = append(items, &service_dto.ServiceItem{ + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + CanDelete: apiCount == 0, + }) + } + return items, nil +} + +func (i *imlServiceModule) SimpleAPPS(ctx context.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) { + w := make(map[string]interface{}) + w["as_app"] = true + services, err := i.serviceService.Search(ctx, keyword, w) + if err != nil { + return nil, err + } + return utils.SliceToSlice(services, func(p *service.Service) *service_dto.SimpleServiceItem { + return &service_dto.SimpleServiceItem{ + Id: p.Id, + Name: p.Name, + Description: p.Description, + + Team: auto.UUID(p.Team), + } + }), nil +} + +func (i *imlServiceModule) Simple(ctx context.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) { + w := make(map[string]interface{}) + w["as_server"] = true + + services, err := i.serviceService.Search(ctx, keyword, w) + if err != nil { + return nil, err + } + + items := make([]*service_dto.SimpleServiceItem, 0, len(services)) + for _, p := range services { + + items = append(items, &service_dto.SimpleServiceItem{ + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), + }) + } + return items, nil +} + +func (i *imlServiceModule) MySimple(ctx context.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) { + services, err := i.searchMyServices(ctx, "", keyword) + + if err != nil { + return nil, err + } + + items := make([]*service_dto.SimpleServiceItem, 0, len(services)) + for _, p := range services { + + items = append(items, &service_dto.SimpleServiceItem{ + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), + }) + } + return items, nil +} + +func (i *imlServiceModule) Get(ctx context.Context, id string) (*service_dto.Service, error) { + serviceInfo, err := i.serviceService.Get(ctx, id) + if err != nil { + return nil, err + } + tags, err := i.serviceTagService.List(ctx, []string{serviceInfo.Id}, nil) + if err != nil { + return nil, err + } + + s := service_dto.ToService(serviceInfo) + s.Tags = auto.List(utils.SliceToSlice(tags, func(p *service_tag.Tag) string { + return p.Tid + })) + return s, nil +} + +func (i *imlServiceModule) Search(ctx context.Context, teamID string, keyword string) ([]*service_dto.ServiceItem, error) { + var list []*service.Service + var err error + if teamID != "" { + _, err = i.teamService.Get(ctx, teamID) + if err != nil { + return nil, err + } + list, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"team": teamID}, "update_at desc") + } else { + list, err = i.serviceService.Search(ctx, keyword, nil, "update_at desc") + } + if err != nil { + return nil, err + } + + serviceIds := utils.SliceToSlice(list, func(s *service.Service) string { + return s.Id + }) + + apiCountMap, err := i.apiService.CountByGroup(ctx, "", map[string]interface{}{"service": serviceIds}, "service") + if err != nil { + return nil, err + } + serviceCountMap, err := i.serviceService.CountByGroup(ctx, "", map[string]interface{}{"service": serviceIds}, "service") + if err != nil { + return nil, err + } + + items := make([]*service_dto.ServiceItem, 0, len(list)) + for _, model := range list { + apiCount := apiCountMap[model.Id] + serviceCount := serviceCountMap[model.Id] + items = append(items, &service_dto.ServiceItem{ + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + ApiNum: apiCount, + CanDelete: apiCount == 0 && serviceCount == 0, + }) + } + return items, nil +} + +func (i *imlServiceModule) Create(ctx context.Context, teamID string, input *service_dto.CreateService) (*service_dto.Service, error) { + + if input.Id == "" { + input.Id = uuid.New().String() + } + mo := &service.Create{ + Id: input.Id, + Name: input.Name, + Description: input.Description, + Team: teamID, + ServiceType: service.ServiceType(input.ServiceType), + Prefix: input.Prefix, + } + if input.AsApp == nil { + // 默认值为false + mo.AsApp = false + } else { + mo.AsApp = *input.AsApp + } + if input.AsServer == nil { + // 默认值为true + mo.AsServer = true + } else { + mo.AsServer = *input.AsServer + } + input.Prefix = strings.Trim(strings.Trim(input.Prefix, " "), "/") + err := i.transaction.Transaction(ctx, func(ctx context.Context) error { + return i.serviceService.Create(ctx, mo) + }) + if err != nil { + return nil, err + } + return i.Get(ctx, input.Id) +} + +func (i *imlServiceModule) Edit(ctx context.Context, id string, input *service_dto.EditService) (*service_dto.Service, error) { + _, err := i.serviceService.Get(ctx, id) + if err != nil { + return nil, err + } + err = i.transaction.Transaction(ctx, func(ctx context.Context) error { + + err = i.serviceService.Save(ctx, id, &service.Edit{ + Name: input.Name, + Description: input.Description, + Logo: input.Logo, + ServiceType: (*service.ServiceType)(input.ServiceType), + }) + if err != nil { + return err + } + if input.Tags != nil { + tags, err := i.getTagUuids(ctx, *input.Tags) + if err != nil { + return err + } + i.serviceTagService.Delete(ctx, nil, []string{id}) + for _, t := range tags { + err = i.serviceTagService.Create(ctx, &service_tag.CreateTag{ + Tid: t, + Sid: id, + }) + if err != nil { + return err + } + } + } + return nil + }) + + if err != nil { + return nil, err + } + return i.Get(ctx, id) +} + +func (i *imlServiceModule) Delete(ctx context.Context, id string) error { - transaction store.ITransaction `autowired:""` + err := i.transaction.Transaction(ctx, func(ctx context.Context) error { + count, err := i.apiService.CountByService(ctx, id) + if err != nil { + return err + } + if count > 0 { + return fmt.Errorf("service has apis, can not delete") + } + + return i.serviceService.Delete(ctx, id) + }) + return err +} + +func (i *imlServiceModule) getTagUuids(ctx context.Context, tags []string) ([]string, error) { + list, err := i.tagService.Search(ctx, "", map[string]interface{}{"name": tags}) + if err != nil { + return nil, err + } + tagMap := make(map[string]string) + for _, t := range list { + tagMap[t.Name] = t.Id + } + tagList := make([]string, 0, len(tags)) + repeatTag := make(map[string]struct{}) + for _, t := range tags { + if _, ok := repeatTag[t]; ok { + continue + } + repeatTag[t] = struct{}{} + v := &tag.CreateTag{ + Name: t, + } + id, ok := tagMap[t] + if !ok { + v.Id = uuid.New().String() + err = i.tagService.Create(ctx, v) + if err != nil { + return nil, err + } + tagMap[t] = v.Id + } else { + v.Id = id + } + tagList = append(tagList, v.Id) + } + return tagList, nil } func (i *imlServiceModule) ServiceDoc(ctx context.Context, pid string) (*serviceDto.ServiceDoc, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) + _, err := i.serviceService.Check(ctx, pid, map[string]bool{"as_server": true}) if err != nil { return nil, err } - info, err := i.projectService.Get(ctx, pid) + info, err := i.serviceService.Get(ctx, pid) if err != nil { return nil, err } @@ -61,13 +393,234 @@ func (i *imlServiceModule) ServiceDoc(ctx context.Context, pid string) (*service } func (i *imlServiceModule) SaveServiceDoc(ctx context.Context, pid string, input *serviceDto.SaveServiceDoc) error { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) + _, err := i.serviceService.Check(ctx, pid, map[string]bool{"as_server": true}) if err != nil { return err } - return i.serviceDocService.Save(ctx, &service.SaveDoc{ + return i.serviceDocService.Save(ctx, &service_doc.SaveDoc{ Sid: pid, Doc: input.Doc, }) } + +var _ IAppModule = &imlAppModule{} + +type imlAppModule struct { + teamService team.ITeamService `autowired:""` + serviceService service.IServiceService `autowired:""` + teamMemberService team_member.ITeamMemberService `autowired:""` + subscribeService subscribe.ISubscribeService `autowired:""` + transaction store.ITransaction `autowired:""` +} + +func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) { + + if input.Id == "" { + input.Id = uuid.New().String() + } + userId := utils.UserId(ctx) + mo := &service.Create{ + Id: input.Id, + Name: input.Name, + Description: input.Description, + Team: teamID, + AsApp: true, + } + // 判断用户是否在团队内 + members, err := i.teamMemberService.Members(ctx, []string{teamID}, []string{userId}) + if err != nil { + return nil, err + } + if len(members) == 0 { + return nil, fmt.Errorf("master is not in team") + } + + err = i.transaction.Transaction(ctx, func(ctx context.Context) error { + + return i.serviceService.Create(ctx, mo) + + }) + if err != nil { + return nil, err + } + return i.GetApp(ctx, input.Id) +} + +func (i *imlAppModule) UpdateApp(ctx context.Context, appId string, input *service_dto.UpdateApp) (*service_dto.App, error) { + //userId := utils.UserId(ctx) + info, err := i.serviceService.Get(ctx, appId) + if err != nil { + return nil, err + } + if !info.AsApp { + return nil, fmt.Errorf("not app") + } + //if info.Master != userId { + // return nil, fmt.Errorf("user is not app master, can not update") + //} + + err = i.serviceService.Save(ctx, appId, &service.Edit{ + Name: input.Name, + Description: input.Description, + }) + if err != nil { + return nil, err + } + return i.GetApp(ctx, info.Id) +} + +func (i *imlAppModule) searchMyApps(ctx context.Context, teamId string, keyword string) ([]*service.Service, error) { + userID := utils.UserId(ctx) + condition := make(map[string]interface{}) + condition["as_app"] = true + if teamId != "" { + _, err := i.teamService.Get(ctx, teamId) + if err != nil { + return nil, err + } + condition["team"] = teamId + return i.serviceService.Search(ctx, keyword, condition, "update_at desc") + } else { + membersForUser, err := i.teamMemberService.FilterMembersForUser(ctx, userID) + if err != nil { + return nil, err + } + teamIds := membersForUser[userID] + condition["team"] = teamIds + + return i.serviceService.Search(ctx, keyword, condition, "update_at desc") + } +} + +func (i *imlAppModule) SearchMyApps(ctx context.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) { + services, err := i.searchMyApps(ctx, teamId, keyword) + if err != nil { + return nil, err + } + serviceIds := utils.SliceToSlice(services, func(p *service.Service) string { + return p.Id + }) + + subscribers, err := i.subscribeService.SubscriptionsByApplication(ctx, serviceIds...) + if err != nil { + return nil, err + } + + subscribeCount := map[string]int64{} + subscribeVerifyCount := map[string]int64{} + verifyTmp := map[string]struct{}{} + subscribeTmp := map[string]struct{}{} + for _, s := range subscribers { + key := fmt.Sprintf("%s-%s", s.Service, s.Application) + switch s.ApplyStatus { + case subscribe.ApplyStatusSubscribe: + if _, ok := subscribeTmp[key]; !ok { + subscribeTmp[key] = struct{}{} + subscribeCount[s.Application]++ + } + case subscribe.ApplyStatusReview: + if _, ok := verifyTmp[key]; !ok { + verifyTmp[key] = struct{}{} + subscribeVerifyCount[s.Application]++ + } + default: + + } + } + items := make([]*service_dto.AppItem, 0, len(services)) + for _, model := range services { + subscribeNum := subscribeCount[model.Id] + verifyNum := subscribeVerifyCount[model.Id] + items = append(items, &service_dto.AppItem{ + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + SubscribeNum: subscribeNum, + SubscribeVerifyNum: verifyNum, + CanDelete: subscribeNum == 0, + }) + } + sort.Slice(items, func(i, j int) bool { + if items[i].SubscribeNum != items[j].SubscribeNum { + return items[i].SubscribeNum > items[j].SubscribeNum + } + if items[i].SubscribeVerifyNum != items[j].SubscribeVerifyNum { + return items[i].SubscribeVerifyNum > items[j].SubscribeVerifyNum + } + return items[i].Name < items[j].Name + }) + return items, nil +} + +func (i *imlAppModule) SimpleApps(ctx context.Context, keyword string) ([]*service_dto.SimpleAppItem, error) { + w := make(map[string]interface{}) + w["as_app"] = true + services, err := i.serviceService.Search(ctx, keyword, w) + if err != nil { + return nil, err + } + return utils.SliceToSlice(services, func(p *service.Service) *service_dto.SimpleAppItem { + return &service_dto.SimpleAppItem{ + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), + } + }), nil +} + +func (i *imlAppModule) MySimpleApps(ctx context.Context, keyword string) ([]*service_dto.SimpleAppItem, error) { + services, err := i.searchMyApps(ctx, "", keyword) + if err != nil { + return nil, err + } + items := make([]*service_dto.SimpleAppItem, 0, len(services)) + for _, p := range services { + + items = append(items, &service_dto.SimpleAppItem{ + Id: p.Id, + Name: p.Name, + Description: p.Description, + Team: auto.UUID(p.Team), + }) + } + return items, nil +} + +func (i *imlAppModule) GetApp(ctx context.Context, appId string) (*service_dto.App, error) { + info, err := i.serviceService.Get(ctx, appId) + if err != nil { + return nil, err + } + if !info.AsApp { + return nil, errors.New("not app") + } + return &service_dto.App{ + Id: info.Id, + Name: info.Name, + Description: info.Description, + Team: auto.UUID(info.Team), + CreateTime: auto.TimeLabel(info.CreateTime), + UpdateTime: auto.TimeLabel(info.UpdateTime), + AsApp: info.AsApp, + }, nil +} + +func (i *imlAppModule) DeleteApp(ctx context.Context, appId string) error { + info, err := i.serviceService.Get(ctx, appId) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + return nil + } + if !info.AsApp { + return errors.New("not app, can not delete") + } + + return i.serviceService.Delete(ctx, appId) +} diff --git a/module/service/module.go b/module/service/module.go new file mode 100644 index 0000000..ffdf52e --- /dev/null +++ b/module/service/module.go @@ -0,0 +1,56 @@ +package service + +import ( + "context" + "reflect" + + service_dto "github.com/eolinker/apipark/module/service/dto" + + "github.com/eolinker/go-common/autowire" +) + +type IServiceModule interface { + // Get 获取项目信息 + Get(ctx context.Context, id string) (*service_dto.Service, error) + // Search 搜索项目 + Search(ctx context.Context, teamID string, keyword string) ([]*service_dto.ServiceItem, error) + // SearchMyServices 搜索 + SearchMyServices(ctx context.Context, teamId string, keyword string) ([]*service_dto.ServiceItem, error) + // Create 创建 + Create(ctx context.Context, teamID string, input *service_dto.CreateService) (*service_dto.Service, error) + // Edit 编辑 + Edit(ctx context.Context, id string, input *service_dto.EditService) (*service_dto.Service, error) + // Delete 删除项目 + Delete(ctx context.Context, id string) error + // Simple 获取简易项目列表 + Simple(ctx context.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) + + // MySimple 获取我的简易项目列表 + MySimple(ctx context.Context, keyword string) ([]*service_dto.SimpleServiceItem, error) + + ServiceDoc(ctx context.Context, pid string) (*service_dto.ServiceDoc, error) + // SaveServiceDoc 保存服务文档 + SaveServiceDoc(ctx context.Context, pid string, input *service_dto.SaveServiceDoc) error +} + +type IAppModule interface { + CreateApp(ctx context.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) + UpdateApp(ctx context.Context, appId string, input *service_dto.UpdateApp) (*service_dto.App, error) + SearchMyApps(ctx context.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) + // SimpleApps 获取简易项目列表 + SimpleApps(ctx context.Context, keyword string) ([]*service_dto.SimpleAppItem, error) + MySimpleApps(ctx context.Context, keyword string) ([]*service_dto.SimpleAppItem, error) + GetApp(ctx context.Context, appId string) (*service_dto.App, error) + DeleteApp(ctx context.Context, appId string) error +} + +func init() { + autowire.Auto[IServiceModule](func() reflect.Value { + m := new(imlServiceModule) + return reflect.ValueOf(m) + }) + autowire.Auto[IAppModule](func() reflect.Value { + return reflect.ValueOf(new(imlAppModule)) + }) + +} diff --git a/module/service/service.go b/module/service/service.go deleted file mode 100644 index 7ea3fd5..0000000 --- a/module/service/service.go +++ /dev/null @@ -1,24 +0,0 @@ -package service - -import ( - "context" - "reflect" - - service_dto "github.com/eolinker/apipark/module/service/dto" - - "github.com/eolinker/go-common/autowire" -) - -type IServiceModule interface { - // ServiceDoc 服务文档 - ServiceDoc(ctx context.Context, pid string) (*service_dto.ServiceDoc, error) - // SaveServiceDoc 保存服务文档 - SaveServiceDoc(ctx context.Context, pid string, input *service_dto.SaveServiceDoc) error -} - -func init() { - autowire.Auto[IServiceModule](func() reflect.Value { - return reflect.ValueOf(new(imlServiceModule)) - }) - -} diff --git a/module/subscribe/iml.go b/module/subscribe/iml.go index 2af4cf5..961a03f 100644 --- a/module/subscribe/iml.go +++ b/module/subscribe/iml.go @@ -22,8 +22,6 @@ import ( "github.com/eolinker/apipark/service/subscribe" - "github.com/eolinker/apipark/service/project" - subscribe_dto "github.com/eolinker/apipark/module/subscribe/dto" ) @@ -32,10 +30,9 @@ var ( ) type imlSubscribeModule struct { - projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` subscribeService subscribe.ISubscribeService `autowired:""` subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - serviceService service.IServiceService `autowired:""` clusterService cluster.IClusterService `autowired:""` transaction store.ITransaction `autowired:""` } @@ -56,11 +53,11 @@ func (i *imlSubscribeModule) getSubscribers(ctx context.Context, projectIds []st func (i *imlSubscribeModule) initGateway(ctx context.Context, clientDriver gateway.IClientDriver) error { - projects, err := i.projectService.List(ctx) + projects, err := i.serviceService.List(ctx) if err != nil { return err } - projectIds := utils.SliceToSlice(projects, func(p *project.Project) string { + projectIds := utils.SliceToSlice(projects, func(p *service.Service) string { return p.Id }) releases, err := i.getSubscribers(ctx, projectIds) @@ -72,55 +69,55 @@ func (i *imlSubscribeModule) initGateway(ctx context.Context, clientDriver gatew } func (i *imlSubscribeModule) SearchSubscriptions(ctx context.Context, partitionId string, app string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { - pInfo, err := i.projectService.Get(ctx, app) - if err != nil { - return nil, fmt.Errorf("get application error: %w", err) - } - if !pInfo.AsApp { - return nil, fmt.Errorf("project %s is not an application", app) - } - - // 获取当前订阅服务列表 - subscriptions, err := i.subscribeService.MySubscribeServices(ctx, app, nil, nil, partitionId) - if err != nil { - return nil, err - } - serviceIds := utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) string { - return s.Service - }) - services, err := i.serviceService.SearchByUuids(ctx, keyword, serviceIds...) - if err != nil { - return nil, fmt.Errorf("search service error: %w", err) - } - serviceMap := utils.SliceToMapArray(services, func(s *service.Service) string { - return s.Id - }) - - return utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) *subscribe_dto.SubscriptionItem { - return &subscribe_dto.SubscriptionItem{ - Id: s.Id, - Service: auto.UUID(s.Service), - ApplyStatus: s.ApplyStatus, - Project: auto.UUID(s.Project), - Team: auto.UUID(pInfo.Team), - From: s.From, - CreateTime: auto.TimeLabel(s.CreateAt), - } - }, func(s *subscribe.Subscribe) bool { - _, ok := serviceMap[s.Service] - if !ok { - return false - } - if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { - return false - } - return true - }), nil - + //pInfo, err := i.serviceService.Get(ctx, app) + //if err != nil { + // return nil, fmt.Errorf("get application error: %w", err) + //} + //if !pInfo.AsApp { + // return nil, fmt.Errorf("project %s is not an application", app) + //} + // + //// 获取当前订阅服务列表 + //subscriptions, err := i.subscribeService.MySubscribeServices(ctx, app, nil, nil, partitionId) + //if err != nil { + // return nil, err + //} + //serviceIds := utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) string { + // return s.Service + //}) + //services, err := i.serviceService.SearchByUuids(ctx, keyword, serviceIds...) + //if err != nil { + // return nil, fmt.Errorf("search service error: %w", err) + //} + //serviceMap := utils.SliceToMapArray(services, func(s *service.Service) string { + // return s.Id + //}) + + //return utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) *subscribe_dto.SubscriptionItem { + // return &subscribe_dto.SubscriptionItem{ + // Id: s.Id, + // Service: auto.UUID(s.Service), + // ApplyStatus: s.ApplyStatus, + // Service: auto.UUID(s.Service), + // Team: auto.UUID(pInfo.Team), + // From: s.From, + // CreateTime: auto.TimeLabel(s.CreateAt), + // } + //}, func(s *subscribe.Subscribe) bool { + // _, ok := serviceMap[s.Service] + // if !ok { + // return false + // } + // if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { + // return false + // } + // return true + //}), nil + return nil, nil } func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, uuid string) error { - _, err := i.projectService.Get(ctx, pid) + _, err := i.serviceService.Get(ctx, pid) if err != nil { return fmt.Errorf("get project error: %w", err) } @@ -160,7 +157,7 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, } func (i *imlSubscribeModule) DeleteSubscription(ctx context.Context, pid string, uuid string) error { - _, err := i.projectService.Get(ctx, pid) + _, err := i.serviceService.Get(ctx, pid) if err != nil { return fmt.Errorf("get project error: %w", err) } @@ -175,7 +172,7 @@ func (i *imlSubscribeModule) DeleteSubscription(ctx context.Context, pid string, } func (i *imlSubscribeModule) RevokeApply(ctx context.Context, app string, uuid string) error { - _, err := i.projectService.Get(ctx, app) + _, err := i.serviceService.Get(ctx, app) if err != nil { return fmt.Errorf("get app error: %w", err) } @@ -193,7 +190,7 @@ func (i *imlSubscribeModule) RevokeApply(ctx context.Context, app string, uuid s } func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, input *subscribe_dto.AddSubscriber) error { - _, err := i.projectService.Get(ctx, project) + _, err := i.serviceService.Get(ctx, project) if err != nil { return err } @@ -249,7 +246,7 @@ func (i *imlSubscribeModule) onlineSubscriber(ctx context.Context, clusterId str } func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project string, serviceId string, applicationId string) error { - _, err := i.projectService.Get(ctx, project) + _, err := i.serviceService.Get(ctx, project) if err != nil { return err } @@ -295,7 +292,7 @@ func (i *imlSubscribeModule) offlineForCluster(ctx context.Context, clusterId st } func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId string, keyword string) ([]*subscribe_dto.Subscriber, error) { - pInfo, err := i.projectService.Get(ctx, projectId) + pInfo, err := i.serviceService.Get(ctx, projectId) if err != nil { return nil, err } @@ -353,7 +350,7 @@ var _ ISubscribeApprovalModule = (*imlSubscribeApprovalModule)(nil) type imlSubscribeApprovalModule struct { subscribeService subscribe.ISubscribeService `autowired:""` subscribeApplyService subscribe.ISubscribeApplyService `autowired:""` - projectService project.IProjectService `autowired:""` + projectService service.IServiceService `autowired:""` clusterService cluster.IClusterService `autowired:""` transaction store.ITransaction `autowired:""` } diff --git a/module/team/dto/output.go b/module/team/dto/output.go index d15d1f5..b897a06 100644 --- a/module/team/dto/output.go +++ b/module/team/dto/output.go @@ -12,18 +12,20 @@ type Item struct { CreateTime auto.TimeLabel `json:"create_time"` UpdateTime auto.TimeLabel `json:"update_time"` CanDelete bool `json:"can_delete"` - ProjectNum int64 `json:"system_num"` + ServiceNum int64 `json:"service_num"` + AppNum int64 `json:"app_num"` } -func ToItem(model *team.Team, projectNum int64) *Item { +func ToItem(model *team.Team, serviceNum int64, appNum int64) *Item { return &Item{ Id: model.Id, Name: model.Name, Description: model.Description, CreateTime: auto.TimeLabel(model.CreateTime), UpdateTime: auto.TimeLabel(model.UpdateTime), - ProjectNum: projectNum, - CanDelete: projectNum == 0, + ServiceNum: serviceNum, + AppNum: appNum, + CanDelete: serviceNum == 0 && appNum == 0, } } @@ -38,7 +40,7 @@ type Team struct { CanDelete bool `json:"can_delete"` } -func ToTeam(model *team.Team, projectNum int) *Team { +func ToTeam(model *team.Team, serviceNum int64, appNum int64) *Team { return &Team{ Id: model.Id, Name: model.Name, @@ -47,6 +49,6 @@ func ToTeam(model *team.Team, projectNum int) *Team { UpdateTime: auto.TimeLabel(model.UpdateTime), Creator: auto.UUID(model.Creator), Updater: auto.UUID(model.Updater), - CanDelete: projectNum == 0, + CanDelete: serviceNum == 0 && appNum == 0, } } diff --git a/module/team/iml.go b/module/team/iml.go index 4e7f34e..458c82b 100644 --- a/module/team/iml.go +++ b/module/team/iml.go @@ -8,12 +8,11 @@ import ( "github.com/eolinker/ap-account/service/role" - "github.com/eolinker/apipark/service/project" - "github.com/eolinker/go-common/store" "github.com/eolinker/ap-account/service/user" + "github.com/eolinker/apipark/service/service" team_member "github.com/eolinker/apipark/service/team-member" "github.com/google/uuid" @@ -30,7 +29,7 @@ type imlTeamModule struct { service team.ITeamService `autowired:""` memberService team_member.ITeamMemberService `autowired:""` userService user.IUserService `autowired:""` - projectService project.IProjectService `autowired:""` + serviceService service.IServiceService `autowired:""` roleService role.IRoleService `autowired:""` roleMemberService role.IRoleMemberService `autowired:""` transaction store.ITransaction `autowired:""` @@ -41,12 +40,16 @@ func (m *imlTeamModule) GetTeam(ctx context.Context, id string) (*team_dto.Team, if err != nil { return nil, err } - projects, err := m.projectService.CountTeam(ctx, id, "") + serviceCountMap, err := m.serviceService.ServiceCountByTeam(ctx, id) + if err != nil { + return nil, err + } + appCountMap, err := m.serviceService.ServiceCountByTeam(ctx, id) if err != nil { return nil, err } - return team_dto.ToTeam(tv, int(projects)), nil + return team_dto.ToTeam(tv, serviceCountMap[id], appCountMap[id]), nil } @@ -55,13 +58,18 @@ func (m *imlTeamModule) Search(ctx context.Context, keyword string) ([]*team_dto if err != nil { return nil, err } - projectNumMap, err := m.projectService.CountByTeam(ctx, keyword) + + serviceCountMap, err := m.serviceService.ServiceCountByTeam(ctx) + if err != nil { + return nil, err + } + appCountMap, err := m.serviceService.AppCountByTeam(ctx) if err != nil { return nil, err } outList := make([]*team_dto.Item, 0, len(list)) for _, v := range list { - outList = append(outList, team_dto.ToItem(v, projectNumMap[v.Id])) + outList = append(outList, team_dto.ToItem(v, serviceCountMap[v.Id], appCountMap[v.Id])) } return outList, nil } @@ -121,7 +129,7 @@ func (m *imlTeamModule) Edit(ctx context.Context, id string, input *team_dto.Edi func (m *imlTeamModule) Delete(ctx context.Context, id string) error { err := m.transaction.Transaction(ctx, func(ctx context.Context) error { - count, err := m.projectService.Count(ctx, "", map[string]interface{}{ + count, err := m.serviceService.Count(ctx, "", map[string]interface{}{ "team": id, }) if err != nil { diff --git a/module/topology/dto/input.go b/module/topology/dto/input.go deleted file mode 100644 index 1ebc085..0000000 --- a/module/topology/dto/input.go +++ /dev/null @@ -1 +0,0 @@ -package topology_dto diff --git a/module/topology/dto/output.go b/module/topology/dto/output.go deleted file mode 100644 index b76e519..0000000 --- a/module/topology/dto/output.go +++ /dev/null @@ -1,22 +0,0 @@ -package topology_dto - -import "github.com/eolinker/go-common/auto" - -type ProjectItem struct { - ID string `json:"id"` - Name string `json:"name"` - InvokeServices []string `json:"invoke_services"` - IsServer bool `json:"is_server"` - IsApp bool `json:"is_app"` -} - -type ServiceItem struct { - ID string `json:"id"` - Name string `json:"name"` - Project string `json:"project"` -} - -type TopologyItem struct { - Project auto.Label `json:"project" aolabel:"project"` - Services []auto.Label `json:"services" aolabel:"service"` -} diff --git a/module/topology/iml.go b/module/topology/iml.go deleted file mode 100644 index 7c4b06c..0000000 --- a/module/topology/iml.go +++ /dev/null @@ -1,104 +0,0 @@ -package topology - -import ( - "context" - - "github.com/eolinker/go-common/auto" - - "github.com/eolinker/apipark/service/subscribe" - - "github.com/eolinker/go-common/utils" - - "github.com/eolinker/apipark/service/service" - - topology_dto "github.com/eolinker/apipark/module/topology/dto" - - "github.com/eolinker/apipark/service/project" -) - -var _ ITopologyModule = (*imlTopologyModule)(nil) - -type imlTopologyModule struct { - projectService project.IProjectService `autowired:""` - subscribeService subscribe.ISubscribeService `autowired:""` - serviceService service.IServiceService `autowired:""` -} - -func (i *imlTopologyModule) SystemTopology(ctx context.Context) ([]*topology_dto.ProjectItem, []*topology_dto.ServiceItem, error) { - projects, err := i.projectService.List(ctx) - if err != nil { - return nil, nil, err - } - subscriptions, err := i.subscribeService.ListBySubscribeStatus(ctx, "", subscribe.ApplyStatusSubscribe) - if err != nil { - return nil, nil, err - } - - services, err := i.serviceService.List(ctx) - if err != nil { - return nil, nil, err - } - subscriptionMap := utils.SliceToMapArrayO(subscriptions, func(s *subscribe.Subscribe) (string, string) { - return s.Application, s.Service - }) - ps := utils.SliceToSlice(projects, func(p *project.Project) *topology_dto.ProjectItem { - return &topology_dto.ProjectItem{ - ID: p.Id, - Name: p.Name, - InvokeServices: subscriptionMap[p.Id], - IsApp: p.AsApp, - IsServer: p.AsServer, - } - }) - ss := utils.SliceToSlice(services, func(s *service.Service) *topology_dto.ServiceItem { - return &topology_dto.ServiceItem{ - ID: s.Id, - Name: s.Name, - Project: s.Project, - } - }) - return ps, ss, nil -} - -func (i *imlTopologyModule) ProjectTopology(ctx context.Context, projectID string) ([]*topology_dto.ServiceItem, []*topology_dto.TopologyItem, []*topology_dto.TopologyItem, error) { - // 获取系统中所有服务 - services, err := i.serviceService.ListByProject(ctx, projectID) - if err != nil { - return nil, nil, nil, err - } - // 获取当前项目的订阅关系 - mySubscribeServices, err := i.subscribeService.MySubscribeServices(ctx, projectID, nil, nil) - if err != nil { - return nil, nil, nil, err - } - - subscribers, err := i.subscribeService.Subscribers(ctx, projectID, subscribe.ApplyStatusSubscribe) - if err != nil { - return nil, nil, nil, err - } - projectMap := utils.SliceToMapArrayO(mySubscribeServices, func(s *subscribe.Subscribe) (string, auto.Label) { - return s.Project, auto.UUID(s.Service) - }) - subscriberMap := utils.SliceToMapArrayO(subscribers, func(s *subscribe.Subscribe) (string, auto.Label) { - return s.Application, auto.UUID(s.Service) - }) - - return utils.SliceToSlice(services, func(s *service.Service) *topology_dto.ServiceItem { - return &topology_dto.ServiceItem{ - ID: s.Id, - Name: s.Name, - Project: s.Project, - } - }), utils.MapToSlice(subscriberMap, func(k string, ss []auto.Label) *topology_dto.TopologyItem { - return &topology_dto.TopologyItem{ - Project: auto.UUID(k), - Services: ss, - } - }), utils.MapToSlice(projectMap, func(k string, ss []auto.Label) *topology_dto.TopologyItem { - return &topology_dto.TopologyItem{ - Project: auto.UUID(k), - Services: ss, - } - }), nil - -} diff --git a/module/topology/topology.go b/module/topology/topology.go deleted file mode 100644 index e518daf..0000000 --- a/module/topology/topology.go +++ /dev/null @@ -1,21 +0,0 @@ -package topology - -import ( - "context" - "reflect" - - "github.com/eolinker/go-common/autowire" - - topology_dto "github.com/eolinker/apipark/module/topology/dto" -) - -type ITopologyModule interface { - SystemTopology(ctx context.Context) ([]*topology_dto.ProjectItem, []*topology_dto.ServiceItem, error) - ProjectTopology(ctx context.Context, projectID string) ([]*topology_dto.ServiceItem, []*topology_dto.TopologyItem, []*topology_dto.TopologyItem, error) -} - -func init() { - autowire.Auto[ITopologyModule](func() reflect.Value { - return reflect.ValueOf(new(imlTopologyModule)) - }) -} diff --git a/module/upstream/iml.go b/module/upstream/iml.go index 772ec8f..6e1333a 100644 --- a/module/upstream/iml.go +++ b/module/upstream/iml.go @@ -6,11 +6,10 @@ import ( "fmt" "github.com/eolinker/apipark/service/cluster" + "github.com/eolinker/apipark/service/service" "gorm.io/gorm" - "github.com/eolinker/apipark/service/project" - "github.com/eolinker/apipark/service/upstream" "github.com/eolinker/go-common/store" @@ -26,13 +25,13 @@ var ( ) type imlUpstreamModule struct { - projectService project.IProjectService `autowired:""` + projectService service.IServiceService `autowired:""` upstreamService upstream.IUpstreamService `autowired:""` transaction store.ITransaction `autowired:""` } func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.UpstreamConfig, error) { - _, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) + _, err := i.projectService.Check(ctx, pid, projectRuleMustServer) if err != nil { return nil, err } @@ -55,7 +54,7 @@ func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.U } func (i *imlUpstreamModule) Save(ctx context.Context, pid string, upstreamConfig upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { - pInfo, err := i.projectService.CheckProject(ctx, pid, projectRuleMustServer) + pInfo, err := i.projectService.Check(ctx, pid, projectRuleMustServer) if err != nil { return nil, err } diff --git a/plugins/core/api.go b/plugins/core/api.go index 047211d..7bd016e 100644 --- a/plugins/core/api.go +++ b/plugins/core/api.go @@ -8,17 +8,17 @@ import ( func (p *plugin) apiApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/apis", []string{"context", "query:keyword", "query:project"}, []string{"apis"}, p.apiController.Search), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/apis/simple", []string{"context", "query:keyword", "query:project"}, []string{"apis"}, p.apiController.SimpleSearch), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/simple/project/apis", []string{"context", "query:partition", "body"}, []string{"apis"}, p.apiController.SimpleList), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/api/detail", []string{"context", "query:project", "query:api"}, []string{"api"}, p.apiController.Detail), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/api/detail/simple", []string{"context", "query:project", "query:api"}, []string{"api"}, p.apiController.SimpleDetail), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/api", []string{"context", "query:project", "body"}, []string{"api"}, p.apiController.Create), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/api", []string{"context", "query:project", "query:api", "body"}, []string{"api"}, p.apiController.Edit), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/api", []string{"context", "query:project", "query:api"}, nil, p.apiController.Delete), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/api/copy", []string{"context", "query:project", "query:api", "body"}, []string{"api"}, p.apiController.Copy), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/api/doc", []string{"context", "query:project", "query:api"}, []string{"api"}, p.apiController.ApiDocDetail), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/api/proxy", []string{"context", "query:project", "query:api"}, []string{"api"}, p.apiController.ApiProxyDetail), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/api/define", []string{"context", "query:project"}, []string{"prefix", "force"}, p.apiController.Prefix), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/apis", []string{"context", "query:keyword", "query:service"}, []string{"apis"}, p.apiController.Search), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/apis/simple", []string{"context", "query:keyword", "query:service"}, []string{"apis"}, p.apiController.SimpleSearch), + //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/simple/service/apis", []string{"context", "query:service"}, []string{"apis"}, p.apiController.SimpleList), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/api/detail", []string{"context", "query:service", "query:api"}, []string{"api"}, p.apiController.Detail), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/api/detail/simple", []string{"context", "query:service", "query:api"}, []string{"api"}, p.apiController.SimpleDetail), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/api", []string{"context", "query:service", "body"}, []string{"api"}, p.apiController.Create), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/api", []string{"context", "query:service", "query:api", "body"}, []string{"api"}, p.apiController.Edit), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/api", []string{"context", "query:service", "query:api"}, nil, p.apiController.Delete), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/api/copy", []string{"context", "query:service", "query:api", "body"}, []string{"api"}, p.apiController.Copy), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/api/doc", []string{"context", "query:service", "query:api"}, []string{"api"}, p.apiController.ApiDocDetail), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/api/proxy", []string{"context", "query:service", "query:api"}, []string{"api"}, p.apiController.ApiProxyDetail), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/api/define", []string{"context", "query:service"}, []string{"prefix", "force"}, p.apiController.Prefix), } } diff --git a/plugins/core/core.go b/plugins/core/core.go index ce9a1ee..93ccc25 100644 --- a/plugins/core/core.go +++ b/plugins/core/core.go @@ -11,13 +11,11 @@ import ( "github.com/eolinker/apipark/controller/common" - "github.com/eolinker/apipark/controller/topology" - dynamic_module "github.com/eolinker/apipark/controller/dynamic-module" "github.com/eolinker/apipark/controller/release" - project_authorization "github.com/eolinker/apipark/controller/project-authorization" + application_authorization "github.com/eolinker/apipark/controller/application-authorization" "github.com/eolinker/apipark/controller/subscribe" @@ -29,8 +27,6 @@ import ( "github.com/eolinker/apipark/controller/catalogue" - "github.com/eolinker/apipark/controller/project" - "github.com/eolinker/apipark/controller/my_team" "github.com/eolinker/apipark/controller/certificate" @@ -58,26 +54,25 @@ func (d *Driver) Create() (pm3.IPlugin, error) { } type plugin struct { - clusterController cluster.IClusterController `autowired:""` - certificateController certificate.ICertificateController `autowired:""` - teamManagerController team_manager.ITeamManagerController `autowired:""` - myTeamController my_team.ITeamController `autowired:""` - appController project.IAppController `autowired:""` - projectController project.IProjectController `autowired:""` - serviceController service.IServiceController `autowired:""` - catalogueController catalogue.ICatalogueController `autowired:""` - upstreamController upstream.IUpstreamController `autowired:""` - apiController api.IAPIController `autowired:""` - subscribeController subscribe.ISubscribeController `autowired:""` - projectAuthorizationController project_authorization.IProjectAuthorizationController `autowired:""` - releaseController release.IReleaseController `autowired:""` - roleController role.IRoleController `autowired:""` - subscribeApprovalController subscribe.ISubscribeApprovalController `autowired:""` - dynamicModuleController dynamic_module.IDynamicModuleController `autowired:""` - topologyController topology.ITopologyController `autowired:""` - pluginClusterController plugin_cluster.IPluginClusterController `autowired:""` - commonController common.ICommonController `autowired:""` - apis []pm3.Api + clusterController cluster.IClusterController `autowired:""` + certificateController certificate.ICertificateController `autowired:""` + teamManagerController team_manager.ITeamManagerController `autowired:""` + myTeamController my_team.ITeamController `autowired:""` + appController service.IAppController `autowired:""` + serviceController service.IServiceController `autowired:""` + //serviceController service.IServiceController `autowired:""` + catalogueController catalogue.ICatalogueController `autowired:""` + upstreamController upstream.IUpstreamController `autowired:""` + apiController api.IAPIController `autowired:""` + subscribeController subscribe.ISubscribeController `autowired:""` + appAuthorizationController application_authorization.IAuthorizationController `autowired:""` + releaseController release.IReleaseController `autowired:""` + roleController role.IRoleController `autowired:""` + subscribeApprovalController subscribe.ISubscribeApprovalController `autowired:""` + dynamicModuleController dynamic_module.IDynamicModuleController `autowired:""` + pluginClusterController plugin_cluster.IPluginClusterController `autowired:""` + commonController common.ICommonController `autowired:""` + apis []pm3.Api } func (p *plugin) OnComplete() { @@ -86,16 +81,15 @@ func (p *plugin) OnComplete() { p.apis = append(p.apis, p.clusterApi()...) p.apis = append(p.apis, p.TeamManagerApi()...) p.apis = append(p.apis, p.MyTeamApi()...) - p.apis = append(p.apis, p.ProjectApi()...) + p.apis = append(p.apis, p.ServiceApis()...) p.apis = append(p.apis, p.catalogueApi()...) - p.apis = append(p.apis, p.serviceApi()...) p.apis = append(p.apis, p.upstreamApis()...) p.apis = append(p.apis, p.apiApis()...) p.apis = append(p.apis, p.subscribeApis()...) p.apis = append(p.apis, p.projectAuthorizationApis()...) p.apis = append(p.apis, p.releaseApis()...) p.apis = append(p.apis, p.DynamicModuleApis()...) - p.apis = append(p.apis, p.TopologyApis()...) + p.apis = append(p.apis, p.PartitionPluginApi()...) p.apis = append(p.apis, p.commonApis()...) } diff --git a/plugins/core/my-team.go b/plugins/core/my-team.go index 311731b..a21ea05 100644 --- a/plugins/core/my-team.go +++ b/plugins/core/my-team.go @@ -20,9 +20,9 @@ func (p *plugin) MyTeamApi() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/team/member/role", []string{"context", "query:team", "body"}, nil, p.myTeamController.UpdateMemberRole), // 团队项目操作 - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/projects", []string{"context", "query:team", "query:keyword"}, []string{"projects"}, p.projectController.Search), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/project", []string{"context", "query:team", "body"}, []string{"project"}, p.projectController.CreateProject), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/app", []string{"context", "query:team", "body"}, []string{"project"}, p.appController.CreateApp), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/project", []string{"context", "query:project"}, nil, p.projectController.DeleteProject), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/services", []string{"context", "query:team", "query:keyword"}, []string{"services"}, p.serviceController.Search), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/service", []string{"context", "query:team", "body"}, []string{"service"}, p.serviceController.Create), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/app", []string{"context", "query:team", "body"}, []string{"app"}, p.appController.CreateApp), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/service", []string{"context", "query:service"}, nil, p.serviceController.Delete), } } diff --git a/plugins/core/project-authorization.go b/plugins/core/project-authorization.go index 77d60e0..e2ad3db 100644 --- a/plugins/core/project-authorization.go +++ b/plugins/core/project-authorization.go @@ -8,11 +8,11 @@ import ( func (p *plugin) projectAuthorizationApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/authorization", []string{"context", "query:project", "body"}, []string{"authorization"}, p.projectAuthorizationController.AddAuthorization), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/authorization", []string{"context", "query:project", "query:authorization", "body"}, []string{"authorization"}, p.projectAuthorizationController.EditAuthorization), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/authorization", []string{"context", "query:project", "query:authorization"}, nil, p.projectAuthorizationController.DeleteAuthorization), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/authorization", []string{"context", "query:project", "query:authorization"}, []string{"authorization"}, p.projectAuthorizationController.Info), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/authorizations", []string{"context", "query:project"}, []string{"authorizations"}, p.projectAuthorizationController.Authorizations), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/authorization/details", []string{"context", "query:project", "query:authorization"}, []string{"details"}, p.projectAuthorizationController.Detail), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/app/authorization", []string{"context", "query:app", "body"}, []string{"authorization"}, p.appAuthorizationController.AddAuthorization), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/app/authorization", []string{"context", "query:app", "query:authorization", "body"}, []string{"authorization"}, p.appAuthorizationController.EditAuthorization), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/app/authorization", []string{"context", "query:app", "query:authorization"}, nil, p.appAuthorizationController.DeleteAuthorization), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/authorization", []string{"context", "query:app", "query:authorization"}, []string{"authorization"}, p.appAuthorizationController.Info), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/authorizations", []string{"context", "query:app"}, []string{"authorizations"}, p.appAuthorizationController.Authorizations), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/authorization/details", []string{"context", "query:app", "query:authorization"}, []string{"details"}, p.appAuthorizationController.Detail), } } diff --git a/plugins/core/project.go b/plugins/core/project.go deleted file mode 100644 index 9592887..0000000 --- a/plugins/core/project.go +++ /dev/null @@ -1,38 +0,0 @@ -package core - -import ( - "net/http" - - "github.com/eolinker/go-common/pm3" -) - -func (p *plugin) ProjectApi() []pm3.Api { - return []pm3.Api{ - // 项目 - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/info", []string{"context", "query:project"}, []string{"project"}, p.projectController.GetProject), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/info", []string{"context", "query:project", "body"}, []string{"project"}, p.projectController.EditProject), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/info", []string{"context", "query:project"}, nil, p.projectController.DeleteProject), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_projects", []string{"context", "query:team", "query:keyword"}, []string{"projects"}, p.projectController.SearchMyProjects), - - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/projects/mine", []string{"context", "query:keyword"}, []string{"projects"}, p.projectController.MySimpleProjects), - - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/projects", []string{"context", "query:keyword", "query:partition"}, []string{"projects"}, p.projectController.SimpleProjects), - - //// 项目成员相关 - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.Members), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/project/members", []string{"context", "query:project"}, []string{"members"}, p.projectMemberController.SimpleMembers), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/members/toadd", []string{"context", "query:project", "query:keyword"}, []string{"members"}, p.projectMemberController.SimpleMembersToAdd), - // - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/member", []string{"context", "query:project", "body"}, nil, p.projectMemberController.AddMember), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/member", []string{"context", "query:project", "query:user"}, nil, p.projectMemberController.RemoveMember), - //pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/member", []string{"context", "query:project", "query:user", "body"}, nil, p.projectMemberController.EditProjectMember), - - // 应用相关 - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/info", []string{"context", "query:app"}, []string{"project"}, p.appController.GetApp), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/app", []string{"context", "query:app"}, nil, p.appController.DeleteApp), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps", []string{"context", "query:keyword"}, []string{"projects"}, p.appController.SimpleApps), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps/mine", []string{"context", "query:keyword"}, []string{"projects"}, p.appController.MySimpleApps), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_apps", []string{"context", "query:team", "query:keyword"}, []string{"projects"}, p.appController.SearchMyApps), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/app/info", []string{"context", "query:app", "body"}, []string{"projects"}, p.appController.UpdateApp), - } -} diff --git a/plugins/core/service.go b/plugins/core/service.go index 91f4fda..de4a307 100644 --- a/plugins/core/service.go +++ b/plugins/core/service.go @@ -6,10 +6,27 @@ import ( "github.com/eolinker/go-common/pm3" ) -func (p *plugin) serviceApi() []pm3.Api { +func (p *plugin) ServiceApis() []pm3.Api { return []pm3.Api{ + // 项目 + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/info", []string{"context", "query:service"}, []string{"service"}, p.serviceController.Get), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/info", []string{"context", "query:service", "body"}, []string{"service"}, p.serviceController.Edit), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/info", []string{"context", "query:service"}, nil, p.serviceController.Delete), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_services", []string{"context", "query:team", "query:keyword"}, []string{"services"}, p.serviceController.SearchMyServices), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/service/doc", []string{"context", "query:project"}, []string{"doc"}, p.serviceController.ServiceDoc), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/service/doc", []string{"context", "query:project", "body"}, nil, p.serviceController.SaveServiceDoc), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/services/mine", []string{"context", "query:keyword"}, []string{"services"}, p.serviceController.MySimple), + + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/services", []string{"context", "query:keyword"}, []string{"services"}, p.serviceController.Simple), + + // 应用相关 + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/app/info", []string{"context", "query:app"}, []string{"app"}, p.appController.GetApp), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/app", []string{"context", "query:app"}, nil, p.appController.DeleteApp), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps", []string{"context", "query:keyword"}, []string{"apps"}, p.appController.SimpleApps), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps/mine", []string{"context", "query:keyword"}, []string{"apps"}, p.appController.MySimpleApps), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_apps", []string{"context", "query:team", "query:keyword"}, []string{"apps"}, p.appController.SearchMyApps), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/app/info", []string{"context", "query:app", "body"}, []string{"app"}, p.appController.UpdateApp), + + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/service/doc", []string{"context", "query:service"}, []string{"doc"}, p.serviceController.ServiceDoc), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/service/doc", []string{"context", "query:service", "body"}, nil, p.serviceController.SaveServiceDoc), } } diff --git a/plugins/core/topology.go b/plugins/core/topology.go deleted file mode 100644 index 24459d9..0000000 --- a/plugins/core/topology.go +++ /dev/null @@ -1,14 +0,0 @@ -package core - -import ( - "net/http" - - "github.com/eolinker/go-common/pm3" -) - -func (p *plugin) TopologyApis() []pm3.Api { - return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/topology", []string{"context"}, []string{"projects", "services"}, p.topologyController.SystemTopology), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/topology", []string{"context", "query:project"}, []string{"services", "subscribers", "invoke"}, p.topologyController.ProjectTopology), - } -} diff --git a/service/api/iml.go b/service/api/iml.go index 48f6e9e..e056143 100644 --- a/service/api/iml.go +++ b/service/api/iml.go @@ -40,85 +40,82 @@ type imlAPIService struct { universally.IServiceDelete } -func (i *imlAPIService) ListInfoForProject(ctx context.Context, project string) ([]*APIInfo, error) { +func (i *imlAPIService) ListInfoForService(ctx context.Context, serviceId string) ([]*Info, error) { apis, err := i.store.List(ctx, map[string]interface{}{ - "project": project, + "service": serviceId, }) aids := utils.SliceToSlice(apis, func(a *api.Api) int64 { return a.Id }) list, err := i.apiInfoStore.List(ctx, map[string]interface{}{ - "project": project, + "service": serviceId, "id": aids, }) if err != nil { return nil, err } - return utils.SliceToSlice(list, func(info *api.Info) *APIInfo { - return &APIInfo{ + return utils.SliceToSlice(list, func(info *api.Info) *Info { + return &Info{ UUID: info.UUID, Name: info.Name, Description: info.Description, CreateAt: info.CreateAt, UpdateAt: info.UpdateAt, - Project: info.Project, + Service: info.Service, Team: info.Team, Creator: info.Creator, Updater: info.Updater, - //Upstream: info.Upstream, - Method: info.Method, - Path: info.Path, - Match: info.Match, + Method: info.Method, + Path: info.Path, + Match: info.Match, } }), nil } -func (i *imlAPIService) ListInfo(ctx context.Context, aids ...string) ([]*APIInfo, error) { +func (i *imlAPIService) ListInfo(ctx context.Context, aids ...string) ([]*Info, error) { list, err := i.apiInfoStore.List(ctx, map[string]interface{}{ "uuid": aids, }) if err != nil { return nil, err } - return utils.SliceToSlice(list, func(info *api.Info) *APIInfo { - return &APIInfo{ + return utils.SliceToSlice(list, func(info *api.Info) *Info { + return &Info{ UUID: info.UUID, Name: info.Name, Description: info.Description, CreateAt: info.CreateAt, UpdateAt: info.UpdateAt, - Project: info.Project, + Service: info.Service, Team: info.Team, Creator: info.Creator, Updater: info.Updater, - //Upstream: info.Upstream, - Method: info.Method, - Path: info.Path, - Match: info.Match, + Method: info.Method, + Path: info.Path, + Match: info.Match, } }), nil } -func (i *imlAPIService) GetInfo(ctx context.Context, aid string) (*APIInfo, error) { +func (i *imlAPIService) GetInfo(ctx context.Context, aid string) (*Info, error) { info, err := i.apiInfoStore.GetByUUID(ctx, aid) if err != nil { return nil, err } - return &APIInfo{ + return &Info{ UUID: info.UUID, Name: info.Name, Description: info.Description, CreateAt: info.CreateAt, UpdateAt: info.UpdateAt, - Project: info.Project, + Service: info.Service, Team: info.Team, Creator: info.Creator, Updater: info.Updater, - //Upstream: info.Upstream, - Method: info.Method, - Path: info.Path, - Match: info.Match, + Method: info.Method, + Path: info.Path, + Match: info.Match, }, nil } @@ -150,7 +147,7 @@ func (i *imlAPIService) Save(ctx context.Context, id string, model *EditAPI) err } func getLabels(input *api.Info, appends ...string) []string { labels := make([]string, 0, len(appends)+9) - labels = append(labels, input.UUID, input.Name, input.Description, input.Method, input.Path, input.Project, input.Team, input.Updater) + labels = append(labels, input.UUID, input.Name, input.Description, input.Method, input.Path, input.Service, input.Team, input.Updater) labels = append(labels, appends...) return labels } @@ -186,7 +183,7 @@ func (i *imlAPIService) Create(ctx context.Context, input *CreateAPI) (err error ne := api.Api{ Id: 0, UUID: input.UUID, - Project: input.Project, + Service: input.Service, Team: input.Team, Creator: operater, CreateAt: time.Now(), @@ -211,7 +208,7 @@ func (i *imlAPIService) Create(ctx context.Context, input *CreateAPI) (err error Method: input.Method, Path: input.Path, Match: input.Match, - Project: input.Project, + Service: input.Service, Team: input.Team, } err = i.apiInfoStore.Save(ctx, ev) @@ -234,9 +231,9 @@ func (i *imlAPIService) ListDocumentCommit(ctx context.Context, commitId ...stri return i.documentCommitService.List(ctx, commitId...) } -func (i *imlAPIService) CountByProject(ctx context.Context, project string) (int64, error) { +func (i *imlAPIService) CountByService(ctx context.Context, service string) (int64, error) { return i.store.CountWhere(ctx, map[string]interface{}{ - "project": project, + "service": service, }) } @@ -257,15 +254,15 @@ func (i *imlAPIService) Exist(ctx context.Context, aid string, a *ExistAPI) erro return nil } -func (i *imlAPIService) ListForProject(ctx context.Context, project string) ([]*API, error) { - list, err := i.listForProject(ctx, project, false) +func (i *imlAPIService) ListForService(ctx context.Context, serviceId string) ([]*API, error) { + list, err := i.listForService(ctx, serviceId, false) if err != nil { return nil, err } return utils.SliceToSlice(list, FromEntity), nil } -func (i *imlAPIService) listForProject(ctx context.Context, project string, isDelete bool) ([]*api.Api, error) { - return i.store.ListQuery(ctx, "project=? and is_delete=?", []interface{}{project, isDelete}, "id") +func (i *imlAPIService) listForService(ctx context.Context, serviceId string, isDelete bool) ([]*api.Api, error) { + return i.store.ListQuery(ctx, "service=? and is_delete=?", []interface{}{serviceId, isDelete}, "id") } func (i *imlAPIService) ListLatestCommitProxy(ctx context.Context, apiUUID ...string) ([]*commit.Commit[Proxy], error) { diff --git a/service/api/model.go b/service/api/model.go index 847977e..23f8159 100644 --- a/service/api/model.go +++ b/service/api/model.go @@ -1,16 +1,16 @@ package api import ( - "github.com/eolinker/apipark/model/plugin_model" "time" + "github.com/eolinker/apipark/model/plugin_model" + "github.com/eolinker/apipark/stores/api" ) type API struct { - UUID string - //Name string - Project string + UUID string + Service string Team string Creator string Method string @@ -19,14 +19,13 @@ type API struct { IsDelete bool } -type APIInfo struct { - //Id int64 +type Info struct { UUID string Name string Description string CreateAt time.Time UpdateAt time.Time - Project string + Service string Team string Creator string Updater string @@ -38,21 +37,14 @@ type APIInfo struct { func FromEntity(e *api.Api) *API { return &API{ - //Id: e.Id, - UUID: e.UUID, - //Name: e.Name, - //Description: e.Description, + UUID: e.UUID, CreateAt: e.CreateAt, IsDelete: e.IsDelete != 0, - //UpdateAt: e.UpdateAt, - Project: e.Project, - Team: e.Team, - Creator: e.Creator, - //Updater: e.Updater, - //Upstream: e.Upstream, - Method: e.Method, - Path: e.Path, - //Match: e.Match, + Service: e.Service, + Team: e.Team, + Creator: e.Creator, + Method: e.Method, + Path: e.Path, } } @@ -60,16 +52,14 @@ type CreateAPI struct { UUID string Name string Description string - Project string + Service string Team string Method string Path string Match string - //Upstream string } type EditAPI struct { - //UUID string Name *string Upstream *string Description *string diff --git a/service/api/service.go b/service/api/service.go index 2aceb0f..e8fdf22 100644 --- a/service/api/service.go +++ b/service/api/service.go @@ -13,14 +13,12 @@ import ( type IAPIService interface { universally.IServiceGet[API] universally.IServiceDelete - //universally.IServiceCreate[CreateAPI] - //universally.IServiceEdit[EditAPI] - CountByProject(ctx context.Context, project string) (int64, error) + CountByService(ctx context.Context, project string) (int64, error) Exist(ctx context.Context, aid string, api *ExistAPI) error - ListForProject(ctx context.Context, project string) ([]*API, error) - GetInfo(ctx context.Context, aid string) (*APIInfo, error) - ListInfo(ctx context.Context, aids ...string) ([]*APIInfo, error) - ListInfoForProject(ctx context.Context, project string) ([]*APIInfo, error) + ListForService(ctx context.Context, serviceId string) ([]*API, error) + GetInfo(ctx context.Context, aid string) (*Info, error) + ListInfo(ctx context.Context, aids ...string) ([]*Info, error) + ListInfoForService(ctx context.Context, serviceId string) ([]*Info, error) ListLatestCommitProxy(ctx context.Context, aid ...string) ([]*commit.Commit[Proxy], error) ListLatestCommitDocument(ctx context.Context, aid ...string) ([]*commit.Commit[Document], error) LatestProxy(ctx context.Context, aid string) (*commit.Commit[Proxy], error) @@ -33,7 +31,6 @@ type IAPIService interface { SaveDocument(ctx context.Context, aid string, data *Document) error Save(ctx context.Context, id string, model *EditAPI) error Create(ctx context.Context, input *CreateAPI) (err error) - //CountByUpstream(ctx context.Context, upstreams ...string) (map[string]int64, error) } var ( diff --git a/service/application-authorization/iml.go b/service/application-authorization/iml.go new file mode 100644 index 0000000..20bd272 --- /dev/null +++ b/service/application-authorization/iml.go @@ -0,0 +1,106 @@ +package application_authorization + +import ( + "context" + "time" + + "github.com/eolinker/go-common/utils" + + "github.com/eolinker/go-common/auto" + + "github.com/eolinker/apipark/service/universally" + "github.com/eolinker/apipark/stores/service" +) + +var ( + _ IAuthorizationService = (*imlAuthorizationService)(nil) +) + +type imlAuthorizationService struct { + store service.IAuthorizationStore `autowired:""` + universally.IServiceGet[Authorization] + universally.IServiceDelete + universally.IServiceCreate[Create] + universally.IServiceEdit[Edit] +} + +func (i *imlAuthorizationService) ListByApp(ctx context.Context, appId ...string) ([]*Authorization, error) { + w := map[string]interface{}{} + if len(appId) > 0 { + w["application"] = appId + } + list, err := i.store.List(ctx, w, "update_at desc") + if err != nil { + return nil, err + } + return utils.SliceToSlice(list, FromEntity), nil +} + +func (i *imlAuthorizationService) GetLabels(ctx context.Context, ids ...string) map[string]string { + if len(ids) == 0 { + return nil + } + list, err := i.store.ListQuery(ctx, "`uuid` in (?)", []interface{}{ids}, "id") + if err != nil { + return nil + } + return utils.SliceToMapO(list, func(i *service.Authorization) (string, string) { + return i.UUID, i.Name + }) +} + +func (i *imlAuthorizationService) OnComplete() { + i.IServiceGet = universally.NewGet[Authorization, service.Authorization](i.store, FromEntity) + + i.IServiceDelete = universally.NewDelete[service.Authorization](i.store) + + i.IServiceCreate = universally.NewCreator[Create, service.Authorization](i.store, "project_authorization", createEntityHandler, uniquestHandler, labelHandler) + + i.IServiceEdit = universally.NewEdit[Edit, service.Authorization](i.store, updateHandler, labelHandler) + auto.RegisterService("project_authorization", i) +} + +func labelHandler(e *service.Authorization) []string { + return []string{e.Name, e.UUID} +} +func uniquestHandler(i *Create) []map[string]interface{} { + return []map[string]interface{}{{"uuid": i.UUID}} +} +func createEntityHandler(i *Create) *service.Authorization { + now := time.Now() + return &service.Authorization{ + UUID: i.UUID, + Name: i.Name, + Application: i.Application, + Type: i.Type, + Position: i.Position, + TokenName: i.TokenName, + Config: i.Config, + ExpireTime: i.ExpireTime, + CreateAt: now, + UpdateAt: now, + HideCredential: i.HideCredential, + } +} + +func updateHandler(e *service.Authorization, i *Edit) { + if i.Name != nil { + e.Name = *i.Name + } + if i.Position != nil { + e.Position = *i.Position + } + if i.TokenName != nil { + e.TokenName = *i.TokenName + } + if i.Config != nil { + e.Config = *i.Config + } + if i.ExpireTime != nil { + e.ExpireTime = *i.ExpireTime + } + if i.HideCredential != nil { + e.HideCredential = *i.HideCredential + } + e.UpdateAt = time.Now() +} diff --git a/service/project-authorization/model.go b/service/application-authorization/model.go similarity index 79% rename from service/project-authorization/model.go rename to service/application-authorization/model.go index d87c105..2448cbc 100644 --- a/service/project-authorization/model.go +++ b/service/application-authorization/model.go @@ -1,14 +1,14 @@ -package project_authorization +package application_authorization import ( "time" - "github.com/eolinker/apipark/stores/project" + "github.com/eolinker/apipark/stores/service" ) type Authorization struct { UUID string - Project string + Application string Name string Type string Position string @@ -22,10 +22,10 @@ type Authorization struct { HideCredential bool } -func FromEntity(e *project.Authorization) *Authorization { +func FromEntity(e *service.Authorization) *Authorization { return &Authorization{ UUID: e.UUID, - Project: e.Project, + Application: e.Application, Name: e.Name, Type: e.Type, Position: e.Position, @@ -40,9 +40,9 @@ func FromEntity(e *project.Authorization) *Authorization { } } -type CreateAuthorization struct { +type Create struct { UUID string - Project string + Application string Name string Type string Position string @@ -53,7 +53,7 @@ type CreateAuthorization struct { HideCredential bool } -type EditAuthorization struct { +type Edit struct { Name *string Position *string TokenName *string diff --git a/service/application-authorization/service.go b/service/application-authorization/service.go new file mode 100644 index 0000000..be1f996 --- /dev/null +++ b/service/application-authorization/service.go @@ -0,0 +1,23 @@ +package application_authorization + +import ( + "context" + "reflect" + + "github.com/eolinker/apipark/service/universally" + "github.com/eolinker/go-common/autowire" +) + +type IAuthorizationService interface { + universally.IServiceGet[Authorization] + universally.IServiceDelete + universally.IServiceCreate[Create] + universally.IServiceEdit[Edit] + ListByApp(ctx context.Context, appId ...string) ([]*Authorization, error) +} + +func init() { + autowire.Auto[IAuthorizationService](func() reflect.Value { + return reflect.ValueOf(new(imlAuthorizationService)) + }) +} diff --git a/service/project-authorization/iml.go b/service/project-authorization/iml.go deleted file mode 100644 index 5c252b9..0000000 --- a/service/project-authorization/iml.go +++ /dev/null @@ -1,106 +0,0 @@ -package project_authorization - -import ( - "context" - "time" - - "github.com/eolinker/go-common/utils" - - "github.com/eolinker/go-common/auto" - - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/apipark/stores/project" -) - -var ( - _ IProjectAuthorizationService = (*imlProjectAuthorizationService)(nil) -) - -type imlProjectAuthorizationService struct { - store project.IAuthorizationStore `autowired:""` - universally.IServiceGet[Authorization] - universally.IServiceDelete - universally.IServiceCreate[CreateAuthorization] - universally.IServiceEdit[EditAuthorization] -} - -func (i *imlProjectAuthorizationService) ListByProject(ctx context.Context, pid ...string) ([]*Authorization, error) { - w := map[string]interface{}{} - if len(pid) > 0 { - w["project"] = pid - } - list, err := i.store.List(ctx, w, "update_at desc") - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, FromEntity), nil -} - -func (i *imlProjectAuthorizationService) GetLabels(ctx context.Context, ids ...string) map[string]string { - if len(ids) == 0 { - return nil - } - list, err := i.store.ListQuery(ctx, "`uuid` in (?)", []interface{}{ids}, "id") - if err != nil { - return nil - } - return utils.SliceToMapO(list, func(i *project.Authorization) (string, string) { - return i.UUID, i.Name - }) -} - -func (i *imlProjectAuthorizationService) OnComplete() { - i.IServiceGet = universally.NewGet[Authorization, project.Authorization](i.store, FromEntity) - - i.IServiceDelete = universally.NewDelete[project.Authorization](i.store) - - i.IServiceCreate = universally.NewCreator[CreateAuthorization, project.Authorization](i.store, "project_authorization", createEntityHandler, uniquestHandler, labelHandler) - - i.IServiceEdit = universally.NewEdit[EditAuthorization, project.Authorization](i.store, updateHandler, labelHandler) - auto.RegisterService("project_authorization", i) -} - -func labelHandler(e *project.Authorization) []string { - return []string{e.Name, e.UUID} -} -func uniquestHandler(i *CreateAuthorization) []map[string]interface{} { - return []map[string]interface{}{{"uuid": i.UUID}} -} -func createEntityHandler(i *CreateAuthorization) *project.Authorization { - now := time.Now() - return &project.Authorization{ - UUID: i.UUID, - Name: i.Name, - Project: i.Project, - Type: i.Type, - Position: i.Position, - TokenName: i.TokenName, - Config: i.Config, - ExpireTime: i.ExpireTime, - CreateAt: now, - UpdateAt: now, - HideCredential: i.HideCredential, - } -} - -func updateHandler(e *project.Authorization, i *EditAuthorization) { - if i.Name != nil { - e.Name = *i.Name - } - if i.Position != nil { - e.Position = *i.Position - } - if i.TokenName != nil { - e.TokenName = *i.TokenName - } - if i.Config != nil { - e.Config = *i.Config - } - if i.ExpireTime != nil { - e.ExpireTime = *i.ExpireTime - } - if i.HideCredential != nil { - e.HideCredential = *i.HideCredential - } - e.UpdateAt = time.Now() -} diff --git a/service/project-authorization/service.go b/service/project-authorization/service.go deleted file mode 100644 index 08a39f7..0000000 --- a/service/project-authorization/service.go +++ /dev/null @@ -1,23 +0,0 @@ -package project_authorization - -import ( - "context" - "reflect" - - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/go-common/autowire" -) - -type IProjectAuthorizationService interface { - universally.IServiceGet[Authorization] - universally.IServiceDelete - universally.IServiceCreate[CreateAuthorization] - universally.IServiceEdit[EditAuthorization] - ListByProject(ctx context.Context, pid ...string) ([]*Authorization, error) -} - -func init() { - autowire.Auto[IProjectAuthorizationService](func() reflect.Value { - return reflect.ValueOf(new(imlProjectAuthorizationService)) - }) -} diff --git a/service/project/iml.go b/service/project/iml.go deleted file mode 100644 index abb98be..0000000 --- a/service/project/iml.go +++ /dev/null @@ -1,129 +0,0 @@ -package project - -import ( - "context" - "fmt" - "time" - - "github.com/eolinker/go-common/utils" - - "github.com/eolinker/go-common/auto" - - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/apipark/stores/project" -) - -var ( - _ IProjectService = (*imlProjectService)(nil) -) - -type imlProjectService struct { - projectStore project.IProjectStore `autowired:""` - universally.IServiceGet[Project] - universally.IServiceDelete - universally.IServiceCreate[CreateProject] - universally.IServiceEdit[EditProject] -} - -func (i *imlProjectService) AppList(ctx context.Context, appIds ...string) ([]*Project, error) { - w := make(map[string]interface{}) - if len(appIds) > 0 { - w["uuid"] = appIds - } - w["as_app"] = true - list, err := i.projectStore.List(ctx, w) - if err != nil { - return nil, err - } - return utils.SliceToSlice(list, FromEntity), nil -} - -func (i *imlProjectService) CheckProject(ctx context.Context, pid string, rule map[string]bool) (*Project, error) { - pro, err := i.Get(ctx, pid) - if err != nil { - return nil, err - } - if rule == nil || len(rule) == 0 { - return pro, nil - } - if rule["as_server"] && !pro.AsServer { - return nil, fmt.Errorf("project %s is not as server", pid) - } - if rule["as_app"] && !pro.AsApp { - return nil, fmt.Errorf("project %s is not as app", pid) - } - return pro, nil -} - -func (i *imlProjectService) CountTeam(ctx context.Context, teamID string, keyword string) (int64, error) { - counts, err := i.projectStore.CountByGroup(ctx, keyword, map[string]interface{}{ - "team": teamID, - "as_server": true, - }, "team") - if err != nil { - return 0, err - } - return counts[teamID], nil -} - -func (i *imlProjectService) CountByTeam(ctx context.Context, keyword string) (map[string]int64, error) { - return i.projectStore.CountByGroup(ctx, keyword, map[string]interface{}{"as_server": true}, "team") -} - -func (i *imlProjectService) GetLabels(ctx context.Context, ids ...string) map[string]string { - if len(ids) == 0 { - return nil - } - list, err := i.projectStore.ListQuery(ctx, "`uuid` in (?)", []interface{}{ids}, "id") - if err != nil { - return nil - } - return utils.SliceToMapO(list, func(i *project.Project) (string, string) { - return i.UUID, i.Name - }) -} - -func (i *imlProjectService) OnComplete() { - i.IServiceGet = universally.NewGetSoftDelete[Project, project.Project](i.projectStore, FromEntity) - - i.IServiceDelete = universally.NewSoftDelete[project.Project](i.projectStore) - - i.IServiceCreate = universally.NewCreatorSoftDelete[CreateProject, project.Project](i.projectStore, "project", createEntityHandler, uniquestHandler, labelHandler) - - i.IServiceEdit = universally.NewEdit[EditProject, project.Project](i.projectStore, updateHandler, labelHandler) - auto.RegisterService("project", i) -} - -func labelHandler(e *project.Project) []string { - return []string{e.Name, e.UUID, e.Description} -} -func uniquestHandler(i *CreateProject) []map[string]interface{} { - return []map[string]interface{}{{"uuid": i.Id}} -} -func createEntityHandler(i *CreateProject) *project.Project { - now := time.Now() - return &project.Project{ - Id: 0, - UUID: i.Id, - Name: i.Name, - CreateAt: now, - UpdateAt: now, - Description: i.Description, - Prefix: i.Prefix, - Team: i.Team, - //Master: i.Master, - AsServer: i.AsServer, - AsApp: i.AsApp, - } -} -func updateHandler(e *project.Project, i *EditProject) { - if i.Name != nil { - e.Name = *i.Name - } - if i.Description != nil { - e.Description = *i.Description - } - //if i.Master != nil { - // e.Master = *i.Master - //} -} diff --git a/service/project/model.go b/service/project/model.go deleted file mode 100644 index cf3b729..0000000 --- a/service/project/model.go +++ /dev/null @@ -1,57 +0,0 @@ -package project - -import ( - "time" - - "github.com/eolinker/apipark/stores/project" -) - -type Project struct { - Id string - Name string - Description string - Team string - //Master string - Prefix string - AsServer bool - AsApp bool - CreateTime time.Time - UpdateTime time.Time -} - -func FromEntity(e *project.Project) *Project { - return &Project{ - Id: e.UUID, - Name: e.Name, - Description: e.Description, - Team: e.Team, - //Master: e.Master, - Prefix: e.Prefix, - AsServer: e.AsServer, - AsApp: e.AsApp, - CreateTime: e.CreateAt, - UpdateTime: e.UpdateAt, - } -} - -type CreateProject struct { - Id string - Name string - Description string - //Master string - Team string - Prefix string - AsServer bool - AsApp bool -} - -type EditProject struct { - Name *string - Description *string - //Master *string -} - -type Partition struct { - Partition string - Project string -} diff --git a/service/project/service.go b/service/project/service.go deleted file mode 100644 index 0044c6a..0000000 --- a/service/project/service.go +++ /dev/null @@ -1,26 +0,0 @@ -package project - -import ( - "context" - "reflect" - - "github.com/eolinker/apipark/service/universally" - "github.com/eolinker/go-common/autowire" -) - -type IProjectService interface { - universally.IServiceGet[Project] - universally.IServiceDelete - universally.IServiceCreate[CreateProject] - universally.IServiceEdit[EditProject] - CountByTeam(ctx context.Context, keyword string) (map[string]int64, error) - CountTeam(ctx context.Context, teamID string, keyword string) (int64, error) - CheckProject(ctx context.Context, pid string, rule map[string]bool) (*Project, error) - AppList(ctx context.Context, appIds ...string) ([]*Project, error) -} - -func init() { - autowire.Auto[IProjectService](func() reflect.Value { - return reflect.ValueOf(new(imlProjectService)) - }) -} diff --git a/service/service-doc/iml.go b/service/service-doc/iml.go new file mode 100644 index 0000000..1c3d831 --- /dev/null +++ b/service/service-doc/iml.go @@ -0,0 +1,60 @@ +package service_doc + +import ( + "context" + "errors" + "time" + + "github.com/eolinker/go-common/utils" + "gorm.io/gorm" + + "github.com/eolinker/apipark/stores/service" +) + +type imlDocService struct { + store service.IServiceDocStore `autowired:""` +} + +func (i *imlDocService) Save(ctx context.Context, input *SaveDoc) error { + info, err := i.Get(ctx, input.Sid) + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + userID := utils.UserId(ctx) + if info != nil { + _, err = i.store.Update(ctx, &service.Doc{ + Id: info.ID, + Sid: input.Sid, + Doc: input.Doc, + CreateAt: info.CreateTime, + UpdateAt: time.Now(), + Creator: info.Creator, + Updater: userID, + }) + return err + } + return i.store.Insert(ctx, &service.Doc{ + Sid: input.Sid, + Doc: input.Doc, + CreateAt: time.Now(), + UpdateAt: time.Now(), + Creator: userID, + Updater: userID, + }) +} + +func (i *imlDocService) Get(ctx context.Context, sid string) (*Doc, error) { + doc, err := i.store.First(ctx, map[string]interface{}{"sid": sid}) + if err != nil { + return nil, err + } + return &Doc{ + ID: doc.Id, + DocID: doc.Sid, + Creator: doc.Creator, + Updater: doc.Updater, + Doc: doc.Doc, + UpdateTime: doc.UpdateAt, + CreateTime: doc.CreateAt, + }, nil +} diff --git a/service/service-doc/model.go b/service/service-doc/model.go new file mode 100644 index 0000000..ef0dd89 --- /dev/null +++ b/service/service-doc/model.go @@ -0,0 +1,19 @@ +package service_doc + +import "time" + +type Doc struct { + ID int64 + DocID string + Name string + Creator string + Updater string + Doc string + UpdateTime time.Time + CreateTime time.Time +} + +type SaveDoc struct { + Sid string + Doc string +} diff --git a/service/service-doc/service.go b/service/service-doc/service.go new file mode 100644 index 0000000..451182d --- /dev/null +++ b/service/service-doc/service.go @@ -0,0 +1,19 @@ +package service_doc + +import ( + "context" + "reflect" + + "github.com/eolinker/go-common/autowire" +) + +type IDocService interface { + Get(ctx context.Context, sid string) (*Doc, error) + Save(ctx context.Context, input *SaveDoc) error +} + +func init() { + autowire.Auto[IDocService](func() reflect.Value { + return reflect.ValueOf(new(imlDocService)) + }) +} diff --git a/service/service-tag/iml.go b/service/service-tag/iml.go new file mode 100644 index 0000000..2e9957e --- /dev/null +++ b/service/service-tag/iml.go @@ -0,0 +1,54 @@ +package service_tag + +import ( + "context" + + "github.com/eolinker/apipark/stores/service" + "github.com/eolinker/go-common/utils" +) + +type imlTagService struct { + store service.IServiceTagStore `autowired:""` +} + +func (i *imlTagService) List(ctx context.Context, sids []string, tids []string) ([]*Tag, error) { + condition := make(map[string]interface{}) + if len(sids) > 0 { + condition["sid"] = sids + } + if len(tids) > 0 { + condition["tid"] = tids + } + result, err := i.store.List(ctx, condition) + if err != nil { + return nil, err + } + return utils.SliceToSlice(result, func(s *service.Tag) *Tag { + return &Tag{ + Tid: s.Tid, + Sid: s.Sid, + } + }), nil +} + +func (i *imlTagService) Delete(ctx context.Context, tids []string, sids []string) error { + if len(tids) == 0 && len(sids) == 0 { + return nil + } + conditions := make(map[string]interface{}) + if len(tids) > 0 { + conditions["tid"] = tids + } + if len(sids) > 0 { + conditions["sid"] = sids + } + _, err := i.store.DeleteWhere(ctx, conditions) + return err +} + +func (i *imlTagService) Create(ctx context.Context, input *CreateTag) error { + return i.store.Insert(ctx, &service.Tag{ + Sid: input.Sid, + Tid: input.Tid, + }) +} diff --git a/service/service-tag/model.go b/service/service-tag/model.go new file mode 100644 index 0000000..44a639b --- /dev/null +++ b/service/service-tag/model.go @@ -0,0 +1,11 @@ +package service_tag + +type CreateTag struct { + Tid string + Sid string +} + +type Tag struct { + Tid string + Sid string +} diff --git a/service/service-tag/service.go b/service/service-tag/service.go new file mode 100644 index 0000000..b09afc3 --- /dev/null +++ b/service/service-tag/service.go @@ -0,0 +1,20 @@ +package service_tag + +import ( + "context" + "reflect" + + "github.com/eolinker/go-common/autowire" +) + +type ITagService interface { + Delete(ctx context.Context, tids []string, sids []string) error + Create(ctx context.Context, input *CreateTag) error + List(ctx context.Context, sids []string, tids []string) ([]*Tag, error) +} + +func init() { + autowire.Auto[ITagService](func() reflect.Value { + return reflect.ValueOf(new(imlTagService)) + }) +} diff --git a/service/service/iml.go b/service/service/iml.go index 1ff5f05..cc0013e 100644 --- a/service/service/iml.go +++ b/service/service/iml.go @@ -2,82 +2,77 @@ package service import ( "context" - "errors" + "fmt" "time" "github.com/eolinker/go-common/utils" "github.com/eolinker/go-common/auto" - "gorm.io/gorm" - - "github.com/eolinker/apipark/stores/service" - "github.com/eolinker/apipark/service/universally" + "github.com/eolinker/apipark/stores/service" ) var ( - _ IServiceService = (*imlServiceService)(nil) - _ IPartitionsService = (*imlPartitionsService)(nil) - _ ITagService = (*imlTagService)(nil) - _ IDocService = (*imlDocService)(nil) - _ IApiService = (*imlApiService)(nil) + _ IServiceService = (*imlServiceService)(nil) ) type imlServiceService struct { store service.IServiceStore `autowired:""` universally.IServiceGet[Service] universally.IServiceDelete - universally.IServiceCreate[CreateService] - universally.IServiceEdit[EditService] + universally.IServiceCreate[Create] + universally.IServiceEdit[Edit] } -func (i *imlServiceService) SearchByUuids(ctx context.Context, keyword string, uuids ...string) ([]*Service, error) { - w := make(map[string]interface{}) - if len(uuids) > 0 { - w["uuid"] = uuids +func (i *imlServiceService) ServiceCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) { + w := map[string]interface{}{ + "as_server": true, } - services, err := i.store.Search(ctx, keyword, w) - if err != nil { - return nil, err + if len(teamId) > 0 { + w["team"] = teamId } - return utils.SliceToSlice(services, FromEntity), nil + return i.store.CountByGroup(ctx, "", w, "team") } -func (i *imlServiceService) ListByProject(ctx context.Context, pids ...string) ([]*Service, error) { +func (i *imlServiceService) AppCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) { + w := map[string]interface{}{ + "as_app": true, + } + if len(teamId) > 0 { + w["team"] = teamId + } + return i.store.CountByGroup(ctx, "", w, "team") +} + +func (i *imlServiceService) AppList(ctx context.Context, appIds ...string) ([]*Service, error) { w := make(map[string]interface{}) - if len(pids) > 0 { - w["project"] = pids + if len(appIds) > 0 { + w["uuid"] = appIds } - sorts := []string{"update_at desc", "name asc"} - services, err := i.store.List(ctx, w, sorts...) + w["as_app"] = true + list, err := i.store.List(ctx, w) if err != nil { return nil, err } - return utils.SliceToSlice(services, FromEntity), nil + return utils.SliceToSlice(list, FromEntity), nil } -func (i *imlServiceService) SearchServicePage(ctx context.Context, input SearchServicePage, sort ...string) ([]*Service, int64, error) { - condition := make(map[string]interface{}) - - if len(input.Uuids) > 0 { - condition["uuid"] = input.Uuids +func (i *imlServiceService) Check(ctx context.Context, id string, rule map[string]bool) (*Service, error) { + pro, err := i.Get(ctx, id) + if err != nil { + return nil, err } - if len(input.Catalogue) > 0 { - condition["catalogue"] = input.Catalogue + if rule == nil || len(rule) == 0 { + return pro, nil } - - if len(sort) == 0 { - sort = []string{"update_at desc", "name asc"} + if rule["as_server"] && !pro.AsServer { + return nil, fmt.Errorf("project %s is not as server", id) } - - condition["status"] = "on" - condition["service_type"] = "public" - items, total, err := i.store.SearchByPage(ctx, input.Keyword, condition, input.Page, input.Size, sort...) - if err != nil { - return nil, 0, err + if rule["as_app"] && !pro.AsApp { + return nil, fmt.Errorf("project %s is not as app", id) } - return utils.SliceToSlice(items, FromEntity), total, nil + return pro, nil } func (i *imlServiceService) GetLabels(ctx context.Context, ids ...string) map[string]string { @@ -95,273 +90,49 @@ func (i *imlServiceService) GetLabels(ctx context.Context, ids ...string) map[st func (i *imlServiceService) OnComplete() { i.IServiceGet = universally.NewGetSoftDelete[Service, service.Service](i.store, FromEntity) - i.IServiceCreate = universally.NewCreatorSoftDelete[CreateService, service.Service](i.store, "service", createEntityHandler, uniquestHandler, labelHandler) + i.IServiceDelete = universally.NewSoftDelete[service.Service](i.store) - i.IServiceEdit = universally.NewEdit[EditService, service.Service](i.store, updateHandler, labelHandler) + + i.IServiceCreate = universally.NewCreatorSoftDelete[Create, service.Service](i.store, "service", createEntityHandler, uniquestHandler, labelHandler) + + i.IServiceEdit = universally.NewEdit[Edit, service.Service](i.store, updateHandler, labelHandler) auto.RegisterService("service", i) } func labelHandler(e *service.Service) []string { - return []string{e.Name, e.UUID, e.Tag} + return []string{e.Name, e.UUID, e.Description} } -func uniquestHandler(i *CreateService) []map[string]interface{} { - return []map[string]interface{}{{"uuid": i.Uuid}} +func uniquestHandler(i *Create) []map[string]interface{} { + return []map[string]interface{}{{"uuid": i.Id}} } -func createEntityHandler(i *CreateService) *service.Service { +func createEntityHandler(i *Create) *service.Service { now := time.Now() return &service.Service{ - UUID: i.Uuid, + Id: 0, + UUID: i.Id, Name: i.Name, - Description: i.Description, - Logo: i.Logo, - ServiceType: i.ServiceType, - Project: i.Project, - Team: i.Team, - Catalogue: i.Catalogue, - Status: i.Status, - Tag: i.Tag, CreateAt: now, UpdateAt: now, + Description: i.Description, + Prefix: i.Prefix, + Team: i.Team, + ServiceType: i.ServiceType.Int(), + AsServer: i.AsServer, + AsApp: i.AsApp, } } -func updateHandler(e *service.Service, i *EditService) { +func updateHandler(e *service.Service, i *Edit) { if i.Name != nil { e.Name = *i.Name } if i.Description != nil { e.Description = *i.Description } - if i.Logo != nil { - e.Logo = *i.Logo - } if i.ServiceType != nil { - e.ServiceType = *i.ServiceType - } - if i.Catalogue != nil { - e.Catalogue = *i.Catalogue + e.ServiceType = (*i.ServiceType).Int() } - if i.Status != nil { - e.Status = *i.Status - } - if i.Tag != nil { - e.Tag = *i.Tag - } - e.UpdateAt = time.Now() -} - -type imlPartitionsService struct { - store service.IServicePartitionStore `autowired:""` -} - -func (i *imlPartitionsService) PartitionsByService(ctx context.Context, sids ...string) (map[string][]string, error) { - condition := make(map[string]interface{}) - if len(sids) > 0 { - condition["sid"] = sids - } - list, err := i.store.List(ctx, condition) - if err != nil { - return nil, err - } - result := make(map[string][]string) - for _, v := range list { - if _, ok := result[v.Sid]; !ok { - result[v.Sid] = []string{} - } - result[v.Sid] = append(result[v.Sid], v.Pid) - } - return result, nil -} - -func (i *imlPartitionsService) List(ctx context.Context, sid string) ([]*Partition, error) { - partitions, err := i.store.List(ctx, map[string]interface{}{"sid": sid}) - if err != nil { - return nil, err - } - return utils.SliceToSlice(partitions, func(p *service.Partition) *Partition { - return &Partition{ - Pid: p.Pid, - Sid: p.Sid, - } - }), nil - -} - -func (i *imlPartitionsService) Delete(ctx context.Context, pidList []string, sids []string) error { - if len(pidList) == 0 && len(sids) == 0 { - return nil - } - conditions := make(map[string]interface{}) - if len(pidList) > 0 { - conditions["pid"] = pidList - } - if len(sids) > 0 { - conditions["sid"] = sids - } - _, err := i.store.DeleteWhere(ctx, conditions) - return err -} - -func (i *imlPartitionsService) Create(ctx context.Context, input *CreatePartition) error { - return i.store.Insert(ctx, &service.Partition{ - Sid: input.Sid, - Pid: input.Pid, - }) -} - -type imlTagService struct { - store service.IServiceTagStore `autowired:""` -} - -func (i *imlTagService) List(ctx context.Context, sids []string, tids []string) ([]*Tag, error) { - condition := make(map[string]interface{}) - if len(sids) > 0 { - condition["sid"] = sids - } - if len(tids) > 0 { - condition["tid"] = tids - } - result, err := i.store.List(ctx, condition) - if err != nil { - return nil, err - } - return utils.SliceToSlice(result, func(s *service.Tag) *Tag { - return &Tag{ - Tid: s.Tid, - Sid: s.Sid, - } - }), nil -} - -func (i *imlTagService) Delete(ctx context.Context, tids []string, sids []string) error { - if len(tids) == 0 && len(sids) == 0 { - return nil - } - conditions := make(map[string]interface{}) - if len(tids) > 0 { - conditions["tid"] = tids - } - if len(sids) > 0 { - conditions["sid"] = sids - } - _, err := i.store.DeleteWhere(ctx, conditions) - return err -} - -func (i *imlTagService) Create(ctx context.Context, input *CreateTag) error { - return i.store.Insert(ctx, &service.Tag{ - Sid: input.Sid, - Tid: input.Tid, - }) -} - -type imlDocService struct { - store service.IServiceDocStore `autowired:""` -} - -func (i *imlDocService) Save(ctx context.Context, input *SaveDoc) error { - info, err := i.Get(ctx, input.Sid) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - userID := utils.UserId(ctx) - if info != nil { - _, err = i.store.Update(ctx, &service.Doc{ - Id: info.ID, - Sid: input.Sid, - Doc: input.Doc, - CreateAt: info.CreateTime, - UpdateAt: time.Now(), - Creator: info.Creator, - Updater: userID, - }) - return err - } - return i.store.Insert(ctx, &service.Doc{ - Sid: input.Sid, - Doc: input.Doc, - CreateAt: time.Now(), - UpdateAt: time.Now(), - Creator: userID, - Updater: userID, - }) -} - -func (i *imlDocService) Get(ctx context.Context, sid string) (*Doc, error) { - doc, err := i.store.First(ctx, map[string]interface{}{"sid": sid}) - if err != nil { - return nil, err - } - return &Doc{ - ID: doc.Id, - DocID: doc.Sid, - Creator: doc.Creator, - Updater: doc.Updater, - Doc: doc.Doc, - UpdateTime: doc.UpdateAt, - CreateTime: doc.CreateAt, - }, nil -} - -func (i *imlDocService) OnComplete() { -} - -type imlApiService struct { - store service.IServiceApiStore `autowired:""` -} - -func (i *imlApiService) CountBySids(ctx context.Context, sids ...string) (map[string]int64, error) { - wm := make(map[string]interface{}) - if len(sids) > 0 { - wm["sid"] = sids - } - return i.store.CountByGroup(ctx, "", wm, "sid") -} - -func (i *imlApiService) Count(ctx context.Context, sid string) (int64, error) { - return i.store.CountWhere(ctx, map[string]interface{}{"sid": sid}) -} - -func (i *imlApiService) LastSortIndex(ctx context.Context, sid string) (int, error) { - result, err := i.store.FirstQuery(ctx, "sid = ?", []interface{}{sid}, "sort desc") - if err != nil { - return 0, err - } - return result.Sort, nil -} - -func (i *imlApiService) Bind(ctx context.Context, sid string, aid string, sort int) error { - return i.store.Insert(ctx, &service.Api{ - Sid: sid, - Aid: aid, - Sort: sort, - }) -} - -func (i *imlApiService) Unbind(ctx context.Context, sid string, aid string) error { - _, err := i.store.DeleteWhere(ctx, map[string]interface{}{"sid": sid, "aid": aid}) - return err -} - -func (i *imlApiService) List(ctx context.Context, sids ...string) ([]*Api, error) { - if len(sids) == 0 { - return nil, nil - } - apis, err := i.store.List(ctx, map[string]interface{}{"sid": sids}, "sort asc") - if err != nil { - return nil, err - } - result := make([]*Api, 0, len(apis)) - for _, api := range apis { - result = append(result, &Api{ - Aid: api.Aid, - Sid: api.Sid, - Sort: api.Sort, - }) + if i.Logo != nil { + e.Logo = *i.Logo } - return result, nil -} -func (i *imlApiService) Clear(ctx context.Context, sid string) error { - _, err := i.store.DeleteWhere(ctx, map[string]interface{}{"sid": sid}) - return err } diff --git a/service/service/model.go b/service/service/model.go index ab44562..1c94c3b 100644 --- a/service/service/model.go +++ b/service/service/model.go @@ -6,21 +6,45 @@ import ( "github.com/eolinker/apipark/stores/service" ) -const ( - StatusOn = "on" - StatusOff = "off" -) +type ServiceType string + +func (s ServiceType) String() string { + return string(s) +} + +func (s ServiceType) Int() int { + switch s { + case "inner": + return 1 + case "public": + return 2 + default: + return 0 + } +} + +func ToServiceType(s int) ServiceType { + + switch s { + case 1: + return "inner" + case 2: + return "public" + default: + return "unknown" + } +} type Service struct { Id string Name string Description string - Logo string - ServiceType string - Project string Team string - Catalogue string - Status string + Prefix string + Logo string + ServiceType ServiceType + AsServer bool + AsApp bool CreateTime time.Time UpdateTime time.Time } @@ -30,87 +54,36 @@ func FromEntity(e *service.Service) *Service { Id: e.UUID, Name: e.Name, Description: e.Description, - Logo: e.Logo, - ServiceType: e.ServiceType, - Project: e.Project, Team: e.Team, - Catalogue: e.Catalogue, - Status: e.Status, + Prefix: e.Prefix, + Logo: e.Logo, + ServiceType: ToServiceType(e.ServiceType), + AsServer: e.AsServer, + AsApp: e.AsApp, CreateTime: e.CreateAt, UpdateTime: e.UpdateAt, } } -type CreateService struct { - Uuid string +type Create struct { + Id string Name string Description string - Logo string - ServiceType string - Project string Team string - Catalogue string - Status string - Tag string + Prefix string + ServiceType ServiceType + AsServer bool + AsApp bool } -type EditService struct { - Uuid string +type Edit struct { Name *string Description *string + ServiceType *ServiceType Logo *string - ServiceType *string - Catalogue *string - Status *string - Tag *string -} - -type SearchServicePage struct { - Keyword string - Page int - Size int - Catalogue []string - Uuids []string } type CreateTag struct { Tid string Sid string } - -type CreatePartition struct { - Pid string - Sid string -} - -type Partition struct { - Pid string - Sid string -} - -type Doc struct { - ID int64 - DocID string - Name string - Creator string - Updater string - Doc string - UpdateTime time.Time - CreateTime time.Time -} - -type SaveDoc struct { - Sid string - Doc string -} - -type Api struct { - Sid string - Aid string - Sort int -} - -type Tag struct { - Tid string - Sid string -} diff --git a/service/service/service.go b/service/service/service.go index 5fef046..dcbaf9c 100644 --- a/service/service/service.go +++ b/service/service/service.go @@ -11,59 +11,16 @@ import ( type IServiceService interface { universally.IServiceGet[Service] universally.IServiceDelete - universally.IServiceCreate[CreateService] - universally.IServiceEdit[EditService] - SearchServicePage(ctx context.Context, input SearchServicePage, sort ...string) ([]*Service, int64, error) - ListByProject(ctx context.Context, pid ...string) ([]*Service, error) - SearchByUuids(ctx context.Context, keyword string, uuids ...string) ([]*Service, error) -} - -type IPartitionsService interface { - Delete(ctx context.Context, pids []string, sids []string) error - Create(ctx context.Context, input *CreatePartition) error - List(ctx context.Context, sid string) ([]*Partition, error) - PartitionsByService(ctx context.Context, sids ...string) (map[string][]string, error) -} - -type ITagService interface { - Delete(ctx context.Context, tids []string, sids []string) error - Create(ctx context.Context, input *CreateTag) error - List(ctx context.Context, sids []string, tids []string) ([]*Tag, error) -} - -type IDocService interface { - Get(ctx context.Context, sid string) (*Doc, error) - Save(ctx context.Context, input *SaveDoc) error -} - -type IApiService interface { - Bind(ctx context.Context, sid string, aid string, sort int) error - Unbind(ctx context.Context, sid string, aid string) error - List(ctx context.Context, sids ...string) ([]*Api, error) - Count(ctx context.Context, sid string) (int64, error) - CountBySids(ctx context.Context, sids ...string) (map[string]int64, error) - Clear(ctx context.Context, sid string) error - LastSortIndex(ctx context.Context, sid string) (int, error) + universally.IServiceCreate[Create] + universally.IServiceEdit[Edit] + ServiceCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) + AppCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) + Check(ctx context.Context, id string, rule map[string]bool) (*Service, error) + AppList(ctx context.Context, appIds ...string) ([]*Service, error) } func init() { autowire.Auto[IServiceService](func() reflect.Value { return reflect.ValueOf(new(imlServiceService)) }) - - autowire.Auto[IPartitionsService](func() reflect.Value { - return reflect.ValueOf(new(imlPartitionsService)) - }) - - autowire.Auto[ITagService](func() reflect.Value { - return reflect.ValueOf(new(imlTagService)) - }) - - autowire.Auto[IDocService](func() reflect.Value { - return reflect.ValueOf(new(imlDocService)) - }) - - autowire.Auto[IApiService](func() reflect.Value { - return reflect.ValueOf(new(imlApiService)) - }) } diff --git a/service/subscribe/iml.go b/service/subscribe/iml.go index 899d88f..e6da918 100644 --- a/service/subscribe/iml.go +++ b/service/subscribe/iml.go @@ -251,7 +251,6 @@ func (i *imlSubscribeApplyService) createEntityHandler(t *CreateApply) *subscrib return &subscribe.Apply{ Uuid: t.Uuid, Service: t.Service, - Project: t.Project, Team: t.Team, Application: t.Application, ApplyTeam: t.ApplyTeam, diff --git a/service/subscribe/model.go b/service/subscribe/model.go index a51c0d4..863f782 100644 --- a/service/subscribe/model.go +++ b/service/subscribe/model.go @@ -50,7 +50,6 @@ func FromEntity(e *subscribe.Subscribe) *Subscribe { type CreateApply struct { Uuid string Service string - Project string Team string Application string ApplyTeam string diff --git a/stores/api/model.go b/stores/api/model.go index d814114..c245b21 100644 --- a/stores/api/model.go +++ b/stores/api/model.go @@ -7,7 +7,7 @@ type Api struct { UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` Driver string `gorm:"size:36;not null;column:driver;comment:驱动;index:driver"` // 驱动 - Project string `gorm:"size:36;not null;column:project;comment:项目;index:project"` // 项目id + Service string `gorm:"size:36;not null;column:service;comment:服务;index:service"` // 服务 Team string `gorm:"size:36;not null;column:team;comment:团队;index:team"` // 团队id Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator" aovalue:"creator"` // 创建人 CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` @@ -16,20 +16,19 @@ type Api struct { Path string `gorm:"size:512;not null;column:path;comment:请求路径"` } type Info struct { - Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"size:255;not null;column:description;comment:description"` - Project string `gorm:"size:36;not null;column:project;comment:项目;index:project"` // 项目id - Team string `gorm:"size:36;not null;column:team;comment:团队;index:team"` // 团队id - //Upstream string `gorm:"size:36;not null;column:upstream;comment:上游id;index:upstream"` - Method string `gorm:"size:36;not null;column:method;comment:请求方法"` - Path string `gorm:"size:512;not null;column:path;comment:请求路径"` - Match string `gorm:"type:text;null;column:match;comment:匹配规则"` - Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator" aovalue:"creator"` // 创建人 - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - Updater string `gorm:"size:36;not null;column:updater;comment:更新人;index:updater" aovalue:"updater"` // 更新人 - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` + Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Description string `gorm:"size:255;not null;column:description;comment:description"` + Service string `gorm:"size:36;not null;column:service;comment:服务;index:service"` + Team string `gorm:"size:36;not null;column:team;comment:团队;index:team"` // 团队id + Method string `gorm:"size:36;not null;column:method;comment:请求方法"` + Path string `gorm:"size:512;not null;column:path;comment:请求路径"` + Match string `gorm:"type:text;null;column:match;comment:匹配规则"` + Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator" aovalue:"creator"` // 创建人 + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + Updater string `gorm:"size:36;not null;column:updater;comment:更新人;index:updater" aovalue:"updater"` // 更新人 + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:update_at;comment:更新时间"` } func (i *Info) TableName() string { diff --git a/stores/project/model.go b/stores/project/model.go deleted file mode 100644 index efc8b64..0000000 --- a/stores/project/model.go +++ /dev/null @@ -1,50 +0,0 @@ -package project - -import "time" - -type Project struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - - Description string `gorm:"size:255;not null;column:description;comment:description"` - Prefix string `gorm:"size:255;not null;column:prefix;comment:前缀"` - Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` - IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` - AsServer bool `gorm:"type:tinyint(1);not null;column:as_server;comment:是否为服务端项目"` - AsApp bool `gorm:"type:tinyint(1);not null;column:as_app;comment:是否为应用项目"` -} - -func (p *Project) IdValue() int64 { - return p.Id -} -func (p *Project) TableName() string { - return "project" -} - -type Authorization struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - UUID string `gorm:"size:36;not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"size:100;not null;column:name;comment:名称"` - Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project"` - Type string `gorm:"size:100;not null;column:type;comment:类型"` - Position string `gorm:"size:100;not null;column:position;comment:位置"` - TokenName string `gorm:"size:100;not null;column:token_name;comment:token名称"` - Config string `gorm:"type:text;not null;column:config;comment:配置"` - Creator string `gorm:"size:36;not null;column:creator;comment:创建者" aovalue:"creator"` - Updater string `gorm:"size:36;not null;column:updater;comment:修改者" aovalue:"updater"` - ExpireTime int64 `gorm:"type:BIGINT(20);not null;column:expire_time;comment:过期时间"` - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` - HideCredential bool `gorm:"type:tinyint(1);not null;column:hide_credential;comment:隐藏凭证"` -} - -func (a *Authorization) IdValue() int64 { - return a.Id -} - -func (a *Authorization) TableName() string { - return "project_authorization" -} diff --git a/stores/project/store.go b/stores/project/store.go deleted file mode 100644 index 9643e15..0000000 --- a/stores/project/store.go +++ /dev/null @@ -1,47 +0,0 @@ -package project - -import ( - "github.com/eolinker/ap-account/store/member" - "github.com/eolinker/go-common/autowire" - "github.com/eolinker/go-common/store" -) -import "reflect" - -type IProjectStore interface { - store.ISearchStore[Project] -} -type imlProjectStore struct { - store.SearchStore[Project] -} - -type IMemberStore member.IMemberStore - -//type IMemberRoleStore interface { -// store.IBaseStore[MemberRole] -//} -//type imlMemberRoleStore struct { -// store.Store[MemberRole] -//} - -type IAuthorizationStore interface { - store.ISearchStore[Authorization] -} - -type imlAuthorizationStore struct { - store.SearchStore[Authorization] -} - -func init() { - autowire.Auto[IProjectStore](func() reflect.Value { - return reflect.ValueOf(new(imlProjectStore)) - }) - autowire.Auto[IMemberStore](func() reflect.Value { - return reflect.ValueOf(member.NewMemberStore("project")) - }) - //autowire.Auto[IMemberRoleStore](func() reflect.Value { - // return reflect.ValueOf(new(imlMemberRoleStore)) - //}) - autowire.Auto[IAuthorizationStore](func() reflect.Value { - return reflect.ValueOf(new(imlAuthorizationStore)) - }) -} diff --git a/stores/service/model.go b/stores/service/model.go index 5ad4350..d069bd5 100644 --- a/stores/service/model.go +++ b/stores/service/model.go @@ -3,43 +3,52 @@ package service import "time" type Service struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"type:varchar(255);not null;column:description;comment:描述"` - Logo string `gorm:"type:text;column:logo;comment:logo"` - ServiceType string `gorm:"type:varchar(36);not null;column:service_type;comment:服务类型"` - Project string `gorm:"type:varchar(36);not null;column:project;comment:项目"` - Team string `gorm:"type:varchar(36);not null;column:team;comment:团队"` - Catalogue string `gorm:"type:varchar(36);not null;column:catalogue;comment:目录"` - Status string `gorm:"type:varchar(36);not null;column:status;comment:状态"` - Tag string `gorm:"type:varchar(255);not null;column:tag;comment:标签"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + + Description string `gorm:"size:255;not null;column:description;comment:description"` + Prefix string `gorm:"size:255;not null;column:prefix;comment:前缀"` + Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id + Logo string `gorm:"type:text;not null;column:logo;comment:logo"` + ServiceType int `gorm:"type:int(11);not null;column:service_type;comment:服务类型"` CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - Creator string `gorm:"type:varchar(36);not null;column:creator;comment:创建者" aovalue:"creator"` - Updater string `gorm:"type:varchar(36);not null;column:updater;comment:修改者" aovalue:"updater"` - IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除 0:未删除 1:已删除"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` + IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` + AsServer bool `gorm:"type:tinyint(1);not null;column:as_server;comment:是否为服务端项目"` + AsApp bool `gorm:"type:tinyint(1);not null;column:as_app;comment:是否为应用项目"` } -func (o *Service) TableName() string { +func (p *Service) IdValue() int64 { + return p.Id +} +func (p *Service) TableName() string { return "service" } -func (o *Service) IdValue() int64 { - return o.Id +type Authorization struct { + Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` + UUID string `gorm:"size:36;not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"size:100;not null;column:name;comment:名称"` + Application string `gorm:"size:100;not null;column:application;comment:应用"` + Type string `gorm:"size:100;not null;column:type;comment:类型"` + Position string `gorm:"size:100;not null;column:position;comment:位置"` + TokenName string `gorm:"size:100;not null;column:token_name;comment:token名称"` + Config string `gorm:"type:text;not null;column:config;comment:配置"` + Creator string `gorm:"size:36;not null;column:creator;comment:创建者" aovalue:"creator"` + Updater string `gorm:"size:36;not null;column:updater;comment:修改者" aovalue:"updater"` + ExpireTime int64 `gorm:"type:BIGINT(20);not null;column:expire_time;comment:过期时间"` + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` + HideCredential bool `gorm:"type:tinyint(1);not null;column:hide_credential;comment:隐藏凭证"` } -type Partition struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - Sid string `gorm:"size:36;not null;column:sid;comment:服务id;uniqueIndex:sid_pid; index:sid;"` - Pid string `gorm:"size:36;not null;column:pid;comment:分区id;uniqueIndex:sid_pid;index:pid;"` +func (a *Authorization) IdValue() int64 { + return a.Id } -func (p *Partition) IdValue() int64 { - return p.Id -} -func (p *Partition) TableName() string { - return "server_partition" +func (a *Authorization) TableName() string { + return "service_authorization" } type Tag struct { @@ -73,17 +82,3 @@ func (d *Doc) IdValue() int64 { func (d *Doc) TableName() string { return "server_doc" } - -type Api struct { - Id int64 `gorm:"type:BIGINT(20);size:20;not null;auto_increment;primary_key;column:id;comment:主键ID;"` - Sid string `gorm:"size:36;not null;column:sid;uniqueIndex:sid_api;index:sid;comment:服务id;"` - Aid string `gorm:"size:36;not null;column:aid;uniqueIndex:sid_api;comment:api id;index:api;"` - Sort int `gorm:"type:int;not null;column:sort;comment:排序"` -} - -func (a *Api) IdValue() int64 { - return a.Id -} -func (a *Api) TableName() string { - return "service_api" -} diff --git a/stores/service/store.go b/stores/service/store.go index a6ec391..8c24fc1 100644 --- a/stores/service/store.go +++ b/stores/service/store.go @@ -1,26 +1,16 @@ package service import ( - "reflect" - "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/store" ) +import "reflect" type IServiceStore interface { store.ISearchStore[Service] } - type imlServiceStore struct { - store.SearchStoreSoftDelete[Service] -} - -type IServicePartitionStore interface { - store.IBaseStore[Partition] -} - -type imlServicePartitionStore struct { - store.Store[Partition] + store.SearchStore[Service] } type IServiceTagStore interface { @@ -39,23 +29,21 @@ type imlServiceDocStore struct { store.SearchStore[Doc] } -type IServiceApiStore interface { - store.IBaseStore[Api] +type IAuthorizationStore interface { + store.ISearchStore[Authorization] } -type imlServiceApiStore struct { - store.Store[Api] +type imlAuthorizationStore struct { + store.SearchStore[Authorization] } func init() { autowire.Auto[IServiceStore](func() reflect.Value { return reflect.ValueOf(new(imlServiceStore)) }) - - autowire.Auto[IServicePartitionStore](func() reflect.Value { - return reflect.ValueOf(new(imlServicePartitionStore)) + autowire.Auto[IAuthorizationStore](func() reflect.Value { + return reflect.ValueOf(new(imlAuthorizationStore)) }) - autowire.Auto[IServiceTagStore](func() reflect.Value { return reflect.ValueOf(new(imlServiceTagStore)) }) @@ -64,7 +52,4 @@ func init() { return reflect.ValueOf(new(imlServiceDocStore)) }) - autowire.Auto[IServiceApiStore](func() reflect.Value { - return reflect.ValueOf(new(imlServiceApiStore)) - }) } From a25aa2615f473fae46bbaa01ea006ad8fe5b4536 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 1 Aug 2024 12:16:20 +0800 Subject: [PATCH 06/19] =?UTF-8?q?=E5=8F=91=E5=B8=83=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/api/api.go | 2 +- controller/api/iml.go | 6 +- controller/publish/iml.go | 51 +++--- controller/publish/publish.go | 24 +-- controller/release/iml.go | 6 +- controller/release/release.go | 8 +- controller/upstream/iml.go | 8 +- controller/upstream/upstream.go | 4 +- module/catalogue/iml.go | 2 +- module/project_diff/diff.go | 24 --- module/publish/dto/diff.go | 6 +- module/publish/dto/out.go | 10 +- module/publish/iml.go | 150 +++++++++++------- module/publish/module.go | 19 +-- module/release/dto/release.go | 8 +- module/release/iml.go | 26 +-- module/release/module.go | 15 +- module/service-diff/diff.go | 25 +++ module/{project_diff => service-diff}/iml.go | 110 +++++-------- module/{project_diff => service-diff}/out.go | 15 +- module/upstream/iml.go | 8 +- plugins/core/release.go | 13 +- plugins/core/upstream.go | 4 +- plugins/publish_flow/apis.go | 23 +-- service/cluster/cluster.go | 31 ++-- service/publish/diff.go | 6 +- service/publish/iml.go | 46 +++--- service/publish/model.go | 9 +- service/publish/service.go | 6 +- service/release/iml.go | 34 ++-- service/release/model.go | 4 +- .../{project_diff => service_diff}/diff.go | 12 +- .../{project_diff => service_diff}/type.go | 2 +- stores/publish/model.go | 10 +- stores/release/release.go | 2 +- stores/release/runtime.go | 4 +- 36 files changed, 381 insertions(+), 352 deletions(-) delete mode 100644 module/project_diff/diff.go create mode 100644 module/service-diff/diff.go rename module/{project_diff => service-diff}/iml.go (73%) rename module/{project_diff => service-diff}/out.go (75%) rename service/{project_diff => service_diff}/diff.go (76%) rename service/{project_diff => service_diff}/type.go (97%) diff --git a/controller/api/api.go b/controller/api/api.go index dd3f64f..f7d160d 100644 --- a/controller/api/api.go +++ b/controller/api/api.go @@ -19,7 +19,7 @@ type IAPIController interface { Search(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiItem, error) // SimpleSearch 获取API简要列表 SimpleSearch(ctx *gin.Context, keyword string, serviceId string) ([]*api_dto.ApiSimpleItem, error) - SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) + //SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) // Create 创建API Create(ctx *gin.Context, serviceId string, dto *api_dto.CreateApi) (*api_dto.ApiSimpleDetail, error) // Edit 编辑API diff --git a/controller/api/iml.go b/controller/api/iml.go index d3ed567..4964b53 100644 --- a/controller/api/iml.go +++ b/controller/api/iml.go @@ -12,9 +12,9 @@ type imlAPIController struct { module api.IApiModule `autowired:""` } -func (i *imlAPIController) SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) { - return i.module.SimpleList(ctx, serviceId) -} +//func (i *imlAPIController) SimpleList(ctx *gin.Context, serviceId string) ([]*api_dto.ApiSimpleItem, error) { +// return i.module.SimpleList(ctx, serviceId) +//} func (i *imlAPIController) Detail(ctx *gin.Context, serviceId string, apiId string) (*api_dto.ApiDetail, error) { return i.module.Detail(ctx, serviceId, apiId) diff --git a/controller/publish/iml.go b/controller/publish/iml.go index c3f3b8a..5140e3b 100644 --- a/controller/publish/iml.go +++ b/controller/publish/iml.go @@ -19,19 +19,24 @@ type imlPublishController struct { releaseModule release.IReleaseModule `autowired:""` } -func (c *imlPublishController) PublishStatuses(ctx *gin.Context, project string, id string) ([]*dto.PublishStatus, error) { - return c.publishModule.PublishStatuses(ctx, project, id) +func (c *imlPublishController) ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) error { + + return c.publishModule.ReleaseDo(ctx, serviceId, input) +} + +func (c *imlPublishController) PublishStatuses(ctx *gin.Context, serviceId string, id string) ([]*dto.PublishStatus, error) { + return c.publishModule.PublishStatuses(ctx, serviceId, id) } -func (c *imlPublishController) ApplyOnRelease(ctx *gin.Context, project string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) { - newReleaseId, err := c.releaseModule.Create(ctx, project, &dto2.CreateInput{ +func (c *imlPublishController) ApplyOnRelease(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) { + newReleaseId, err := c.releaseModule.Create(ctx, serviceId, &dto2.CreateInput{ Version: input.Version, Remark: input.VersionRemark, }) if err != nil { return nil, err } - apply, err := c.publishModule.Apply(ctx, project, &dto.ApplyInput{ + apply, err := c.publishModule.Apply(ctx, serviceId, &dto.ApplyInput{ Release: newReleaseId, Remark: input.PublishRemark, }) @@ -41,43 +46,43 @@ func (c *imlPublishController) ApplyOnRelease(ctx *gin.Context, project string, return apply, nil } -func (c *imlPublishController) Apply(ctx *gin.Context, project string, input *dto.ApplyInput) (*dto.Publish, error) { - apply, err := c.publishModule.Apply(ctx, project, input) +func (c *imlPublishController) Apply(ctx *gin.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) { + apply, err := c.publishModule.Apply(ctx, serviceId, input) if err != nil { return nil, err } return apply, nil } -func (c *imlPublishController) CheckPublish(ctx *gin.Context, project string, releaseId string) (*dto.DiffOut, error) { - return c.publishModule.CheckPublish(ctx, project, releaseId) +func (c *imlPublishController) CheckPublish(ctx *gin.Context, serviceId string, releaseId string) (*dto.DiffOut, error) { + return c.publishModule.CheckPublish(ctx, serviceId, releaseId) } -func (c *imlPublishController) Close(ctx *gin.Context, project string, id string) error { - err := c.publishModule.Stop(ctx, project, id) +func (c *imlPublishController) Close(ctx *gin.Context, serviceId string, id string) error { + err := c.publishModule.Stop(ctx, serviceId, id) if err != nil { return err } return nil } -func (c *imlPublishController) Stop(ctx *gin.Context, project string, id string) error { - return c.publishModule.Stop(ctx, project, id) +func (c *imlPublishController) Stop(ctx *gin.Context, serviceId string, id string) error { + return c.publishModule.Stop(ctx, serviceId, id) } -func (c *imlPublishController) Refuse(ctx *gin.Context, project string, id string, input *dto.Comments) error { - return c.publishModule.Refuse(ctx, project, id, input.Comments) +func (c *imlPublishController) Refuse(ctx *gin.Context, serviceId string, id string, input *dto.Comments) error { + return c.publishModule.Refuse(ctx, serviceId, id, input.Comments) } -func (c *imlPublishController) Accept(ctx *gin.Context, project string, id string, input *dto.Comments) error { - return c.publishModule.Accept(ctx, project, id, input.Comments) +func (c *imlPublishController) Accept(ctx *gin.Context, serviceId string, id string, input *dto.Comments) error { + return c.publishModule.Accept(ctx, serviceId, id, input.Comments) } -func (c *imlPublishController) Publish(ctx *gin.Context, project string, id string) error { - return c.publishModule.Publish(ctx, project, id) +func (c *imlPublishController) Publish(ctx *gin.Context, serviceId string, id string) error { + return c.publishModule.Publish(ctx, serviceId, id) } -func (c *imlPublishController) ListPage(ctx *gin.Context, project string, page, pageSize string) ([]*dto.Publish, int, int, int64, error) { +func (c *imlPublishController) ListPage(ctx *gin.Context, serviceId string, page, pageSize string) ([]*dto.Publish, int, int, int64, error) { pageNum, _ := strconv.Atoi(page) pageSizeNum, _ := strconv.Atoi(pageSize) if pageNum < 1 { @@ -86,7 +91,7 @@ func (c *imlPublishController) ListPage(ctx *gin.Context, project string, page, if pageSizeNum <= 0 { pageSizeNum = 50 } - list, total, err := c.publishModule.List(ctx, project, pageNum, pageSizeNum) + list, total, err := c.publishModule.List(ctx, serviceId, pageNum, pageSizeNum) if err != nil { return nil, 0, 0, 0, err } @@ -94,6 +99,6 @@ func (c *imlPublishController) ListPage(ctx *gin.Context, project string, page, return list, pageNum, pageSizeNum, total, nil } -func (c *imlPublishController) Detail(ctx *gin.Context, project string, id string) (*dto.PublishDetail, error) { - return c.publishModule.Detail(ctx, project, id) +func (c *imlPublishController) Detail(ctx *gin.Context, serviceId string, id string) (*dto.PublishDetail, error) { + return c.publishModule.Detail(ctx, serviceId, id) } diff --git a/controller/publish/publish.go b/controller/publish/publish.go index 66b7930..33b64f0 100644 --- a/controller/publish/publish.go +++ b/controller/publish/publish.go @@ -13,18 +13,18 @@ var ( ) type IPublishController interface { - CheckPublish(ctx *gin.Context, project string, releaseId string) (*dto.DiffOut, error) - - ApplyOnRelease(ctx *gin.Context, project string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) - Apply(ctx *gin.Context, project string, input *dto.ApplyInput) (*dto.Publish, error) - Close(ctx *gin.Context, project string, id string) error - Stop(ctx *gin.Context, project string, id string) error - Refuse(ctx *gin.Context, project string, id string, input *dto.Comments) error - Accept(ctx *gin.Context, project string, id string, input *dto.Comments) error - Publish(ctx *gin.Context, project string, id string) error - ListPage(ctx *gin.Context, project string, page, pageSize string) ([]*dto.Publish, int, int, int64, error) - Detail(ctx *gin.Context, project string, id string) (*dto.PublishDetail, error) - PublishStatuses(ctx *gin.Context, project string, id string) ([]*dto.PublishStatus, error) + CheckPublish(ctx *gin.Context, serviceId string, releaseId string) (*dto.DiffOut, error) + ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) error + ApplyOnRelease(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) + Apply(ctx *gin.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) + Close(ctx *gin.Context, serviceId string, id string) error + Stop(ctx *gin.Context, serviceId string, id string) error + Refuse(ctx *gin.Context, serviceId string, id string, input *dto.Comments) error + Accept(ctx *gin.Context, serviceId string, id string, input *dto.Comments) error + Publish(ctx *gin.Context, serviceId string, id string) error + ListPage(ctx *gin.Context, serviceId string, page, pageSize string) ([]*dto.Publish, int, int, int64, error) + Detail(ctx *gin.Context, serviceId string, id string) (*dto.PublishDetail, error) + PublishStatuses(ctx *gin.Context, serviceId string, id string) ([]*dto.PublishStatus, error) } func init() { diff --git a/controller/release/iml.go b/controller/release/iml.go index de9cd49..7272a0a 100644 --- a/controller/release/iml.go +++ b/controller/release/iml.go @@ -1,9 +1,9 @@ package release import ( - "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/release" "github.com/eolinker/apipark/module/release/dto" + service_diff "github.com/eolinker/apipark/module/service-diff" "github.com/gin-gonic/gin" ) @@ -13,7 +13,7 @@ var ( type imlReleaseController struct { module release.IReleaseModule `autowired:""` - diffModule project_diff.IProjectDiffModule `autowired:""` + diffModule service_diff.IServiceDiffModule `autowired:""` } func (c *imlReleaseController) Create(ctx *gin.Context, project string, input *dto.CreateInput) error { @@ -30,7 +30,7 @@ func (c *imlReleaseController) Detail(ctx *gin.Context, project string, id strin func (c *imlReleaseController) List(ctx *gin.Context, project string) ([]*dto.Release, error) { return c.module.List(ctx, project) } -func (c *imlReleaseController) Preview(ctx *gin.Context, project string) (*dto.Release, *project_diff.DiffOut, bool, error) { +func (c *imlReleaseController) Preview(ctx *gin.Context, project string) (*dto.Release, *service_diff.DiffOut, bool, error) { releaseInfo, diff, complete, err := c.module.Preview(ctx, project) if err != nil { return nil, nil, false, err diff --git a/controller/release/release.go b/controller/release/release.go index 2e297fc..ad46dcb 100644 --- a/controller/release/release.go +++ b/controller/release/release.go @@ -1,11 +1,13 @@ package release import ( - "github.com/eolinker/apipark/module/project_diff" + "reflect" + + service_diff "github.com/eolinker/apipark/module/service-diff" + "github.com/eolinker/apipark/module/release/dto" "github.com/eolinker/go-common/autowire" "github.com/gin-gonic/gin" - "reflect" ) type IReleaseController interface { @@ -13,7 +15,7 @@ type IReleaseController interface { Delete(ctx *gin.Context, project string, id string) error Detail(ctx *gin.Context, project string, id string) (*dto.Detail, error) List(ctx *gin.Context, project string) ([]*dto.Release, error) - Preview(ctx *gin.Context, project string) (*dto.Release, *project_diff.DiffOut, bool, error) + Preview(ctx *gin.Context, project string) (*dto.Release, *service_diff.DiffOut, bool, error) } func init() { diff --git a/controller/upstream/iml.go b/controller/upstream/iml.go index 41fb391..36349fe 100644 --- a/controller/upstream/iml.go +++ b/controller/upstream/iml.go @@ -18,10 +18,10 @@ type imlUpstreamController struct { partitionModule cluster.IClusterModule `autowired:""` } -func (i *imlUpstreamController) Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, error) { - return i.upstreamModule.Get(ctx, pid) +func (i *imlUpstreamController) Get(ctx *gin.Context, serviceId string) (upstream_dto.UpstreamConfig, error) { + return i.upstreamModule.Get(ctx, serviceId) } -func (i *imlUpstreamController) Save(ctx *gin.Context, pid string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { - return i.upstreamModule.Save(ctx, pid, *upstream) +func (i *imlUpstreamController) Save(ctx *gin.Context, serviceId string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { + return i.upstreamModule.Save(ctx, serviceId, *upstream) } diff --git a/controller/upstream/upstream.go b/controller/upstream/upstream.go index 122582d..68482bc 100644 --- a/controller/upstream/upstream.go +++ b/controller/upstream/upstream.go @@ -10,8 +10,8 @@ import ( ) type IUpstreamController interface { - Get(ctx *gin.Context, pid string) (upstream_dto.UpstreamConfig, error) - Save(ctx *gin.Context, pid string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) + Get(ctx *gin.Context, serviceId string) (upstream_dto.UpstreamConfig, error) + Save(ctx *gin.Context, serviceId string, upstream *upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) } func init() { diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index 7320ae0..7a88ab7 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -257,7 +257,7 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca // Description: s.Description, // Document: docStr, // Basic: &catalogue_dto.ServiceBasic{ - // //Service: auto.UUID(s.Project), + // //Service: auto.UUID(s.Service), // Team: auto.UUID(s.Team), // ApiNum: len(apis), // SubscriberNum: subscribeCount[s.Id], diff --git a/module/project_diff/diff.go b/module/project_diff/diff.go deleted file mode 100644 index 8776472..0000000 --- a/module/project_diff/diff.go +++ /dev/null @@ -1,24 +0,0 @@ -package project_diff - -import ( - "context" - "github.com/eolinker/apipark/service/project_diff" - "github.com/eolinker/go-common/autowire" - "reflect" -) - -var ( - _ IProjectDiffModule = (*imlProjectDiff)(nil) -) - -type IProjectDiffModule interface { - Diff(ctx context.Context, projectId string, baseRelease, targetRelease string) (*project_diff.Diff, error) - DiffForLatest(ctx context.Context, project string, baseRelease string) (*project_diff.Diff, bool, error) - Out(ctx context.Context, diff *project_diff.Diff) (*DiffOut, error) -} - -func init() { - autowire.Auto[IProjectDiffModule](func() reflect.Value { - return reflect.ValueOf(new(imlProjectDiff)) - }) -} diff --git a/module/publish/dto/diff.go b/module/publish/dto/diff.go index 4991fbf..a11a3e5 100644 --- a/module/publish/dto/diff.go +++ b/module/publish/dto/diff.go @@ -1,7 +1,5 @@ package dto -import ( - "github.com/eolinker/apipark/module/project_diff" -) +import service_diff "github.com/eolinker/apipark/module/service-diff" -type DiffOut = project_diff.DiffOut +type DiffOut = service_diff.DiffOut diff --git a/module/publish/dto/out.go b/module/publish/dto/out.go index 509a045..828841a 100644 --- a/module/publish/dto/out.go +++ b/module/publish/dto/out.go @@ -13,7 +13,7 @@ type Publish struct { Comments string `json:"comments,omitempty"` Release auto.Label `json:"release,omitempty" aolabel:"release"` Previous *auto.Label `json:"previous,omitempty" aolabel:"release"` - Project auto.Label `json:"project" aolabel:"project"` + Service auto.Label `json:"service" aolabel:"service"` Applicant auto.Label `json:"applicant" aolabel:"user"` Approver *auto.Label `json:"approver,omitempty" aolabel:"user"` Status publish.StatusType `json:"status,omitempty" ` @@ -29,7 +29,7 @@ func FromModel(m *publish.Publish, versionRemark string) *Publish { Remark: m.Remark, VersionRemark: versionRemark, Comments: m.Comments, - Project: auto.UUID(m.Project), + Service: auto.UUID(m.Service), Applicant: auto.UUID(m.Applicant), Release: auto.UUID(m.Release), @@ -54,7 +54,7 @@ type PublishDetail struct { type PublishStatus struct { //Partition auto.Label `json:"partition" aolabel:"partition"` - Cluster auto.Label `json:"cluster" aolabel:"cluster"` - Status string `json:"status"` - Error string `json:"error"` + //Cluster auto.Label `json:"cluster" aolabel:"cluster"` + Status string `json:"status"` + Error string `json:"error"` } diff --git a/module/publish/iml.go b/module/publish/iml.go index e307626..92ec131 100644 --- a/module/publish/iml.go +++ b/module/publish/iml.go @@ -6,6 +6,9 @@ import ( "fmt" "time" + dto2 "github.com/eolinker/apipark/module/release/dto" + "github.com/eolinker/go-common/store" + "github.com/eolinker/apipark/service/service" "github.com/eolinker/apipark/service/universally/commit" @@ -13,14 +16,13 @@ import ( "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/upstream" - "github.com/eolinker/go-common/auto" - "github.com/eolinker/apipark/gateway" "github.com/eolinker/eosc/log" - projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/publish/dto" + releaseModule "github.com/eolinker/apipark/module/release" + serviceDiff "github.com/eolinker/apipark/module/service-diff" "github.com/eolinker/apipark/service/cluster" "github.com/eolinker/apipark/service/publish" "github.com/eolinker/apipark/service/release" @@ -30,20 +32,52 @@ import ( ) var ( - _ IPublishModule = (*imlPublishModule)(nil) - projectRuleMustServer = map[string]bool{ + _ IPublishModule = (*imlPublishModule)(nil) + asServer = map[string]bool{ "as_server": true, } ) type imlPublishModule struct { - projectDiffModule projectDiff.IProjectDiffModule `autowired:""` + projectDiffModule serviceDiff.IServiceDiffModule `autowired:""` + releaseModule releaseModule.IReleaseModule `autowired:""` publishService publish.IPublishService `autowired:""` apiService api.IAPIService `autowired:""` upstreamService upstream.IUpstreamService `autowired:""` releaseService release.IReleaseService `autowired:""` clusterService cluster.IClusterService `autowired:""` serviceService service.IServiceService `autowired:""` + transaction store.ITransaction `autowired:""` +} + +func (m *imlPublishModule) ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error { + return m.transaction.Transaction(ctx, func(ctx context.Context) error { + newReleaseId, err := m.releaseModule.Create(ctx, serviceId, &dto2.CreateInput{ + Version: input.Version, + Remark: input.VersionRemark, + }) + if err != nil { + return err + } + apply, err := m.Apply(ctx, serviceId, &dto.ApplyInput{ + Release: newReleaseId, + Remark: input.PublishRemark, + }) + if err != nil { + return err + } + err = m.Accept(ctx, serviceId, apply.Id, "") + if err != nil { + m.releaseModule.Delete(ctx, serviceId, newReleaseId) + return err + } + err = m.Publish(ctx, serviceId, apply.Id) + if err != nil { + m.releaseModule.Delete(ctx, serviceId, newReleaseId) + } + + return nil + }) } func (m *imlPublishModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { @@ -152,7 +186,7 @@ func (m *imlPublishModule) getProjectRelease(ctx context.Context, projectID stri ID: c.Target, Version: version, MatchLabels: map[string]string{ - "project": projectID, + "serviceId": projectID, }, }, PassHost: c.Data.PassHost, @@ -251,7 +285,7 @@ func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releas ID: c.Target, Version: version, MatchLabels: map[string]string{ - "project": projectID, + "serviceId": projectID, }, }, PassHost: c.Data.PassHost, @@ -278,8 +312,8 @@ func (m *imlPublishModule) getReleaseInfo(ctx context.Context, projectID, releas return projectReleaseMap, nil } -func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, id string) ([]*dto.PublishStatus, error) { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) PublishStatuses(ctx context.Context, serviceId string, id string) ([]*dto.PublishStatus, error) { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } @@ -287,8 +321,8 @@ func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, if err != nil { return nil, err } - if flow.Project != project { - return nil, errors.New("项目不一致") + if flow.Service != serviceId { + return nil, errors.New("服务不一致") } list, err := m.publishService.GetPublishStatus(ctx, id) if err != nil { @@ -302,9 +336,9 @@ func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, errMsg = "发布超时" } return &dto.PublishStatus{ - Cluster: auto.UUID(s.Cluster), - Status: status.String(), - Error: errMsg, + //Cluster: auto.UUID(s.Cluster), + Status: status.String(), + Error: errMsg, } }), nil @@ -312,20 +346,20 @@ func (m *imlPublishModule) PublishStatuses(ctx context.Context, project string, // Apply applies the changes to the imlPublishModule. // -// ctx context.Context, project string, input *dto.ApplyInput +// ctx context.Context, serviceId string, input *dto.ApplyInput // *dto.Publish, error -func (m *imlPublishModule) Apply(ctx context.Context, project string, input *dto.ApplyInput) (*dto.Publish, error) { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Apply(ctx context.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - err = m.checkPublish(ctx, project, input.Release) + err = m.checkPublish(ctx, serviceId, input.Release) if err != nil { return nil, err } previous := "" - running, err := m.releaseService.GetRunning(ctx, project) + running, err := m.releaseService.GetRunning(ctx, serviceId) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err @@ -341,14 +375,14 @@ func (m *imlPublishModule) Apply(ctx context.Context, project string, input *dto } newPublishId := uuid.NewString() - diff, ok, err := m.projectDiffModule.DiffForLatest(ctx, project, previous) + diff, ok, err := m.projectDiffModule.DiffForLatest(ctx, serviceId, previous) if err != nil { return nil, err } if !ok { return nil, errors.New("latest completeness check failed") } - err = m.publishService.Create(ctx, newPublishId, project, releaseToPublish.UUID, previous, releaseToPublish.Version, input.Remark, diff) + err = m.publishService.Create(ctx, newPublishId, serviceId, releaseToPublish.UUID, previous, releaseToPublish.Version, input.Remark, diff) if err != nil { return nil, err } @@ -359,17 +393,17 @@ func (m *imlPublishModule) Apply(ctx context.Context, project string, input *dto return dto.FromModel(np, releaseToPublish.Remark), nil } -func (m *imlPublishModule) CheckPublish(ctx context.Context, project string, releaseId string) (*dto.DiffOut, error) { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) CheckPublish(ctx context.Context, serviceId string, releaseId string) (*dto.DiffOut, error) { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } - err = m.checkPublish(ctx, project, releaseId) + err = m.checkPublish(ctx, serviceId, releaseId) if err != nil { return nil, err } - running, err := m.releaseService.GetRunning(ctx, project) + running, err := m.releaseService.GetRunning(ctx, serviceId) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } @@ -379,14 +413,14 @@ func (m *imlPublishModule) CheckPublish(ctx context.Context, project string, rel } if releaseId == "" { // 发布latest 版本 - diff, _, err := m.projectDiffModule.DiffForLatest(ctx, project, runningReleaseId) + diff, _, err := m.projectDiffModule.DiffForLatest(ctx, serviceId, runningReleaseId) if err != nil { return nil, err } return m.projectDiffModule.Out(ctx, diff) } else { // 发布 releaseId 版本, 返回 与当前版本的差异 - diff, err := m.projectDiffModule.Diff(ctx, project, runningReleaseId, releaseId) + diff, err := m.projectDiffModule.Diff(ctx, serviceId, runningReleaseId, releaseId) if err != nil { return nil, err } @@ -394,15 +428,15 @@ func (m *imlPublishModule) CheckPublish(ctx context.Context, project string, rel } } -func (m *imlPublishModule) checkPublish(ctx context.Context, project string, releaseId string) error { - flows, err := m.publishService.ListForStatus(ctx, project, publish.StatusApply, publish.StatusAccept) +func (m *imlPublishModule) checkPublish(ctx context.Context, serviceId string, releaseId string) error { + flows, err := m.publishService.ListForStatus(ctx, serviceId, publish.StatusApply, publish.StatusAccept) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return err } if len(flows) > 0 { return errors.New("正在发布中") } - running, err := m.releaseService.GetRunning(ctx, project) + running, err := m.releaseService.GetRunning(ctx, serviceId) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return err } @@ -415,8 +449,8 @@ func (m *imlPublishModule) checkPublish(ctx context.Context, project string, rel } return nil } -func (m *imlPublishModule) Close(ctx context.Context, project, id string) error { - err := m.publishService.SetStatus(ctx, project, id, publish.StatusClose) +func (m *imlPublishModule) Close(ctx context.Context, serviceId, id string) error { + err := m.publishService.SetStatus(ctx, serviceId, id, publish.StatusClose) if err != nil { return err } @@ -424,8 +458,8 @@ func (m *imlPublishModule) Close(ctx context.Context, project, id string) error return nil } -func (m *imlPublishModule) Stop(ctx context.Context, project string, id string) error { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Stop(ctx context.Context, serviceId string, id string) error { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return err } @@ -433,7 +467,7 @@ func (m *imlPublishModule) Stop(ctx context.Context, project string, id string) if err != nil { return err } - if flow.Project != project { + if flow.Service != serviceId { return errors.New("项目不一致") } @@ -444,23 +478,23 @@ func (m *imlPublishModule) Stop(ctx context.Context, project string, id string) if flow.Status == publish.StatusApply { status = publish.StatusClose } - return m.publishService.SetStatus(ctx, project, id, status) + return m.publishService.SetStatus(ctx, serviceId, id, status) } -func (m *imlPublishModule) Refuse(ctx context.Context, project string, id string, commits string) error { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Refuse(ctx context.Context, serviceId string, id string, commits string) error { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return err } - return m.publishService.Refuse(ctx, project, id, commits) + return m.publishService.Refuse(ctx, serviceId, id, commits) } -func (m *imlPublishModule) Accept(ctx context.Context, project string, id string, commits string) error { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Accept(ctx context.Context, serviceId string, id string, commits string) error { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return err } - return m.publishService.Accept(ctx, project, id, commits) + return m.publishService.Accept(ctx, serviceId, id, commits) } func (m *imlPublishModule) publish(ctx context.Context, id string, clusterId string, projectRelease *gateway.ProjectRelease) error { @@ -506,8 +540,8 @@ func (m *imlPublishModule) publish(ctx context.Context, id string, clusterId str return nil } -func (m *imlPublishModule) Publish(ctx context.Context, project string, id string) error { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Publish(ctx context.Context, serviceId string, id string) error { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return err } @@ -515,10 +549,10 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin if err != nil { return err } - if flow.Project != project { - return errors.New("项目不一致") + if flow.Service != serviceId { + return errors.New("服务不一致") } - if flow.Status != publish.StatusAccept { + if flow.Status != publish.StatusAccept && flow.Status != publish.StatusDone { return errors.New("只有通过状态才能发布") } clusters, err := m.clusterService.List(ctx) @@ -529,7 +563,7 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin return i.Uuid }) - projectReleaseMap, err := m.getReleaseInfo(ctx, project, flow.Release, flow.Release, clusterIds) + projectReleaseMap, err := m.getReleaseInfo(ctx, serviceId, flow.Release, flow.Release, clusterIds) if err != nil { return err } @@ -543,7 +577,7 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin continue } } - err = m.releaseService.SetRunning(ctx, project, flow.Release) + err = m.releaseService.SetRunning(ctx, serviceId, flow.Release) if err != nil { return err } @@ -551,15 +585,15 @@ func (m *imlPublishModule) Publish(ctx context.Context, project string, id strin if hasError { status = publish.StatusPublishError } - return m.publishService.SetStatus(ctx, project, id, status) + return m.publishService.SetStatus(ctx, serviceId, id, status) } -func (m *imlPublishModule) List(ctx context.Context, project string, page, pageSize int) ([]*dto.Publish, int64, error) { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) List(ctx context.Context, serviceId string, page, pageSize int) ([]*dto.Publish, int64, error) { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, 0, err } - list, total, err := m.publishService.ListProjectPage(ctx, project, page, pageSize) + list, total, err := m.publishService.ListProjectPage(ctx, serviceId, page, pageSize) if err != nil { return nil, 0, err } @@ -569,8 +603,8 @@ func (m *imlPublishModule) List(ctx context.Context, project string, page, pageS }), total, nil } -func (m *imlPublishModule) Detail(ctx context.Context, project string, id string) (*dto.PublishDetail, error) { - _, err := m.serviceService.Check(ctx, project, projectRuleMustServer) +func (m *imlPublishModule) Detail(ctx context.Context, serviceId string, id string) (*dto.PublishDetail, error) { + _, err := m.serviceService.Check(ctx, serviceId, asServer) if err != nil { return nil, err } @@ -578,7 +612,7 @@ func (m *imlPublishModule) Detail(ctx context.Context, project string, id string if err != nil { return nil, err } - if flow.Project != project { + if flow.Service != serviceId { return nil, errors.New("项目不一致") } diff, err := m.publishService.GetDiff(ctx, id) @@ -589,7 +623,7 @@ func (m *imlPublishModule) Detail(ctx context.Context, project string, id string if err != nil { return nil, err } - publishStatuses, err := m.PublishStatuses(ctx, project, id) + publishStatuses, err := m.PublishStatuses(ctx, serviceId, id) if err != nil { return nil, err } diff --git a/module/publish/module.go b/module/publish/module.go index cbd6447..a15c951 100644 --- a/module/publish/module.go +++ b/module/publish/module.go @@ -11,16 +11,17 @@ import ( ) type IPublishModule interface { - CheckPublish(ctx context.Context, project string, releaseId string) (*dto.DiffOut, error) + CheckPublish(ctx context.Context, serviceId string, releaseId string) (*dto.DiffOut, error) + ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error - Apply(ctx context.Context, project string, input *dto.ApplyInput) (*dto.Publish, error) - Stop(ctx context.Context, project string, id string) error - Refuse(ctx context.Context, project string, id string, commits string) error - Accept(ctx context.Context, project string, id string, commits string) error - Publish(ctx context.Context, project string, id string) error - List(ctx context.Context, project string, page, pageSize int) ([]*dto.Publish, int64, error) - Detail(ctx context.Context, project string, id string) (*dto.PublishDetail, error) - PublishStatuses(ctx context.Context, project string, id string) ([]*dto.PublishStatus, error) + Apply(ctx context.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) + Stop(ctx context.Context, serviceId string, id string) error + Refuse(ctx context.Context, serviceId string, id string, commits string) error + Accept(ctx context.Context, serviceId string, id string, commits string) error + Publish(ctx context.Context, serviceId string, id string) error + List(ctx context.Context, serviceId string, page, pageSize int) ([]*dto.Publish, int64, error) + Detail(ctx context.Context, serviceId string, id string) (*dto.PublishDetail, error) + PublishStatuses(ctx context.Context, serviceId string, id string) ([]*dto.PublishStatus, error) } func init() { diff --git a/module/release/dto/release.go b/module/release/dto/release.go index 9b6b673..692d73b 100644 --- a/module/release/dto/release.go +++ b/module/release/dto/release.go @@ -8,7 +8,7 @@ import ( type Release struct { Id string `json:"id,omitempty"` Version string `json:"version,omitempty"` - Project auto.Label `json:"project,omitempty" aolabel:"project"` + Service auto.Label `json:"service,omitempty" aolabel:"service"` CreateTime auto.TimeLabel `json:"create_time"` Creator auto.Label `json:"creator" aolabel:"user"` Status Status `json:"status,omitempty"` @@ -22,10 +22,8 @@ type Detail struct { Id string `json:"id,omitempty"` Version string `json:"version,omitempty"` Remark string `json:"remark,omitempty"` - Project auto.Label `json:"project,omitempty" aolabel:"project"` + Service auto.Label `json:"service,omitempty" aolabel:"service"` CreateTime auto.TimeLabel `json:"createTime"` Creator auto.Label `json:"creator" aolabel:"user"` - //Apis []*project_diff.ApiDiff `json:"apis,omitempty"` - //Upstreams []*project_diff.UpstreamDiff `json:"upstreams,omitempty"` - Diffs *dto.DiffOut `json:"diffs,omitempty"` + Diffs *dto.DiffOut `json:"diffs,omitempty"` } diff --git a/module/release/iml.go b/module/release/iml.go index 6698bd6..a8e26d8 100644 --- a/module/release/iml.go +++ b/module/release/iml.go @@ -7,11 +7,11 @@ import ( "github.com/eolinker/apipark/service/cluster" "github.com/eolinker/apipark/service/service" + "github.com/eolinker/apipark/service/service_diff" - projectDiff "github.com/eolinker/apipark/module/project_diff" "github.com/eolinker/apipark/module/release/dto" + serviceDiff "github.com/eolinker/apipark/module/service-diff" "github.com/eolinker/apipark/service/api" - "github.com/eolinker/apipark/service/project_diff" "github.com/eolinker/apipark/service/publish" "github.com/eolinker/apipark/service/release" "github.com/eolinker/apipark/service/universally/commit" @@ -30,7 +30,7 @@ var ( ) type imlReleaseModule struct { - projectDiffModule projectDiff.IProjectDiffModule `autowired:""` + projectDiffModule serviceDiff.IServiceDiffModule `autowired:""` releaseService release.IReleaseService `autowired:""` apiService api.IAPIService `autowired:""` upstreamService upstream.IUpstreamService `autowired:""` @@ -40,9 +40,9 @@ type imlReleaseModule struct { clusterService cluster.IClusterService `autowired:""` } -func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input *dto.CreateInput) (string, error) { +func (m *imlReleaseModule) Create(ctx context.Context, serviceId string, input *dto.CreateInput) (string, error) { - proInfo, err := m.projectService.Check(ctx, projectId, projectRuleMustServer) + proInfo, err := m.projectService.Check(ctx, serviceId, projectRuleMustServer) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return "", errors.New("project not found") @@ -87,7 +87,7 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * if len(apis) != len(apiDocs) { return "", errors.New("api or document not found") } - upstreams, err := m.upstreamService.ListLatestCommit(ctx, projectId) + upstreams, err := m.upstreamService.ListLatestCommit(ctx, serviceId) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return "", errors.New("api config or document not found") @@ -114,7 +114,7 @@ func (m *imlReleaseModule) Create(ctx context.Context, projectId string, input * }), apiUUIDS, apiProxy, apiDocs, upstreams) { return "", errors.New("completeness check failed") } - newRelease, err := m.releaseService.CreateRelease(ctx, projectId, input.Version, input.Remark, apiProxyCommits, apiDocumentCommits, upstreamCommitsForUKC) + newRelease, err := m.releaseService.CreateRelease(ctx, serviceId, input.Version, input.Remark, apiProxyCommits, apiDocumentCommits, upstreamCommitsForUKC) if err != nil { return "", err } @@ -126,7 +126,7 @@ func (m *imlReleaseModule) Detail(ctx context.Context, project string, id string if err != nil { return nil, err } - if r.Project != project { + if r.Service != project { return nil, errors.New("release not found") } running, err := m.releaseService.GetRunning(ctx, project) @@ -149,7 +149,7 @@ func (m *imlReleaseModule) Detail(ctx context.Context, project string, id string Id: r.UUID, Version: r.Version, Remark: r.Remark, - Project: auto.UUID(r.Project), + Service: auto.UUID(r.Service), CreateTime: auto.TimeLabel(r.CreateAt), Creator: auto.UUID(r.Creator), Diffs: out, @@ -185,7 +185,7 @@ func (m *imlReleaseModule) List(ctx context.Context, project string) ([]*dto.Rel r := &dto.Release{ Id: s.UUID, - Project: auto.UUID(s.Project), + Service: auto.UUID(s.Service), Version: s.Version, Remark: s.Remark, Status: dto.StatusNone, @@ -233,7 +233,7 @@ func (m *imlReleaseModule) Delete(ctx context.Context, project string, id string if r == nil { return errors.New("release not found") } - if r.Project != project { + if r.Service != project { return errors.New("project not match") } running, err := m.releaseService.GetRunning(ctx, project) @@ -257,7 +257,7 @@ func (m *imlReleaseModule) Delete(ctx context.Context, project string, id string } -func (m *imlReleaseModule) Preview(ctx context.Context, project string) (*dto.Release, *project_diff.Diff, bool, error) { +func (m *imlReleaseModule) Preview(ctx context.Context, project string) (*dto.Release, *service_diff.Diff, bool, error) { _, err := m.projectService.Check(ctx, project, projectRuleMustServer) if err != nil { return nil, nil, false, err @@ -278,7 +278,7 @@ func (m *imlReleaseModule) Preview(ctx context.Context, project string) (*dto.Re return &dto.Release{ Id: running.UUID, Version: running.Version, - Project: auto.UUID(project), + Service: auto.UUID(project), CreateTime: auto.TimeLabel(running.CreateAt), Creator: auto.UUID(running.Creator), Status: dto.StatusNone, diff --git a/module/release/module.go b/module/release/module.go index 9a99e0c..bab0a45 100644 --- a/module/release/module.go +++ b/module/release/module.go @@ -2,18 +2,19 @@ package release import ( "context" + "reflect" + "github.com/eolinker/apipark/module/release/dto" - "github.com/eolinker/apipark/service/project_diff" + "github.com/eolinker/apipark/service/service_diff" "github.com/eolinker/go-common/autowire" - "reflect" ) type IReleaseModule interface { - Create(ctx context.Context, project string, input *dto.CreateInput) (string, error) - Detail(ctx context.Context, project string, id string) (*dto.Detail, error) - List(ctx context.Context, project string) ([]*dto.Release, error) - Delete(ctx context.Context, project string, id string) error - Preview(ctx context.Context, project string) (*dto.Release, *project_diff.Diff, bool, error) + Create(ctx context.Context, service string, input *dto.CreateInput) (string, error) + Detail(ctx context.Context, service string, id string) (*dto.Detail, error) + List(ctx context.Context, service string) ([]*dto.Release, error) + Delete(ctx context.Context, service string, id string) error + Preview(ctx context.Context, service string) (*dto.Release, *service_diff.Diff, bool, error) } func init() { diff --git a/module/service-diff/diff.go b/module/service-diff/diff.go new file mode 100644 index 0000000..545e144 --- /dev/null +++ b/module/service-diff/diff.go @@ -0,0 +1,25 @@ +package service_diff + +import ( + "context" + "reflect" + + "github.com/eolinker/apipark/service/service_diff" + "github.com/eolinker/go-common/autowire" +) + +var ( + _ IServiceDiffModule = (*imlServiceDiff)(nil) +) + +type IServiceDiffModule interface { + Diff(ctx context.Context, serviceId string, baseRelease, targetRelease string) (*service_diff.Diff, error) + DiffForLatest(ctx context.Context, serviceId string, baseRelease string) (*service_diff.Diff, bool, error) + Out(ctx context.Context, diff *service_diff.Diff) (*DiffOut, error) +} + +func init() { + autowire.Auto[IServiceDiffModule](func() reflect.Value { + return reflect.ValueOf(new(imlServiceDiff)) + }) +} diff --git a/module/project_diff/iml.go b/module/service-diff/iml.go similarity index 73% rename from module/project_diff/iml.go rename to module/service-diff/iml.go index 13bca22..0153869 100644 --- a/module/project_diff/iml.go +++ b/module/service-diff/iml.go @@ -1,4 +1,4 @@ -package project_diff +package service_diff import ( "context" @@ -7,22 +7,22 @@ import ( "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/cluster" - "github.com/eolinker/apipark/service/project_diff" "github.com/eolinker/apipark/service/release" + "github.com/eolinker/apipark/service/service_diff" "github.com/eolinker/apipark/service/universally/commit" "github.com/eolinker/apipark/service/upstream" "github.com/eolinker/go-common/auto" "github.com/eolinker/go-common/utils" ) -type imlProjectDiff struct { +type imlServiceDiff struct { apiService api.IAPIService `autowired:""` upstreamService upstream.IUpstreamService `autowired:""` releaseService release.IReleaseService `autowired:""` clusterService cluster.IClusterService `autowired:""` } -func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease, targetRelease string) (*project_diff.Diff, error) { +func (m *imlServiceDiff) Diff(ctx context.Context, serviceId string, baseRelease, targetRelease string) (*service_diff.Diff, error) { if targetRelease == "" { return nil, fmt.Errorf("target release is required") } @@ -33,7 +33,7 @@ func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease if err != nil { return nil, fmt.Errorf("get target release failed:%w", err) } - if targetReleaseValue.Project != projectId { + if targetReleaseValue.Service != serviceId { return nil, errors.New("project not match") } @@ -41,11 +41,11 @@ func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease if err != nil { return nil, err } - base, err := m.getBaseInfo(ctx, projectId, baseRelease) + base, err := m.getBaseInfo(ctx, serviceId, baseRelease) if err != nil { return nil, err } - target.id = projectId + target.id = serviceId clusters, err := m.clusterService.List(ctx) if err != nil { return nil, err @@ -57,7 +57,7 @@ func (m *imlProjectDiff) Diff(ctx context.Context, projectId string, baseRelease return diff, nil } -func (m *imlProjectDiff) getBaseInfo(ctx context.Context, projectId, baseRelease string) (*projectInfo, error) { +func (m *imlServiceDiff) getBaseInfo(ctx context.Context, serviceId, baseRelease string) (*projectInfo, error) { if baseRelease == "" { return &projectInfo{}, nil } @@ -65,7 +65,7 @@ func (m *imlProjectDiff) getBaseInfo(ctx context.Context, projectId, baseRelease if err != nil { return nil, fmt.Errorf("get base release failed:%w", err) } - if baseReleaseValue.Project != projectId { + if baseReleaseValue.Service != serviceId { return nil, errors.New("project not match") } base, err := m.getReleaseInfo(ctx, baseRelease) @@ -75,9 +75,9 @@ func (m *imlProjectDiff) getBaseInfo(ctx context.Context, projectId, baseRelease return base, nil } -func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, baseRelease string) (*project_diff.Diff, bool, error) { +func (m *imlServiceDiff) DiffForLatest(ctx context.Context, serviceId string, baseRelease string) (*service_diff.Diff, bool, error) { - apis, err := m.apiService.ListForService(ctx, projectId) + apis, err := m.apiService.ListForService(ctx, serviceId) if err != nil { return nil, false, err } @@ -98,17 +98,17 @@ func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, ba return nil, false, err } - upstreamCommits, err := m.upstreamService.ListLatestCommit(ctx, projectId) + upstreamCommits, err := m.upstreamService.ListLatestCommit(ctx, serviceId) if err != nil { return nil, false, err } - base, err := m.getBaseInfo(ctx, projectId, baseRelease) + base, err := m.getBaseInfo(ctx, serviceId, baseRelease) if err != nil { return nil, false, err } target := &projectInfo{ - id: projectId, + id: serviceId, apis: apiInfos, apiCommits: proxy, apiDocs: documents, @@ -123,7 +123,7 @@ func (m *imlProjectDiff) DiffForLatest(ctx context.Context, projectId string, ba }) return m.diff(clusterIds, base, target), true, nil } -func (m *imlProjectDiff) getReleaseInfo(ctx context.Context, releaseId string) (*projectInfo, error) { +func (m *imlServiceDiff) getReleaseInfo(ctx context.Context, releaseId string) (*projectInfo, error) { commits, err := m.releaseService.GetCommits(ctx, releaseId) if err != nil { return nil, err @@ -172,8 +172,8 @@ func (m *imlProjectDiff) getReleaseInfo(ctx context.Context, releaseId string) ( upstreamCommits: upstreamCommits, }, nil } -func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *project_diff.Diff { - out := &project_diff.Diff{ +func (m *imlServiceDiff) diff(partitions []string, base, target *projectInfo) *service_diff.Diff { + out := &service_diff.Diff{ Apis: nil, Upstreams: nil, //Clusters: partitions, @@ -197,55 +197,55 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p for _, apiInfo := range target.apis { apiId := apiInfo.UUID - a := &project_diff.ApiDiff{ + a := &service_diff.ApiDiff{ APi: apiInfo.UUID, Name: apiInfo.Name, Method: apiInfo.Method, Path: apiInfo.Path, - Status: project_diff.Status{}, + Status: service_diff.Status{}, } pc, hasPc := targetApiProxy[apiId] dc, hasDC := targetAPIDoc[apiId] if !hasPc { // 未设置proxy信息 - a.Status.Proxy = project_diff.StatusUnset + a.Status.Proxy = service_diff.StatusUnset } if !hasDC { // 未设置文档 - a.Status.Doc = project_diff.StatusUnset + a.Status.Doc = service_diff.StatusUnset } if !baseApis.Has(apiId) { - a.Change = project_diff.ChangeTypeNew + a.Change = service_diff.ChangeTypeNew } else { - a.Change = project_diff.ChangeTypeNone + a.Change = service_diff.ChangeTypeNone baseProxy, hasBaseProxy := baseApiProxy[apiId] baseDoc, hasBaseDoc := baseAPIDoc[apiId] if hasBaseDoc != hasDC || hasBaseProxy != hasPc { // 文档或者proxy变更 - a.Change = project_diff.ChangeTypeUpdate + a.Change = service_diff.ChangeTypeUpdate } else if (hasPc && pc.UUID != baseProxy.UUID) || (hasDC && dc.UUID != baseDoc.UUID) { // 文档 或者 proxy 变更 - a.Change = project_diff.ChangeTypeUpdate + a.Change = service_diff.ChangeTypeUpdate } } out.Apis = append(out.Apis, a) } - baseApis.Remove(utils.SliceToSlice(out.Apis, func(i *project_diff.ApiDiff) string { + baseApis.Remove(utils.SliceToSlice(out.Apis, func(i *service_diff.ApiDiff) string { return i.APi })...) for _, apiInfo := range base.apis { if baseApis.Has(apiInfo.UUID) { - out.Apis = append(out.Apis, &project_diff.ApiDiff{ + out.Apis = append(out.Apis, &service_diff.ApiDiff{ APi: apiInfo.UUID, Name: apiInfo.Name, Method: apiInfo.Method, Path: apiInfo.Path, - Status: project_diff.Status{}, - Change: project_diff.ChangeTypeDelete, + Status: service_diff.Status{}, + Change: service_diff.ChangeTypeDelete, }) } @@ -260,12 +260,12 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p for _, partitionId := range partitions { key := fmt.Sprintf("%s-%s", target.id, partitionId) - o := &project_diff.UpstreamDiff{ - Upstream: target.id, - Partition: partitionId, - Data: nil, - Change: project_diff.ChangeTypeNone, - Status: 0, + o := &service_diff.UpstreamDiff{ + Upstream: target.id, + //Partition: partitionId, + Data: nil, + Change: service_diff.ChangeTypeNone, + Status: 0, } out.Upstreams = append(out.Upstreams, o) bu, hasBu := baseUpstreamMap[key] @@ -273,15 +273,15 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p if hasTu { o.Data = tu.Data if !hasBu { - o.Change = project_diff.ChangeTypeNew + o.Change = service_diff.ChangeTypeNew } else if tu.UUID != bu.UUID { - o.Change = project_diff.ChangeTypeUpdate + o.Change = service_diff.ChangeTypeUpdate } } else { - o.Status = project_diff.StatusLoss + o.Status = service_diff.StatusLoss if hasBu { - o.Change = project_diff.ChangeTypeDelete + o.Change = service_diff.ChangeTypeDelete } } } @@ -289,7 +289,7 @@ func (m *imlProjectDiff) diff(partitions []string, base, target *projectInfo) *p return out } -func (m *imlProjectDiff) Out(ctx context.Context, diff *project_diff.Diff) (*DiffOut, error) { +func (m *imlServiceDiff) Out(ctx context.Context, diff *service_diff.Diff) (*DiffOut, error) { clusters, err := m.clusterService.List(ctx, diff.Clusters...) if err != nil { @@ -298,30 +298,9 @@ func (m *imlProjectDiff) Out(ctx context.Context, diff *project_diff.Diff) (*Dif if len(clusters) == 0 { return nil, fmt.Errorf("unset gateway for clusters %v", diff.Clusters) } - //// 检查分区是否配置集群,若没有配置,则报错 - //requirePartition := make([]*partition.Partition, 0, len(partitions)) - //for _, p := range partitions { - // if p.Cluster == "" { - // requirePartition = append(requirePartition, p) - // continue - // } - // _, err = m.clusterService.Get(ctx, p.Cluster) - // if err != nil { - // if !errors.Is(err, gorm.ErrRecordNotFound) { - // requirePartition = append(requirePartition, p) - // continue - // } - // return nil, err - // } - // - //} - // - //if len(requirePartition) > 0 { - // return nil, fmt.Errorf("unset gateway for partitions %v", requirePartition) - //} out := &DiffOut{} - out.Apis = utils.SliceToSlice(diff.Apis, func(i *project_diff.ApiDiff) *ApiDiffOut { + out.Apis = utils.SliceToSlice(diff.Apis, func(i *service_diff.ApiDiff) *ApiDiffOut { return &ApiDiffOut{ Api: auto.UUID(i.APi), Name: i.Name, @@ -339,10 +318,9 @@ func (m *imlProjectDiff) Out(ctx context.Context, diff *project_diff.Diff) (*Dif typeValue = "static" } out.Upstreams = append(out.Upstreams, &UpstreamDiffOut{ - Partition: auto.UUID(u.Partition), - Change: u.Change, - Type: typeValue, - Status: u.Status, + Change: u.Change, + Type: typeValue, + Status: u.Status, Addr: utils.SliceToSlice(u.Data.Nodes, func(i *upstream.NodeConfig) string { return i.Address }), diff --git a/module/project_diff/out.go b/module/service-diff/out.go similarity index 75% rename from module/project_diff/out.go rename to module/service-diff/out.go index dcfb92a..6b3cc21 100644 --- a/module/project_diff/out.go +++ b/module/service-diff/out.go @@ -1,8 +1,8 @@ -package project_diff +package service_diff import ( "github.com/eolinker/apipark/service/api" - "github.com/eolinker/apipark/service/project_diff" + "github.com/eolinker/apipark/service/service_diff" "github.com/eolinker/apipark/service/universally/commit" "github.com/eolinker/apipark/service/upstream" "github.com/eolinker/go-common/auto" @@ -19,15 +19,12 @@ type ApiDiffOut struct { Method string `json:"method,omitempty"` Path string `json:"path,omitempty"` //Upstream auto.Label `json:"upstream,omitempty" aolabel:"upstream"` - Change project_diff.ChangeType `json:"change,omitempty"` - Status project_diff.Status `json:"status,omitempty"` + Change service_diff.ChangeType `json:"change,omitempty"` + Status service_diff.Status `json:"status,omitempty"` } type UpstreamDiffOut struct { - //Upstream auto.Label `json:"upstream,omitempty" aolabel:"upstream"` - Partition auto.Label `json:"partition,omitempty" aolabel:"partition"` - //Cluster auto.Label `json:"cluster,omitempty" aolabel:"cluster"` - Change project_diff.ChangeType `json:"change,omitempty"` - Status project_diff.StatusType `json:"status,omitempty"` + Change service_diff.ChangeType `json:"change,omitempty"` + Status service_diff.StatusType `json:"status,omitempty"` Type string `json:"type,omitempty"` Addr []string `json:"addr,omitempty"` } diff --git a/module/upstream/iml.go b/module/upstream/iml.go index 6e1333a..3bdfa6f 100644 --- a/module/upstream/iml.go +++ b/module/upstream/iml.go @@ -18,8 +18,8 @@ import ( ) var ( - _ IUpstreamModule = (*imlUpstreamModule)(nil) - projectRuleMustServer = map[string]bool{ + _ IUpstreamModule = (*imlUpstreamModule)(nil) + asServer = map[string]bool{ "as_server": true, } ) @@ -31,7 +31,7 @@ type imlUpstreamModule struct { } func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.UpstreamConfig, error) { - _, err := i.projectService.Check(ctx, pid, projectRuleMustServer) + _, err := i.projectService.Check(ctx, pid, asServer) if err != nil { return nil, err } @@ -54,7 +54,7 @@ func (i *imlUpstreamModule) Get(ctx context.Context, pid string) (upstream_dto.U } func (i *imlUpstreamModule) Save(ctx context.Context, pid string, upstreamConfig upstream_dto.UpstreamConfig) (upstream_dto.UpstreamConfig, error) { - pInfo, err := i.projectService.Check(ctx, pid, projectRuleMustServer) + pInfo, err := i.projectService.Check(ctx, pid, asServer) if err != nil { return nil, err } diff --git a/plugins/core/release.go b/plugins/core/release.go index 594d15f..750d6bf 100644 --- a/plugins/core/release.go +++ b/plugins/core/release.go @@ -1,17 +1,18 @@ package core import ( - "github.com/eolinker/go-common/pm3" "net/http" + + "github.com/eolinker/go-common/pm3" ) func (p *plugin) releaseApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/release", []string{"context", "query:project", "body"}, []string{}, p.releaseController.Create), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/release", []string{"context", "query:project", "query:id"}, []string{}, p.releaseController.Delete), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/release", []string{"context", "query:project", "query:id"}, []string{"release"}, p.releaseController.Detail), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/releases", []string{"context", "query:project"}, []string{"releases"}, p.releaseController.List), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/release/preview", []string{"context", "query:project"}, []string{"running", "diff", "complete"}, p.releaseController.Preview), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/release", []string{"context", "query:service", "body"}, []string{}, p.releaseController.Create), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/release", []string{"context", "query:service", "query:id"}, []string{}, p.releaseController.Delete), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/release", []string{"context", "query:service", "query:id"}, []string{"release"}, p.releaseController.Detail), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/releases", []string{"context", "query:service"}, []string{"releases"}, p.releaseController.List), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/release/preview", []string{"context", "query:service"}, []string{"running", "diff", "complete"}, p.releaseController.Preview), } } diff --git a/plugins/core/upstream.go b/plugins/core/upstream.go index c72138e..af77a86 100644 --- a/plugins/core/upstream.go +++ b/plugins/core/upstream.go @@ -8,7 +8,7 @@ import ( func (p *plugin) upstreamApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/upstream", []string{"context", "query:project"}, []string{"upstream"}, p.upstreamController.Get), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/upstream", []string{"context", "query:project", "body"}, []string{"upstream"}, p.upstreamController.Save), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/upstream", []string{"context", "query:service"}, []string{"upstream"}, p.upstreamController.Get), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/upstream", []string{"context", "query:service", "body"}, []string{"upstream"}, p.upstreamController.Save), } } diff --git a/plugins/publish_flow/apis.go b/plugins/publish_flow/apis.go index 703a279..7f659b1 100644 --- a/plugins/publish_flow/apis.go +++ b/plugins/publish_flow/apis.go @@ -8,16 +8,17 @@ import ( func (p *plugin) getApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/publish/release", []string{"context", "query:project", "body"}, []string{"publish"}, p.controller.ApplyOnRelease), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/publish/apply", []string{"context", "query:project", "body"}, []string{"publish"}, p.controller.Apply), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/publishs", []string{"context", "query:project", "query:page", "query:page_size"}, []string{"publishs", "page", "size", "total"}, p.controller.ListPage), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/publish", []string{"context", "query:project", "query:id"}, []string{"publish"}, p.controller.Detail), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/publish/check", []string{"context", "query:project", "query:release"}, []string{"diffs"}, p.controller.CheckPublish), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/publish/close", []string{"context", "query:project", "query:id"}, []string{}, p.controller.Close), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/publish/stop", []string{"context", "query:project", "query:id"}, []string{}, p.controller.Stop), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/publish/refuse", []string{"context", "query:project", "query:id", "body"}, []string{}, p.controller.Refuse), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/publish/accept", []string{"context", "query:project", "query:id", "body"}, []string{}, p.controller.Accept), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/project/publish/execute", []string{"context", "query:project", "query:id"}, []string{}, p.controller.Publish), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/publish/status", []string{"context", "query:project", "query:id"}, []string{"publish_status_list"}, p.controller.PublishStatuses), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/release", []string{"context", "query:service", "body"}, []string{"publish"}, p.controller.ApplyOnRelease), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/release/do", []string{"context", "query:service", "body"}, []string{}, p.controller.ReleaseDo), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/apply", []string{"context", "query:service", "body"}, []string{"publish"}, p.controller.Apply), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publishs", []string{"context", "query:service", "query:page", "query:page_size"}, []string{"publishs", "page", "size", "total"}, p.controller.ListPage), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publish", []string{"context", "query:service", "query:id"}, []string{"publish"}, p.controller.Detail), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publish/check", []string{"context", "query:service", "query:release"}, []string{"diffs"}, p.controller.CheckPublish), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/publish/close", []string{"context", "query:service", "query:id"}, []string{}, p.controller.Close), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/publish/stop", []string{"context", "query:service", "query:id"}, []string{}, p.controller.Stop), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/publish/refuse", []string{"context", "query:service", "query:id", "body"}, []string{}, p.controller.Refuse), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/publish/accept", []string{"context", "query:service", "query:id", "body"}, []string{}, p.controller.Accept), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/publish/execute", []string{"context", "query:service", "query:id"}, []string{}, p.controller.Publish), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publish/status", []string{"context", "query:service", "query:id"}, []string{"publish_status_list"}, p.controller.PublishStatuses), } } diff --git a/service/cluster/cluster.go b/service/cluster/cluster.go index 6b62be7..248284c 100644 --- a/service/cluster/cluster.go +++ b/service/cluster/cluster.go @@ -277,14 +277,25 @@ func (s *imlClusterService) UpdateAddress(ctx context.Context, id string, addres if err != nil { return nil, err } - if info.Cluster != id { - return nil, errors.New("cluster id not match") - } + //if info.Cluster != id { + // return nil, errors.New("cluster id not match") + //} + operator := utils.UserId(ctx) + now := time.Now() cv, err := s.store.FirstQuery(ctx, "`uuid` = ?", []interface{}{id}, "id desc") if err != nil { - return nil, err + if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, err + } + cv = &cluster.Cluster{ + UUID: id, + Name: "默认集群", + Resume: "默认集群", + Creator: operator, + CreateAt: now, + } } - operator := utils.UserId(ctx) + // check node nodeIds := utils.SliceToSlice(info.Nodes, func(i *admin.Node) string { return i.Id @@ -316,14 +327,14 @@ func (s *imlClusterService) UpdateAddress(ctx context.Context, id string, addres return err } cv.Updater = operator - cv.UpdateAt = time.Now() - uc, err := s.store.Update(ctx, cv) + cv.UpdateAt = now + err = s.store.Save(ctx, cv) if err != nil { return err } - if uc == 0 { - return errors.New("no update") - } + //if uc == 0 { + // return errors.New("no update") + //} err = s.nodeStore.Insert(ctx, nodeEn...) if err != nil { return err diff --git a/service/publish/diff.go b/service/publish/diff.go index cb5c61e..765ab11 100644 --- a/service/publish/diff.go +++ b/service/publish/diff.go @@ -1,7 +1,5 @@ package publish -import ( - "github.com/eolinker/apipark/service/project_diff" -) +import "github.com/eolinker/apipark/service/service_diff" -type Diff = project_diff.Diff +type Diff = service_diff.Diff diff --git a/service/publish/iml.go b/service/publish/iml.go index 42bdeaf..32595ba 100644 --- a/service/publish/iml.go +++ b/service/publish/iml.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/eolinker/apipark/service/project_diff" + "github.com/eolinker/apipark/service/service_diff" "github.com/eolinker/apipark/stores/publish" "github.com/eolinker/go-common/utils" "gorm.io/gorm" @@ -51,15 +51,15 @@ func (s *imlPublishService) GetPublishStatus(ctx context.Context, id string) ([] }), nil } -func (s *imlPublishService) setAction(ctx context.Context, project, id string, status StatusType, comments string) error { +func (s *imlPublishService) setAction(ctx context.Context, service, id string, status StatusType, comments string) error { operator := utils.UserId(ctx) return s.store.Transaction(ctx, func(ctx context.Context) error { ev, err := s.store.GetByUUID(ctx, id) if err != nil { return err } - if ev.Project != project { - return errors.New("project not match") + if ev.Service != service { + return errors.New("service not match") } ev.Status = int(status) ev.Comments = comments @@ -69,12 +69,12 @@ func (s *imlPublishService) setAction(ctx context.Context, project, id string, s return err }) } -func (s *imlPublishService) Refuse(ctx context.Context, project, id string, comments string) error { - return s.setAction(ctx, project, id, StatusRefuse, comments) +func (s *imlPublishService) Refuse(ctx context.Context, service, id string, comments string) error { + return s.setAction(ctx, service, id, StatusRefuse, comments) } -func (s *imlPublishService) Accept(ctx context.Context, project, id string, comments string) error { - return s.setAction(ctx, project, id, StatusAccept, comments) +func (s *imlPublishService) Accept(ctx context.Context, service, id string, comments string) error { + return s.setAction(ctx, service, id, StatusAccept, comments) } @@ -157,12 +157,12 @@ func (s *imlPublishService) Get(ctx context.Context, id string) (*Publish, error return FromEntity(env), nil } -func (s *imlPublishService) GetDiff(ctx context.Context, id string) (*project_diff.Diff, error) { +func (s *imlPublishService) GetDiff(ctx context.Context, id string) (*service_diff.Diff, error) { ev, err := s.diffStore.GetByUUID(ctx, id) if err != nil { return nil, err } - df := new(project_diff.Diff) + df := new(service_diff.Diff) err = json.Unmarshal(ev.Data, df) if err != nil { return nil, err @@ -170,29 +170,29 @@ func (s *imlPublishService) GetDiff(ctx context.Context, id string) (*project_di return df, nil } -func (s *imlPublishService) ListProject(ctx context.Context, project string) ([]*Publish, error) { - flows, err := s.store.ListQuery(ctx, "project = ?", []interface{}{project}, "apply_time desc") +func (s *imlPublishService) ListProject(ctx context.Context, service string) ([]*Publish, error) { + flows, err := s.store.ListQuery(ctx, "service = ?", []interface{}{service}, "apply_time desc") if err != nil { return nil, err } return utils.SliceToSlice(flows, FromEntity), nil } -func (s *imlPublishService) ListProjectPage(ctx context.Context, project string, page int, pageSize int) ([]*Publish, int64, error) { - flows, total, err := s.store.ListPage(ctx, "project = ?", page, pageSize, []interface{}{project}, "apply_time desc") +func (s *imlPublishService) ListProjectPage(ctx context.Context, service string, page int, pageSize int) ([]*Publish, int64, error) { + flows, total, err := s.store.ListPage(ctx, "service = ?", page, pageSize, []interface{}{service}, "apply_time desc") if err != nil { return nil, 0, err } return utils.SliceToSlice(flows, FromEntity), total, nil } -func (s *imlPublishService) ListForStatus(ctx context.Context, project string, status ...StatusType) ([]*Publish, error) { +func (s *imlPublishService) ListForStatus(ctx context.Context, service string, status ...StatusType) ([]*Publish, error) { wheres := make([]string, 0, 2) args := make([]interface{}, 0, 2) - if project != "" { - wheres = append(wheres, "project = ?") - args = append(args, project) + if service != "" { + wheres = append(wheres, "service = ?") + args = append(args, service) } if len(status) == 1 { wheres = append(wheres, "status = ?") @@ -230,7 +230,7 @@ func (s *imlPublishService) ListForStatusPage(ctx context.Context, page int, pag return utils.SliceToSlice(flows, FromEntity), total, nil } -func (s *imlPublishService) Create(ctx context.Context, uuid, project, release, previous, version, remark string, df *project_diff.Diff) error { +func (s *imlPublishService) Create(ctx context.Context, uuid, service, release, previous, version, remark string, df *service_diff.Diff) error { operator := utils.UserId(ctx) data, err := json.Marshal(df) if err != nil { @@ -240,7 +240,7 @@ func (s *imlPublishService) Create(ctx context.Context, uuid, project, release, nv := &publish.Publish{ Id: 0, UUID: uuid, - Project: project, + Service: service, Release: release, Previous: previous, Version: version, @@ -277,14 +277,14 @@ func (s *imlPublishService) Create(ctx context.Context, uuid, project, release, return nil } -func (s *imlPublishService) SetStatus(ctx context.Context, project, id string, status StatusType) error { +func (s *imlPublishService) SetStatus(ctx context.Context, service, id string, status StatusType) error { return s.store.Transaction(ctx, func(ctx context.Context) error { ev, err := s.store.GetByUUID(ctx, id) if err != nil { return err } - if ev.Project != project { - return errors.New("project not match") + if ev.Service != service { + return errors.New("service not match") } ev.Status = int(status) _, err = s.store.Update(ctx, ev) diff --git a/service/publish/model.go b/service/publish/model.go index 2783b58..60e38b8 100644 --- a/service/publish/model.go +++ b/service/publish/model.go @@ -8,7 +8,7 @@ import ( type Publish struct { Id string - Project string + Service string Release string Previous string Version string @@ -24,7 +24,7 @@ type Publish struct { func FromEntity(e *publish.Publish) *Publish { return &Publish{ Id: e.UUID, - Project: e.Project, + Service: e.Service, Release: e.Release, Previous: e.Previous, Version: e.Version, @@ -39,9 +39,8 @@ func FromEntity(e *publish.Publish) *Publish { } type Status struct { - Publish string - Cluster string - //Partition string + Publish string + Cluster string Status StatusType Error string UpdateAt time.Time diff --git a/service/publish/service.go b/service/publish/service.go index d991e93..34465b7 100644 --- a/service/publish/service.go +++ b/service/publish/service.go @@ -4,7 +4,7 @@ import ( "context" "reflect" - "github.com/eolinker/apipark/service/project_diff" + "github.com/eolinker/apipark/service/service_diff" "github.com/eolinker/go-common/autowire" ) @@ -14,13 +14,13 @@ type IPublishService interface { Latest(ctx context.Context, release ...string) ([]*Publish, error) GetLatest(ctx context.Context, id string) (*Publish, error) Get(ctx context.Context, id string) (*Publish, error) - GetDiff(ctx context.Context, id string) (*project_diff.Diff, error) + GetDiff(ctx context.Context, id string) (*service_diff.Diff, error) ListProject(ctx context.Context, project string) ([]*Publish, error) ListProjectPage(ctx context.Context, project string, page int, pageSize int) ([]*Publish, int64, error) ListForStatus(ctx context.Context, project string, status ...StatusType) ([]*Publish, error) ListForStatusPage(ctx context.Context, page int, pageSize int, status ...StatusType) ([]*Publish, int64, error) - Create(ctx context.Context, uuid, project, release, previous, version, remark string, diff *project_diff.Diff) error + Create(ctx context.Context, uuid, project, release, previous, version, remark string, diff *service_diff.Diff) error SetStatus(ctx context.Context, project, id string, status StatusType) error Refuse(ctx context.Context, project, id string, comments string) error diff --git a/service/release/iml.go b/service/release/iml.go index 3f26d05..6cff1df 100644 --- a/service/release/iml.go +++ b/service/release/iml.go @@ -150,9 +150,9 @@ func (s *imlReleaseService) GetApiDocCommit(ctx context.Context, id string, apiU return commits[0].Commit, nil } -func (s *imlReleaseService) GetRunningApiDocCommit(ctx context.Context, project string, apiUUID string) (string, error) { +func (s *imlReleaseService) GetRunningApiDocCommit(ctx context.Context, service string, apiUUID string) (string, error) { running, err := s.releaseRuntime.First(ctx, map[string]interface{}{ - "project": project, + "service": service, }) if err != nil { return "", err @@ -161,9 +161,9 @@ func (s *imlReleaseService) GetRunningApiDocCommit(ctx context.Context, project } -func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, project string, apiUUID string) (string, error) { +func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, service string, apiUUID string) (string, error) { running, err := s.releaseRuntime.First(ctx, map[string]interface{}{ - "project": project, + "service": service, }) if err != nil { return "", err @@ -251,11 +251,15 @@ func (s *imlReleaseService) GetRunningApiProxyCommit(ctx context.Context, projec // return Upstreams //} -func (s *imlReleaseService) SetRunning(ctx context.Context, project string, id string) error { +func (s *imlReleaseService) SetRunning(ctx context.Context, service string, id string) error { + _, err := s.releaseRuntime.DeleteWhere(ctx, map[string]interface{}{"service": service}) + if err != nil { + return err + } operator := utils.UserId(ctx) return s.releaseRuntime.Save(ctx, &release.Runtime{ Id: 0, - Project: project, + Service: service, Release: id, UpdateTime: time.Now(), Operator: operator, @@ -263,7 +267,7 @@ func (s *imlReleaseService) SetRunning(ctx context.Context, project string, id s } -func (s *imlReleaseService) CreateRelease(ctx context.Context, project string, version string, remark string, apisProxyCommits, apiDocCommits map[string]string, upstreams map[string]map[string]string) (*Release, error) { +func (s *imlReleaseService) CreateRelease(ctx context.Context, service string, version string, remark string, apisProxyCommits, apiDocCommits map[string]string, upstreams map[string]map[string]string) (*Release, error) { operator := utils.UserId(ctx) releaseId := uuid.NewString() commits := make([]*release.Commit, 0, len(apisProxyCommits)+len(apiDocCommits)+len(upstreams)) @@ -300,13 +304,13 @@ func (s *imlReleaseService) CreateRelease(ctx context.Context, project string, v Id: 0, UUID: releaseId, Name: version, - Project: project, + Service: service, Remark: remark, Creator: operator, CreateAt: time.Now(), } err := s.releaseStore.Transaction(ctx, func(ctx context.Context) error { - ok, e := s.CheckNewVersion(ctx, project, version) + ok, e := s.CheckNewVersion(ctx, service, version) if e != nil { return e } @@ -326,9 +330,9 @@ func (s *imlReleaseService) CreateRelease(ctx context.Context, project string, v return FromEntity(ev), nil } -func (s *imlReleaseService) CheckNewVersion(ctx context.Context, project string, version string) (bool, error) { +func (s *imlReleaseService) CheckNewVersion(ctx context.Context, service string, version string) (bool, error) { v, err := s.releaseStore.First(ctx, map[string]interface{}{ - "project": project, + "service": service, "name": version, }) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { @@ -396,8 +400,8 @@ func (s *imlReleaseService) DeleteRelease(ctx context.Context, id string) error } -func (s *imlReleaseService) List(ctx context.Context, project string) ([]*Release, error) { - list, err := s.releaseStore.List(ctx, map[string]interface{}{"project": project}, "create_at desc") +func (s *imlReleaseService) List(ctx context.Context, service string) ([]*Release, error) { + list, err := s.releaseStore.List(ctx, map[string]interface{}{"service": service}, "create_at desc") if err != nil { return nil, err } @@ -445,9 +449,9 @@ func (s *imlReleaseService) GetReleaseInfos(ctx context.Context, id string) ([]* return apiProxyCommits, apiDocumentCommits, upstreamCommits, nil } -func (s *imlReleaseService) GetRunning(ctx context.Context, project string) (*Release, error) { +func (s *imlReleaseService) GetRunning(ctx context.Context, service string) (*Release, error) { running, err := s.releaseRuntime.First(ctx, map[string]interface{}{ - "project": project, + "service": service, }) if err != nil { return nil, err diff --git a/service/release/model.go b/service/release/model.go index 1e80dc5..f75ed3d 100644 --- a/service/release/model.go +++ b/service/release/model.go @@ -8,7 +8,7 @@ import ( type Release struct { UUID string - Project string + Service string Version string Remark string Creator string @@ -18,7 +18,7 @@ type Release struct { func FromEntity(e *release.Release) *Release { return &Release{ UUID: e.UUID, - Project: e.Project, + Service: e.Service, Version: e.Name, Remark: e.Remark, Creator: e.Creator, diff --git a/service/project_diff/diff.go b/service/service_diff/diff.go similarity index 76% rename from service/project_diff/diff.go rename to service/service_diff/diff.go index 2d66133..c021b04 100644 --- a/service/project_diff/diff.go +++ b/service/service_diff/diff.go @@ -1,4 +1,4 @@ -package project_diff +package service_diff import ( "github.com/eolinker/apipark/service/upstream" @@ -31,11 +31,11 @@ type UpstreamConfig struct { Addr []string `json:"addr"` } type UpstreamDiff struct { - Upstream string `json:"upstream,omitempty" ` - Partition string `json:"partition,omitempty"` - Data *upstream.Config `json:"data,omitempty"` - Change ChangeType `json:"change,omitempty"` - Status StatusType `json:"status,omitempty"` + Upstream string `json:"upstream,omitempty" ` + //Partition string `json:"partition,omitempty"` + Data *upstream.Config `json:"data,omitempty"` + Change ChangeType `json:"change,omitempty"` + Status StatusType `json:"status,omitempty"` } type Diff struct { diff --git a/service/project_diff/type.go b/service/service_diff/type.go similarity index 97% rename from service/project_diff/type.go rename to service/service_diff/type.go index 01abd99..ef52a48 100644 --- a/service/project_diff/type.go +++ b/service/service_diff/type.go @@ -1,4 +1,4 @@ -package project_diff +package service_diff import ( "encoding/json" diff --git a/stores/publish/model.go b/stores/publish/model.go index e21defd..d1af174 100644 --- a/stores/publish/model.go +++ b/stores/publish/model.go @@ -5,7 +5,7 @@ import "time" type Publish struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Project string `gorm:"size:36;not null;column:project;comment:项目;index:project;"` + Service string `gorm:"type:varchar(50);not null;column:service;comment:服务名;index:service"` Release string `gorm:"type:varchar(36);not null;column:release;comment:release id;"` Previous string `gorm:"type:varchar(50);not null;column:previous;comment:上一个版本release id;index:previous"` Version string `gorm:"type:varchar(50);not null;column:version;comment:版本号(冗余);index:version;"` @@ -22,7 +22,7 @@ func (t *Publish) IdValue() int64 { return t.Id } func (t *Publish) TableName() string { - return "project_publish" + return "service_publish" } type Diff struct { @@ -35,7 +35,7 @@ func (t *Diff) IdValue() int64 { return t.Id } func (t *Diff) TableName() string { - return "project_publish_diff" + return "service_publish_diff" } type Latest struct { @@ -48,7 +48,7 @@ func (t *Latest) IdValue() int64 { return t.Id } func (t *Latest) TableName() string { - return "project_publish_latest" + return "service_publish_latest" } type Status struct { @@ -64,5 +64,5 @@ func (t *Status) IdValue() int64 { return t.Id } func (t *Status) TableName() string { - return "project_publish_status" + return "service_publish_status" } diff --git a/stores/release/release.go b/stores/release/release.go index fc47350..8dfadce 100644 --- a/stores/release/release.go +++ b/stores/release/release.go @@ -6,7 +6,7 @@ type Release struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Project string `gorm:"size:36;not null;column:project;comment:项目;index:project"` // 项目id + Service string `gorm:"type:varchar(50);not null;column:service;comment:服务ID;index:service"` Remark string `gorm:"size:255;not null;column:remark;comment:备注"` Creator string `gorm:"size:36;not null;column:creator;comment:创建人;index:creator"` // 创建人 CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` diff --git a/stores/release/runtime.go b/stores/release/runtime.go index 03acaa7..c079885 100644 --- a/stores/release/runtime.go +++ b/stores/release/runtime.go @@ -4,7 +4,7 @@ import "time" type Runtime struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - Project string `gorm:"size:36;not null;column:project;comment:项目; uniqueIndex:project"` + Service string `gorm:"type:varchar(50);not null;column:service;comment:服务ID;index:service"` Release string `gorm:"type:varchar(36);not null;column:release;comment:release id;"` UpdateTime time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:update_time;comment:更新时间"` Operator string `gorm:"size:36;not null;column:operator;comment:操作人;index:operator"` @@ -14,5 +14,5 @@ func (t *Runtime) IdValue() int64 { return t.Id } func (t *Runtime) TableName() string { - return "project_runtime" + return "service_runtime" } From a25c3bf7f665a9993f2ed3ef25c2d78f0f812caf Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 1 Aug 2024 18:23:32 +0800 Subject: [PATCH 07/19] =?UTF-8?q?=E8=AE=A2=E9=98=85=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/publish/iml.go | 33 +++- controller/publish/publish.go | 2 +- controller/subscribe/iml.go | 42 ++-- controller/subscribe/subscribe.go | 2 +- module/catalogue/dto/input.go | 1 - module/catalogue/dto/output.go | 12 +- module/catalogue/iml.go | 313 +++++++++++++++--------------- module/service/dto/input.go | 2 + module/service/dto/output.go | 2 + module/service/iml.go | 13 +- module/subscribe/dto/input.go | 6 +- module/subscribe/dto/output.go | 12 +- module/subscribe/iml.go | 146 +++++++------- module/subscribe/subscribe.go | 2 +- plugins/core/service.go | 4 +- plugins/core/subscribe.go | 16 +- plugins/publish_flow/apis.go | 2 +- service/api/iml.go | 8 + service/api/service.go | 3 +- service/release/service.go | 26 ++- service/service/iml.go | 16 ++ service/service/model.go | 20 +- service/service/service.go | 1 + service/subscribe/iml.go | 55 ++++-- service/subscribe/model.go | 19 +- service/subscribe/service.go | 4 +- stores/service/model.go | 1 + stores/subscribe/model.go | 15 +- 28 files changed, 422 insertions(+), 356 deletions(-) diff --git a/controller/publish/iml.go b/controller/publish/iml.go index 5140e3b..6eb2b0b 100644 --- a/controller/publish/iml.go +++ b/controller/publish/iml.go @@ -19,9 +19,36 @@ type imlPublishController struct { releaseModule release.IReleaseModule `autowired:""` } -func (c *imlPublishController) ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) error { - - return c.publishModule.ReleaseDo(ctx, serviceId, input) +func (c *imlPublishController) ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) { + newReleaseId, err := c.releaseModule.Create(ctx, serviceId, &dto2.CreateInput{ + Version: input.Version, + Remark: input.VersionRemark, + }) + if err != nil { + return nil, err + } + apply, err := c.publishModule.Apply(ctx, serviceId, &dto.ApplyInput{ + Release: newReleaseId, + Remark: input.PublishRemark, + }) + if err != nil { + return nil, err + } + err = c.publishModule.Accept(ctx, serviceId, apply.Id, "") + if err != nil { + c.releaseModule.Delete(ctx, serviceId, newReleaseId) + return nil, err + } + err = c.publishModule.Publish(ctx, serviceId, apply.Id) + if err != nil { + c.releaseModule.Delete(ctx, serviceId, newReleaseId) + return nil, err + } + err = c.publishModule.ReleaseDo(ctx, serviceId, input) + if err != nil { + return nil, err + } + return apply, err } func (c *imlPublishController) PublishStatuses(ctx *gin.Context, serviceId string, id string) ([]*dto.PublishStatus, error) { diff --git a/controller/publish/publish.go b/controller/publish/publish.go index 33b64f0..a37d0fa 100644 --- a/controller/publish/publish.go +++ b/controller/publish/publish.go @@ -14,7 +14,7 @@ var ( type IPublishController interface { CheckPublish(ctx *gin.Context, serviceId string, releaseId string) (*dto.DiffOut, error) - ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) error + ReleaseDo(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) ApplyOnRelease(ctx *gin.Context, serviceId string, input *dto.ApplyOnReleaseInput) (*dto.Publish, error) Apply(ctx *gin.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) Close(ctx *gin.Context, serviceId string, id string) error diff --git a/controller/subscribe/iml.go b/controller/subscribe/iml.go index ff9da18..0c4bed3 100644 --- a/controller/subscribe/iml.go +++ b/controller/subscribe/iml.go @@ -21,32 +21,32 @@ type imlSubscribeController struct { // return i.module.PartitionServices(ctx, app) //} -func (i *imlSubscribeController) SearchSubscriptions(ctx *gin.Context, partitionId string, projectId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { - return i.module.SearchSubscriptions(ctx, partitionId, projectId, keyword) +func (i *imlSubscribeController) SearchSubscriptions(ctx *gin.Context, appId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { + return i.module.SearchSubscriptions(ctx, appId, keyword) } -func (i *imlSubscribeController) RevokeSubscription(ctx *gin.Context, project string, uuid string) error { - return i.module.RevokeSubscription(ctx, project, uuid) +func (i *imlSubscribeController) RevokeSubscription(ctx *gin.Context, service string, uuid string) error { + return i.module.RevokeSubscription(ctx, service, uuid) } -func (i *imlSubscribeController) DeleteSubscription(ctx *gin.Context, project string, uuid string) error { - return i.module.DeleteSubscription(ctx, project, uuid) +func (i *imlSubscribeController) DeleteSubscription(ctx *gin.Context, service string, uuid string) error { + return i.module.DeleteSubscription(ctx, service, uuid) } -func (i *imlSubscribeController) AddSubscriber(ctx *gin.Context, project string, input *subscribe_dto.AddSubscriber) error { - return i.module.AddSubscriber(ctx, project, input) +func (i *imlSubscribeController) AddSubscriber(ctx *gin.Context, service string, input *subscribe_dto.AddSubscriber) error { + return i.module.AddSubscriber(ctx, service, input) } -func (i *imlSubscribeController) DeleteSubscriber(ctx *gin.Context, project string, serviceId string, applicationId string) error { - return i.module.DeleteSubscriber(ctx, project, serviceId, applicationId) +func (i *imlSubscribeController) DeleteSubscriber(ctx *gin.Context, service string, serviceId string, applicationId string) error { + return i.module.DeleteSubscriber(ctx, service, serviceId, applicationId) } -func (i *imlSubscribeController) RevokeApply(ctx *gin.Context, project string, uuid string) error { - return i.module.RevokeApply(ctx, project, uuid) +func (i *imlSubscribeController) RevokeApply(ctx *gin.Context, service string, uuid string) error { + return i.module.RevokeApply(ctx, service, uuid) } -func (i *imlSubscribeController) Search(ctx *gin.Context, project string, keyword string) ([]*subscribe_dto.Subscriber, error) { - return i.module.SearchSubscribers(ctx, project, keyword) +func (i *imlSubscribeController) Search(ctx *gin.Context, service string, keyword string) ([]*subscribe_dto.Subscriber, error) { + return i.module.SearchSubscribers(ctx, service, keyword) } var _ ISubscribeApprovalController = (*imlSubscribeApprovalController)(nil) @@ -55,20 +55,20 @@ type imlSubscribeApprovalController struct { module subscribe.ISubscribeApprovalModule `autowired:""` } -func (i *imlSubscribeApprovalController) GetApprovalList(ctx *gin.Context, project string, status int) ([]*subscribe_dto.ApprovalItem, error) { - return i.module.GetApprovalList(ctx, project, status) +func (i *imlSubscribeApprovalController) GetApprovalList(ctx *gin.Context, service string, status int) ([]*subscribe_dto.ApprovalItem, error) { + return i.module.GetApprovalList(ctx, service, status) } -func (i *imlSubscribeApprovalController) GetApprovalDetail(ctx *gin.Context, project string, id string) (*subscribe_dto.Approval, error) { - return i.module.GetApprovalDetail(ctx, project, id) +func (i *imlSubscribeApprovalController) GetApprovalDetail(ctx *gin.Context, service string, id string) (*subscribe_dto.Approval, error) { + return i.module.GetApprovalDetail(ctx, service, id) } -func (i *imlSubscribeApprovalController) Approval(ctx *gin.Context, project string, id string, approveInfo *subscribe_dto.Approve) error { +func (i *imlSubscribeApprovalController) Approval(ctx *gin.Context, service string, id string, approveInfo *subscribe_dto.Approve) error { switch approveInfo.Operate { case "pass": - return i.module.Pass(ctx, project, id, approveInfo) + return i.module.Pass(ctx, service, id, approveInfo) case "refuse": - return i.module.Reject(ctx, project, id, approveInfo) + return i.module.Reject(ctx, service, id, approveInfo) } return fmt.Errorf("unknown operate: %s", approveInfo.Operate) } diff --git a/controller/subscribe/subscribe.go b/controller/subscribe/subscribe.go index fab292f..aeb2d89 100644 --- a/controller/subscribe/subscribe.go +++ b/controller/subscribe/subscribe.go @@ -18,7 +18,7 @@ type ISubscribeController interface { // Search 关键字获取订阅者列表 Search(ctx *gin.Context, project string, keyword string) ([]*subscribe_dto.Subscriber, error) // SearchSubscriptions 关键字获取订阅服务列表 - SearchSubscriptions(ctx *gin.Context, partitionId string, projectId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) + SearchSubscriptions(ctx *gin.Context, appId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) // RevokeSubscription 取消订阅 RevokeSubscription(ctx *gin.Context, project string, uuid string) error // DeleteSubscription 删除订阅 diff --git a/module/catalogue/dto/input.go b/module/catalogue/dto/input.go index 54d22b4..11fb91b 100644 --- a/module/catalogue/dto/input.go +++ b/module/catalogue/dto/input.go @@ -13,7 +13,6 @@ type EditCatalogue struct { type SubscribeService struct { Service string `json:"service"` - Partitions []string `json:"partitions" aocheck:"partition"` Applications []string `json:"applications" aocheck:"project"` Reason string `json:"reason"` } diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index d991b03..684e114 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -20,12 +20,12 @@ type ServiceItem struct { } type ServiceDetail struct { - Name string `json:"name"` - Description string `json:"description"` - Document string `json:"document"` - Basic *ServiceBasic `json:"basic"` - Apis []*ServiceApi `json:"apis"` - DisableApis []*ServiceApiBasic `json:"disable_apis"` + Name string `json:"name"` + Description string `json:"description"` + Document string `json:"document"` + Basic *ServiceBasic `json:"basic"` + Apis []*ServiceApi `json:"apis"` + //DisableApis []*ServiceApiBasic `json:"disable_apis"` } type ServiceBasic struct { diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index 7a88ab7..a99c59b 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -2,9 +2,11 @@ package catalogue import ( "context" + "encoding/json" "errors" "fmt" "math" + "sort" service_doc "github.com/eolinker/apipark/service/service-doc" @@ -41,7 +43,6 @@ var ( type imlCatalogueModule struct { catalogueService catalogue.ICatalogueService `autowired:""` - projectService service.IServiceService `autowired:""` apiService api.IAPIService `autowired:""` serviceService service.IServiceService `autowired:""` serviceTagService service_tag.ITagService `autowired:""` @@ -64,43 +65,58 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal if err != nil { return fmt.Errorf("get service failed: %w", err) } + if !s.AsServer { + return fmt.Errorf("service does not support subscribe") + } userId := utils.UserId(ctx) return i.transaction.Transaction(ctx, func(ctx context.Context) error { - projects := make([]string, 0, len(subscribeInfo.Applications)) + apps := make([]string, 0, len(subscribeInfo.Applications)) - for _, pid := range subscribeInfo.Applications { - if pid == s.Id { + for _, appId := range subscribeInfo.Applications { + if appId == s.Id { // 不能订阅自己 continue } - pInfo, err := i.projectService.Get(ctx, pid) + appInfo, err := i.serviceService.Get(ctx, appId) if err != nil { return err } - if !pInfo.AsApp { + if !appInfo.AsApp { // 当系统不可作为订阅方时,不可订阅 continue } - applyID := uuid.New().String() - // 创建一条审核申请 - err = i.subscribeApplyService.Create(ctx, &subscribe.CreateApply{ - Uuid: applyID, - Service: subscribeInfo.Service, - Team: s.Team, - Application: pid, - ApplyTeam: pInfo.Team, - Reason: subscribeInfo.Reason, - Status: subscribe.ApplyStatusReview, - Applier: userId, - }) + info, err := i.subscribeApplyService.GetApply(ctx, subscribeInfo.Service, appId) + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } + err = i.subscribeApplyService.Create(ctx, &subscribe.CreateApply{ + Uuid: uuid.New().String(), + Service: subscribeInfo.Service, + Team: s.Team, + Application: appId, + ApplyTeam: appInfo.Team, + Reason: subscribeInfo.Reason, + Status: subscribe.ApplyStatusReview, + Applier: userId, + }) + + } else { + status := subscribe.ApplyStatusReview + err = i.subscribeApplyService.Save(ctx, info.Id, &subscribe.EditApply{ + Status: &status, + Applier: &userId, + }) + } if err != nil { return err } + // 修改订阅表状态 - subscriber, err := i.subscribeService.ListByApplication(ctx, subscribeInfo.Service, pid) + subscribers, err := i.subscribeService.ListByApplication(ctx, subscribeInfo.Service, appId) if err != nil { if !errors.Is(err, gorm.ErrRecordNotFound) { return err @@ -108,7 +124,7 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ Uuid: uuid.New().String(), Service: subscribeInfo.Service, - Application: pid, + Application: appId, ApplyStatus: subscribe.ApplyStatusReview, From: subscribe.FromSubscribe, }) @@ -117,15 +133,15 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal } } else { - subscriberMap := utils.SliceToMap(subscriber, func(t *subscribe.Subscribe) string { + subscriberMap := utils.SliceToMap(subscribers, func(t *subscribe.Subscribe) string { return t.Application }) - v, has := subscriberMap[pid] + v, has := subscriberMap[appId] if !has { err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ Uuid: uuid.New().String(), Service: subscribeInfo.Service, - Application: pid, + Application: appId, ApplyStatus: subscribe.ApplyStatusReview, From: subscribe.FromSubscribe, }) @@ -141,10 +157,10 @@ func (i *imlCatalogueModule) Subscribe(ctx context.Context, subscribeInfo *catal } - projects = append(projects, pid) + apps = append(apps, appId) } - if len(projects) == 0 { - return fmt.Errorf("no available projects") + if len(apps) == 0 { + return fmt.Errorf("no available apps") } return nil }) @@ -175,7 +191,6 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Description: s.Description, Document: docStr, Basic: &catalogue_dto.ServiceBasic{ - //Service: auto.UUID(s.Id), Team: auto.UUID(s.Team), ApiNum: 0, }, @@ -186,85 +201,69 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca } _, docCommits, _, err := i.releaseService.GetReleaseInfos(ctx, r.UUID) if err != nil { - return nil, fmt.Errorf("get release apis failed: %w", err) } - apiMap := utils.SliceToMap(docCommits, func(t *release.APIDocumentCommit) string { - return t.API - }) - fmt.Println("apiMap", apiMap) - - //apiList, err := i.serviceApiService.List(ctx, sid) - //if err != nil { - // return nil, err - //} - //apis := make([]*catalogue_dto.ServiceApi, 0, len(apiList)) - //disableApis := make([]*catalogue_dto.ServiceApiBasic, 0, len(apiList)) - //for _, a := range apiList { - // - // apiInfo, err := i.apiService.GetInfo(ctx, a.Aid) - // if err != nil { - // return nil, err - // } - // basicApi := &catalogue_dto.ServiceApiBasic{ - // Id: apiInfo.UUID, - // Name: apiInfo.Name, - // Description: apiInfo.Description, - // Method: apiInfo.Method, - // Path: apiInfo.Path, - // Creator: auto.UUID(apiInfo.Creator), - // Updater: auto.UUID(apiInfo.Updater), - // CreateTime: auto.TimeLabel(apiInfo.CreateAt), - // UpdateTime: auto.TimeLabel(apiInfo.UpdateAt), - // } - // v, ok := apiMap[a.Aid] - // if !ok { - // disableApis = append(disableApis, basicApi) - // continue - // } - // commit, err := i.apiService.GetDocumentCommit(ctx, v.Commit) - // if err != nil { - // return nil, err - // } - // tmp := make(map[string]interface{}) - // if commit.Data != nil { - // err = json.Unmarshal([]byte(commit.Data.Content), &tmp) - // if err != nil { - // return nil, err - // } - // } - // - // apis = append(apis, &catalogue_dto.ServiceApi{ - // ServiceApiBasic: basicApi, - // Doc: tmp, - // }) - //} - //subscribers, err := i.subscribeService.ListByServices(ctx, sid) - //if err != nil { - // return nil, err - //} - //subscribeCount := map[string]int{} - //tmp := map[string]struct{}{} - //for _, s := range subscribers { - // key := fmt.Sprintf("%s-%s", s.Service, s.Application) - // if _, ok := tmp[key]; !ok { - // tmp[key] = struct{}{} - // subscribeCount[s.Service]++ - // } - //} - //return &catalogue_dto.ServiceDetail{ - // Name: s.Name, - // Description: s.Description, - // Document: docStr, - // Basic: &catalogue_dto.ServiceBasic{ - // //Service: auto.UUID(s.Service), - // Team: auto.UUID(s.Team), - // ApiNum: len(apis), - // SubscriberNum: subscribeCount[s.Id], - // }, - // Apis: apis, - //}, nil - return nil, nil + apiMap := make(map[string]*release.APIDocumentCommit) + apiIds := make([]string, 0, len(docCommits)) + for _, v := range docCommits { + apiIds = append(apiIds, v.API) + apiMap[v.API] = v + } + apiList, err := i.apiService.ListInfo(ctx, apiIds...) + if err != nil { + return nil, err + } + + apis := make([]*catalogue_dto.ServiceApi, 0, len(apiList)) + for _, info := range apiList { + basicApi := &catalogue_dto.ServiceApiBasic{ + Id: info.UUID, + Name: info.Name, + Description: info.Description, + Method: info.Method, + Path: info.Path, + Creator: auto.UUID(info.Creator), + Updater: auto.UUID(info.Updater), + CreateTime: auto.TimeLabel(info.CreateAt), + UpdateTime: auto.TimeLabel(info.UpdateAt), + } + v, ok := apiMap[info.UUID] + if !ok { + continue + } + commit, err := i.apiService.GetDocumentCommit(ctx, v.Commit) + if err != nil { + return nil, err + } + tmp := make(map[string]interface{}) + if commit.Data != nil { + err = json.Unmarshal([]byte(commit.Data.Content), &tmp) + if err != nil { + return nil, err + } + } + + apis = append(apis, &catalogue_dto.ServiceApi{ + ServiceApiBasic: basicApi, + Doc: tmp, + }) + } + countMap, err := i.subscribeService.CountMapByService(ctx, subscribe.ApplyStatusSubscribe, sid) + if err != nil { + return nil, err + } + + return &catalogue_dto.ServiceDetail{ + Name: s.Name, + Description: s.Description, + Document: docStr, + Basic: &catalogue_dto.ServiceBasic{ + Team: auto.UUID(s.Team), + ApiNum: len(apis), + SubscriberNum: int(countMap[s.Id]), + }, + Apis: apis, + }, nil } func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*catalogue_dto.ServiceItem, error) { @@ -277,64 +276,60 @@ func (i *imlCatalogueModule) Services(ctx context.Context, keyword string) ([]*c return t.Sid, t.Tid }) - items, err := i.serviceService.Search(ctx, keyword, nil) + items, err := i.serviceService.SearchPublicServices(ctx, keyword) + if err != nil { + return nil, err + } + serviceIds := utils.SliceToSlice(items, func(i *service.Service) string { + return i.Id + }, func(s *service.Service) bool { + // 未发布的不给展示 + _, err = i.releaseService.GetRunning(ctx, s.Id) + return err == nil + }) + if len(serviceIds) < 1 { + return nil, nil + } + + // 获取服务API数量 + apiCountMap, err := i.apiService.CountMapByService(ctx, serviceIds...) if err != nil { return nil, err } - fmt.Println("items", items, serviceTagMap) - //serviceApiCountMap, err := i.serviceApiService.CountBySids(ctx) - //if err != nil { - // return nil, err - //} - //subscribers, err := i.subscribeService.ListByServices(ctx) - //if err != nil { - // return nil, err - //} - //subscribeCount := map[string]int64{} - //tmp := map[string]struct{}{} - //for _, s := range subscribers { - // if s.ApplyStatus != subscribe.ApplyStatusSubscribe { - // continue - // } - // key := fmt.Sprintf("%s-%s", s.Service, s.Application) - // if _, ok := tmp[key]; !ok { - // tmp[key] = struct{}{} - // subscribeCount[s.Service]++ - // } - //} - //result := make([]*catalogue_dto.ServiceItem, 0, len(items)) - //for _, v := range items { - // apiNum, ok := serviceApiCountMap[v.Id] - // if !ok || apiNum < 1 { - // continue - // } - // //ps := utils.Intersection(servicePartitionMap[v.Id], projectPartitionMap[v.Service]) - // //if len(ps) < 1 { - // // continue - // //} - // result = append(result, &catalogue_dto.ServiceItem{ - // Id: v.Id, - // Name: v.Name, - // Tags: auto.List(serviceTagMap[v.Id]), - // Catalogue: auto.UUID(v.Catalogue), - // //Cluster: auto.List(ps), - // ApiNum: apiNum, - // SubscriberNum: subscribeCount[v.Id], - // Description: v.Description, - // Logo: v.Logo, - // }) - //} - //sort.Slice(result, func(i, j int) bool { - // if result[i].SubscriberNum != result[j].SubscriberNum { - // return result[i].SubscriberNum > result[j].SubscriberNum - // } - // if result[i].ApiNum != result[j].ApiNum { - // return result[i].ApiNum > result[j].ApiNum - // } - // return result[i].Name < result[j].Name - //}) - //return result, nil - return nil, nil + + subscriberCountMap, err := i.subscribeService.CountMapByService(ctx, subscribe.ApplyStatusSubscribe, serviceIds...) + if err != nil { + return nil, err + } + + result := make([]*catalogue_dto.ServiceItem, 0, len(items)) + for _, v := range items { + apiNum, ok := apiCountMap[v.Id] + if !ok || apiNum < 1 { + continue + } + + result = append(result, &catalogue_dto.ServiceItem{ + Id: v.Id, + Name: v.Name, + Tags: auto.List(serviceTagMap[v.Id]), + Catalogue: auto.UUID(v.Catalogue), + ApiNum: apiNum, + SubscriberNum: subscriberCountMap[v.Id], + Description: v.Description, + Logo: v.Logo, + }) + } + sort.Slice(result, func(i, j int) bool { + if result[i].SubscriberNum != result[j].SubscriberNum { + return result[i].SubscriberNum > result[j].SubscriberNum + } + if result[i].ApiNum != result[j].ApiNum { + return result[i].ApiNum > result[j].ApiNum + } + return result[i].Name < result[j].Name + }) + return result, nil } func (i *imlCatalogueModule) recurseUpdateSort(ctx context.Context, parent string, sorts []*catalogue_dto.SortItem) error { diff --git a/module/service/dto/input.go b/module/service/dto/input.go index cdfa683..3607450 100644 --- a/module/service/dto/input.go +++ b/module/service/dto/input.go @@ -6,6 +6,7 @@ type CreateService struct { Prefix string `json:"prefix"` Description string `json:"description"` ServiceType string `json:"service_type"` + Catalogue string `json:"catalogue" aocheck:"catalogue"` AsApp *bool `json:"as_app"` AsServer *bool `json:"as_server"` } @@ -14,6 +15,7 @@ type EditService struct { Name *string `json:"name"` Description *string `json:"description"` ServiceType *string `json:"service_type"` + Catalogue *string `json:"catalogue" aocheck:"catalogue"` Logo *string `json:"logo"` Tags *[]string `json:"tags"` } diff --git a/module/service/dto/output.go b/module/service/dto/output.go index b14fbc2..2524474 100644 --- a/module/service/dto/output.go +++ b/module/service/dto/output.go @@ -51,6 +51,7 @@ type Service struct { CreateTime auto.TimeLabel `json:"create_time"` UpdateTime auto.TimeLabel `json:"update_time"` ServiceType string `json:"service_type"` + Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` Tags []auto.Label `json:"tags" aolabel:"tag"` Logo string `json:"logo"` AsServer bool `json:"as_server"` @@ -76,6 +77,7 @@ func ToService(model *service.Service) *Service { Team: auto.UUID(model.Team), ServiceType: model.ServiceType.String(), Logo: model.Logo, + Catalogue: auto.UUID(model.Catalogue), CreateTime: auto.TimeLabel(model.CreateTime), UpdateTime: auto.TimeLabel(model.UpdateTime), AsServer: model.AsServer, diff --git a/module/service/iml.go b/module/service/iml.go index cadd493..28dc32c 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -244,8 +244,12 @@ func (i *imlServiceModule) Create(ctx context.Context, teamID string, input *ser Description: input.Description, Team: teamID, ServiceType: service.ServiceType(input.ServiceType), + Catalogue: input.Catalogue, Prefix: input.Prefix, } + if mo.ServiceType == service.PublicService && mo.Catalogue == "" { + return nil, fmt.Errorf("catalogue can not be empty") + } if input.AsApp == nil { // 默认值为false mo.AsApp = false @@ -274,12 +278,19 @@ func (i *imlServiceModule) Edit(ctx context.Context, id string, input *service_d return nil, err } err = i.transaction.Transaction(ctx, func(ctx context.Context) error { + serviceType := (*service.ServiceType)(input.ServiceType) + if serviceType != nil && *serviceType == service.PublicService { + if input.Catalogue == nil || *input.Catalogue == "" { + return fmt.Errorf("catalogue can not be empty") + } + } err = i.serviceService.Save(ctx, id, &service.Edit{ Name: input.Name, Description: input.Description, Logo: input.Logo, - ServiceType: (*service.ServiceType)(input.ServiceType), + ServiceType: serviceType, + Catalogue: input.Catalogue, }) if err != nil { return err diff --git a/module/subscribe/dto/input.go b/module/subscribe/dto/input.go index 4f8dc66..56b4d6a 100644 --- a/module/subscribe/dto/input.go +++ b/module/subscribe/dto/input.go @@ -1,10 +1,8 @@ package subscribe_dto type AddSubscriber struct { - Uuid string `json:"uuid"` - Service string `json:"service" aocheck:"service"` - Project string `json:"subscriber" aocheck:"project"` - Applier string `json:"applier" aocheck:"user"` + Application string `json:"application" aocheck:"service"` + Applier string `json:"applier" aocheck:"user"` //Cluster []string `json:"partition" aocheck:"partition"` } diff --git a/module/subscribe/dto/output.go b/module/subscribe/dto/output.go index 2baaaf5..d3c8fe0 100644 --- a/module/subscribe/dto/output.go +++ b/module/subscribe/dto/output.go @@ -4,14 +4,13 @@ import "github.com/eolinker/go-common/auto" type Subscriber struct { Id string `json:"id"` - Project auto.Label `json:"project" aolabel:"project"` Service auto.Label `json:"service" aolabel:"service"` //Cluster []auto.Label `json:"partition" aolabel:"partition"` - Subscriber auto.Label `json:"subscriber" aolabel:"project"` + Subscriber auto.Label `json:"subscriber" aolabel:"service"` Team auto.Label `json:"team" aolabel:"team"` ApplyTime auto.TimeLabel `json:"apply_time"` - //Applier auto.Label `json:"applier" aolabel:"user"` + Applier auto.Label `json:"applier" aolabel:"user"` //Approver auto.Label `json:"approver" aolabel:"user"` From int `json:"from"` } @@ -21,7 +20,6 @@ type SubscriptionItem struct { Service auto.Label `json:"service" aolabel:"service"` //Cluster auto.Label `json:"partition" aolabel:"partition"` ApplyStatus int `json:"apply_status"` - Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` //Applier auto.Label `json:"applier" aolabel:"user"` From int `json:"from"` @@ -31,9 +29,8 @@ type SubscriptionItem struct { type Approval struct { Id string `json:"id,omitempty"` Service auto.Label `json:"service" aolabel:"service"` - Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` - ApplyProject auto.Label `json:"apply_project" aolabel:"project"` + Application auto.Label `json:"application" aolabel:"service"` ApplyTeam auto.Label `json:"apply_team" aolabel:"team"` ApplyTime auto.TimeLabel `json:"apply_time"` Applier auto.Label `json:"applier" aolabel:"user"` @@ -47,9 +44,8 @@ type Approval struct { type ApprovalItem struct { Id string `json:"id"` Service auto.Label `json:"service" aolabel:"service"` - Project auto.Label `json:"project" aolabel:"project"` Team auto.Label `json:"team" aolabel:"team"` - ApplyProject auto.Label `json:"apply_project" aolabel:"project"` + Application auto.Label `json:"application" aolabel:"service"` ApplyTeam auto.Label `json:"apply_team" aolabel:"team"` ApplyTime auto.TimeLabel `json:"apply_time"` Applier auto.Label `json:"applier" aolabel:"user"` diff --git a/module/subscribe/iml.go b/module/subscribe/iml.go index 961a03f..1a2bb88 100644 --- a/module/subscribe/iml.go +++ b/module/subscribe/iml.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/google/uuid" + "github.com/eolinker/eosc/log" "github.com/eolinker/apipark/gateway" @@ -16,8 +18,6 @@ import ( "github.com/eolinker/go-common/store" - "github.com/google/uuid" - "github.com/eolinker/go-common/auto" "github.com/eolinker/apipark/service/subscribe" @@ -37,8 +37,8 @@ type imlSubscribeModule struct { transaction store.ITransaction `autowired:""` } -func (i *imlSubscribeModule) getSubscribers(ctx context.Context, projectIds []string) ([]*gateway.SubscribeRelease, error) { - subscribers, err := i.subscribeService.SubscribersByProject(ctx, projectIds...) +func (i *imlSubscribeModule) getSubscribers(ctx context.Context, serviceIds []string) ([]*gateway.SubscribeRelease, error) { + subscribers, err := i.subscribeService.SubscribersByProject(ctx, serviceIds...) if err != nil { return nil, err } @@ -57,10 +57,10 @@ func (i *imlSubscribeModule) initGateway(ctx context.Context, clientDriver gatew if err != nil { return err } - projectIds := utils.SliceToSlice(projects, func(p *service.Service) string { + serviceIds := utils.SliceToSlice(projects, func(p *service.Service) string { return p.Id }) - releases, err := i.getSubscribers(ctx, projectIds) + releases, err := i.getSubscribers(ctx, serviceIds) if err != nil { return err } @@ -68,58 +68,56 @@ func (i *imlSubscribeModule) initGateway(ctx context.Context, clientDriver gatew return clientDriver.Subscribe().Online(ctx, releases...) } -func (i *imlSubscribeModule) SearchSubscriptions(ctx context.Context, partitionId string, app string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { - //pInfo, err := i.serviceService.Get(ctx, app) - //if err != nil { - // return nil, fmt.Errorf("get application error: %w", err) - //} - //if !pInfo.AsApp { - // return nil, fmt.Errorf("project %s is not an application", app) - //} - // - //// 获取当前订阅服务列表 - //subscriptions, err := i.subscribeService.MySubscribeServices(ctx, app, nil, nil, partitionId) - //if err != nil { - // return nil, err - //} - //serviceIds := utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) string { - // return s.Service - //}) - //services, err := i.serviceService.SearchByUuids(ctx, keyword, serviceIds...) - //if err != nil { - // return nil, fmt.Errorf("search service error: %w", err) - //} - //serviceMap := utils.SliceToMapArray(services, func(s *service.Service) string { - // return s.Id - //}) - - //return utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) *subscribe_dto.SubscriptionItem { - // return &subscribe_dto.SubscriptionItem{ - // Id: s.Id, - // Service: auto.UUID(s.Service), - // ApplyStatus: s.ApplyStatus, - // Service: auto.UUID(s.Service), - // Team: auto.UUID(pInfo.Team), - // From: s.From, - // CreateTime: auto.TimeLabel(s.CreateAt), - // } - //}, func(s *subscribe.Subscribe) bool { - // _, ok := serviceMap[s.Service] - // if !ok { - // return false - // } - // if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { - // return false - // } - // return true - //}), nil - return nil, nil +func (i *imlSubscribeModule) SearchSubscriptions(ctx context.Context, appId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) { + info, err := i.serviceService.Get(ctx, appId) + if err != nil { + return nil, fmt.Errorf("get application error: %w", err) + } + if !info.AsApp { + return nil, fmt.Errorf("service %s is not an application", appId) + } + + // 获取当前订阅服务列表 + subscriptions, err := i.subscribeService.MySubscribeServices(ctx, appId, nil) + if err != nil { + return nil, err + } + serviceIds := utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) string { + return s.Service + }) + services, err := i.serviceService.List(ctx, serviceIds...) + if err != nil { + return nil, fmt.Errorf("search service error: %w", err) + } + serviceMap := utils.SliceToMapArray(services, func(s *service.Service) string { + return s.Id + }) + + return utils.SliceToSlice(subscriptions, func(s *subscribe.Subscribe) *subscribe_dto.SubscriptionItem { + return &subscribe_dto.SubscriptionItem{ + Id: s.Id, + ApplyStatus: s.ApplyStatus, + Service: auto.UUID(s.Service), + Team: auto.UUID(info.Team), + From: s.From, + CreateTime: auto.TimeLabel(s.CreateAt), + } + }, func(s *subscribe.Subscribe) bool { + _, ok := serviceMap[s.Service] + if !ok { + return false + } + if s.ApplyStatus != subscribe.ApplyStatusSubscribe && s.ApplyStatus != subscribe.ApplyStatusReview { + return false + } + return true + }), nil } func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, uuid string) error { _, err := i.serviceService.Get(ctx, pid) if err != nil { - return fmt.Errorf("get project error: %w", err) + return fmt.Errorf("get service error: %w", err) } subscription, err := i.subscribeService.Get(ctx, uuid) if err != nil { @@ -159,7 +157,7 @@ func (i *imlSubscribeModule) RevokeSubscription(ctx context.Context, pid string, func (i *imlSubscribeModule) DeleteSubscription(ctx context.Context, pid string, uuid string) error { _, err := i.serviceService.Get(ctx, pid) if err != nil { - return fmt.Errorf("get project error: %w", err) + return fmt.Errorf("get service error: %w", err) } subscription, err := i.subscribeService.Get(ctx, uuid) if err != nil { @@ -189,18 +187,15 @@ func (i *imlSubscribeModule) RevokeApply(ctx context.Context, app string, uuid s }) } -func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, input *subscribe_dto.AddSubscriber) error { - _, err := i.serviceService.Get(ctx, project) +func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, serviceId string, input *subscribe_dto.AddSubscriber) error { + _, err := i.serviceService.Get(ctx, serviceId) if err != nil { return err } - if input.Uuid == "" { - input.Uuid = uuid.New().String() - } sub := &gateway.SubscribeRelease{ - Service: input.Service, - Application: input.Project, + Service: serviceId, + Application: input.Application, Expired: "0", } clusters, err := i.clusterService.List(ctx) @@ -210,12 +205,12 @@ func (i *imlSubscribeModule) AddSubscriber(ctx context.Context, project string, return i.transaction.Transaction(ctx, func(ctx context.Context) error { err = i.subscribeService.Create(ctx, &subscribe.CreateSubscribe{ - Uuid: input.Uuid, - Service: input.Service, - Project: project, - Application: input.Project, + Uuid: uuid.New().String(), + Service: serviceId, + Application: input.Application, ApplyStatus: subscribe.ApplyStatusSubscribe, From: subscribe.FromUser, + Applier: input.Applier, }) if err != nil { return err @@ -245,8 +240,8 @@ func (i *imlSubscribeModule) onlineSubscriber(ctx context.Context, clusterId str } -func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, project string, serviceId string, applicationId string) error { - _, err := i.serviceService.Get(ctx, project) +func (i *imlSubscribeModule) DeleteSubscriber(ctx context.Context, service string, serviceId string, applicationId string) error { + _, err := i.serviceService.Get(ctx, service) if err != nil { return err } @@ -291,14 +286,14 @@ func (i *imlSubscribeModule) offlineForCluster(ctx context.Context, clusterId st return client.Subscribe().Offline(ctx, config) } -func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId string, keyword string) ([]*subscribe_dto.Subscriber, error) { - pInfo, err := i.serviceService.Get(ctx, projectId) +func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, serviceId string, keyword string) ([]*subscribe_dto.Subscriber, error) { + pInfo, err := i.serviceService.Get(ctx, serviceId) if err != nil { return nil, err } // 获取当前项目所有订阅方 - list, err := i.subscribeService.ListBySubscribeStatus(ctx, projectId, subscribe.ApplyStatusSubscribe) + list, err := i.subscribeService.ListBySubscribeStatus(ctx, serviceId, subscribe.ApplyStatusSubscribe) if err != nil { return nil, err } @@ -308,10 +303,10 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st for _, subscriber := range list { items = append(items, &subscribe_dto.Subscriber{ Id: subscriber.Application, - Project: auto.UUID(subscriber.Project), Service: auto.UUID(subscriber.Service), Subscriber: auto.UUID(subscriber.Application), Team: auto.UUID(pInfo.Team), + Applier: auto.UUID(subscriber.Applier), ApplyTime: auto.TimeLabel(subscriber.CreateAt), From: subscriber.From, }) @@ -319,7 +314,7 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st return items, nil } serviceList, err := i.serviceService.Search(ctx, keyword, map[string]interface{}{ - "project": projectId, + "service": serviceId, }) if err != nil { return nil, err @@ -333,7 +328,6 @@ func (i *imlSubscribeModule) SearchSubscribers(ctx context.Context, projectId st if _, ok := serviceMap[subscriber.Service]; ok { items = append(items, &subscribe_dto.Subscriber{ Id: subscriber.Id, - Project: auto.UUID(subscriber.Project), Service: auto.UUID(subscriber.Service), Subscriber: auto.UUID(subscriber.Application), Team: auto.UUID(pInfo.Team), @@ -444,9 +438,8 @@ func (i *imlSubscribeApprovalModule) GetApprovalList(ctx context.Context, pid st return &subscribe_dto.ApprovalItem{ Id: s.Id, Service: auto.UUID(s.Service), - Project: auto.UUID(s.Project), Team: auto.UUID(s.Team), - ApplyProject: auto.UUID(s.Application), + Application: auto.UUID(s.Application), ApplyTeam: auto.UUID(s.ApplyTeam), ApplyTime: auto.TimeLabel(s.ApplyAt), Applier: auto.UUID(s.Applier), @@ -470,9 +463,8 @@ func (i *imlSubscribeApprovalModule) GetApprovalDetail(ctx context.Context, pid return &subscribe_dto.Approval{ Id: item.Id, Service: auto.UUID(item.Service), - Project: auto.UUID(item.Project), Team: auto.UUID(item.Team), - ApplyProject: auto.UUID(item.Application), + Application: auto.UUID(item.Application), ApplyTeam: auto.UUID(item.ApplyTeam), ApplyTime: auto.TimeLabel(item.ApplyAt), Applier: auto.UUID(item.Applier), diff --git a/module/subscribe/subscribe.go b/module/subscribe/subscribe.go index 110e75e..659312d 100644 --- a/module/subscribe/subscribe.go +++ b/module/subscribe/subscribe.go @@ -17,7 +17,7 @@ type ISubscribeModule interface { // SearchSubscribers 关键字获取订阅方列表 SearchSubscribers(ctx context.Context, pid string, keyword string) ([]*subscribe_dto.Subscriber, error) // SearchSubscriptions 关键字获取订阅服务列表 - SearchSubscriptions(ctx context.Context, partitionId string, app string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) + SearchSubscriptions(ctx context.Context, appId string, keyword string) ([]*subscribe_dto.SubscriptionItem, error) // RevokeSubscription 取消订阅 RevokeSubscription(ctx context.Context, pid string, uuid string) error // DeleteSubscription 删除订阅 diff --git a/plugins/core/service.go b/plugins/core/service.go index de4a307..57d087f 100644 --- a/plugins/core/service.go +++ b/plugins/core/service.go @@ -26,7 +26,7 @@ func (p *plugin) ServiceApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_apps", []string{"context", "query:team", "query:keyword"}, []string{"apps"}, p.appController.SearchMyApps), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/app/info", []string{"context", "query:app", "body"}, []string{"app"}, p.appController.UpdateApp), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/service/doc", []string{"context", "query:service"}, []string{"doc"}, p.serviceController.ServiceDoc), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/service/doc", []string{"context", "query:service", "body"}, nil, p.serviceController.SaveServiceDoc), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/doc", []string{"context", "query:service"}, []string{"doc"}, p.serviceController.ServiceDoc), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/doc", []string{"context", "query:service", "body"}, nil, p.serviceController.SaveServiceDoc), } } diff --git a/plugins/core/subscribe.go b/plugins/core/subscribe.go index 68868fb..8a0d7a7 100644 --- a/plugins/core/subscribe.go +++ b/plugins/core/subscribe.go @@ -8,20 +8,18 @@ import ( func (p *plugin) subscribeApis() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/subscribers", []string{"context", "query:project", "query:keyword"}, []string{"subscribers"}, p.subscribeController.Search), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/subscribers", []string{"context", "query:service", "query:keyword"}, []string{"subscribers"}, p.subscribeController.Search), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/subscriber", []string{"context", "query:project", "body"}, nil, p.subscribeController.AddSubscriber), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/subscriber", []string{"context", "query:project", "query:service", "query:application"}, nil, p.subscribeController.DeleteSubscriber), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/subscriber", []string{"context", "query:service", "body"}, nil, p.subscribeController.AddSubscriber), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/subscriber", []string{"context", "query:service", "query:service", "query:application"}, nil, p.subscribeController.DeleteSubscriber), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/application/subscriptions", []string{"context", "query:partition", "query:application", "query:keyword"}, []string{"subscriptions"}, p.subscribeController.SearchSubscriptions), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/application/subscriptions", []string{"context", "query:application", "query:keyword"}, []string{"subscriptions"}, p.subscribeController.SearchSubscriptions), pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/application/subscription/cancel", []string{"context", "query:application", "query:subscription"}, nil, p.subscribeController.RevokeSubscription), pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/application/subscription/cancel_apply", []string{"context", "query:application", "query:subscription"}, nil, p.subscribeController.RevokeApply), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/application/partitions", []string{"context", "query:application"}, []string{"partitions"}, p.subscribeController.PartitionServices), - // 审批相关 - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/approval/subscribes", []string{"context", "query:project", "query:status"}, []string{"approvals"}, p.subscribeApprovalController.GetApprovalList), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/approval/subscribe", []string{"context", "query:project", "query:application"}, []string{"approval"}, p.subscribeApprovalController.GetApprovalDetail), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/approval/subscribe", []string{"context", "query:project", "query:application", "body"}, nil, p.subscribeApprovalController.Approval), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/approval/subscribes", []string{"context", "query:service", "query:status"}, []string{"approvals"}, p.subscribeApprovalController.GetApprovalList), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/approval/subscribe", []string{"context", "query:service", "query:apply"}, []string{"approval"}, p.subscribeApprovalController.GetApprovalDetail), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/approval/subscribe", []string{"context", "query:service", "query:apply", "body"}, nil, p.subscribeApprovalController.Approval), } } diff --git a/plugins/publish_flow/apis.go b/plugins/publish_flow/apis.go index 7f659b1..d02819a 100644 --- a/plugins/publish_flow/apis.go +++ b/plugins/publish_flow/apis.go @@ -9,7 +9,7 @@ import ( func (p *plugin) getApis() []pm3.Api { return []pm3.Api{ pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/release", []string{"context", "query:service", "body"}, []string{"publish"}, p.controller.ApplyOnRelease), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/release/do", []string{"context", "query:service", "body"}, []string{}, p.controller.ReleaseDo), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/release/do", []string{"context", "query:service", "body"}, []string{"publish"}, p.controller.ReleaseDo), pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/service/publish/apply", []string{"context", "query:service", "body"}, []string{"publish"}, p.controller.Apply), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publishs", []string{"context", "query:service", "query:page", "query:page_size"}, []string{"publishs", "page", "size", "total"}, p.controller.ListPage), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/publish", []string{"context", "query:service", "query:id"}, []string{"publish"}, p.controller.Detail), diff --git a/service/api/iml.go b/service/api/iml.go index e056143..edb193c 100644 --- a/service/api/iml.go +++ b/service/api/iml.go @@ -40,6 +40,14 @@ type imlAPIService struct { universally.IServiceDelete } +func (i *imlAPIService) CountMapByService(ctx context.Context, service ...string) (map[string]int64, error) { + w := map[string]interface{}{} + if len(service) > 0 { + w["service"] = service + } + return i.store.CountByGroup(ctx, "", w, "service") +} + func (i *imlAPIService) ListInfoForService(ctx context.Context, serviceId string) ([]*Info, error) { apis, err := i.store.List(ctx, map[string]interface{}{ "service": serviceId, diff --git a/service/api/service.go b/service/api/service.go index e8fdf22..db74303 100644 --- a/service/api/service.go +++ b/service/api/service.go @@ -13,7 +13,8 @@ import ( type IAPIService interface { universally.IServiceGet[API] universally.IServiceDelete - CountByService(ctx context.Context, project string) (int64, error) + CountByService(ctx context.Context, service string) (int64, error) + CountMapByService(ctx context.Context, service ...string) (map[string]int64, error) Exist(ctx context.Context, aid string, api *ExistAPI) error ListForService(ctx context.Context, serviceId string) ([]*API, error) GetInfo(ctx context.Context, aid string) (*Info, error) diff --git a/service/release/service.go b/service/release/service.go index d3b45af..bdbb852 100644 --- a/service/release/service.go +++ b/service/release/service.go @@ -2,44 +2,40 @@ package release import ( "context" + "reflect" + "github.com/eolinker/apipark/service/api" "github.com/eolinker/apipark/service/universally/commit" "github.com/eolinker/apipark/service/upstream" "github.com/eolinker/go-common/autowire" - "reflect" ) type IReleaseService interface { // GetRelease 获取发布信息 GetRelease(ctx context.Context, id string) (*Release, error) // CreateRelease 创建发布 - CreateRelease(ctx context.Context, project string, version string, remark string, apisProxyCommits, apiDocCommits map[string]string, upstreams map[string]map[string]string) (*Release, error) - //Diff(ctx context.Context, baseReleaseId string, targetReleaseId string) (*Diff, error) - //DiffApis(ctx context.Context, baseAPi []*Api, targetAPiProxy []*Api) []*APiDiff - //DiffUpstreams(ctx context.Context, baseUpstream []*UpstreamCommit, targetUpstream []*UpstreamCommit) []*UpstreamDiff + CreateRelease(ctx context.Context, service string, version string, remark string, apisProxyCommits, apiDocCommits map[string]string, upstreams map[string]map[string]string) (*Release, error) // DeleteRelease 删除发布 DeleteRelease(ctx context.Context, id string) error - List(ctx context.Context, project string) ([]*Release, error) + List(ctx context.Context, service string) ([]*Release, error) GetApiProxyCommit(ctx context.Context, id string, apiUUID string) (string, error) GetApiDocCommit(ctx context.Context, id string, apiUUID string) (string, error) GetReleaseInfos(ctx context.Context, id string) ([]*APIProxyCommit, []*APIDocumentCommit, []*UpstreamCommit, error) - //GetApiProxyCommit(ctx context.Context, id string, apiUUID string) (string, error) - //GetApiDocCommit(ctx context.Context, id string, apiUUID string) (string, error) GetCommits(ctx context.Context, id string) ([]*ProjectCommits, error) - GetRunningApiDocCommit(ctx context.Context, project string, apiUUID string) (string, error) - GetRunningApiProxyCommit(ctx context.Context, project string, apiUUID string) (string, error) + GetRunningApiDocCommit(ctx context.Context, service string, apiUUID string) (string, error) + GetRunningApiProxyCommit(ctx context.Context, service string, apiUUID string) (string, error) Completeness(partitions []string, apis []string, proxyCommits []*commit.Commit[api.Proxy], documentCommits []*commit.Commit[api.Document], upstreamCommits []*commit.Commit[upstream.Config]) bool - // GetRunning gets the running release with the given project. + // GetRunning gets the running release with the given service. // // ctx: the context - // project: the project name + // service: the service name // Return type(s): *Release, error - GetRunning(ctx context.Context, project string) (*Release, error) + GetRunning(ctx context.Context, service string) (*Release, error) - SetRunning(ctx context.Context, project string, id string) error - CheckNewVersion(ctx context.Context, project string, version string) (bool, error) + SetRunning(ctx context.Context, service string, id string) error + CheckNewVersion(ctx context.Context, service string, version string) (bool, error) } func init() { diff --git a/service/service/iml.go b/service/service/iml.go index cc0013e..788f7c6 100644 --- a/service/service/iml.go +++ b/service/service/iml.go @@ -25,6 +25,18 @@ type imlServiceService struct { universally.IServiceEdit[Edit] } +func (i *imlServiceService) SearchPublicServices(ctx context.Context, keyword string) ([]*Service, error) { + w := map[string]interface{}{ + "as_server": true, + "service_type": PublicService.Int(), + } + list, err := i.store.Search(ctx, keyword, w) + if err != nil { + return nil, err + } + return utils.SliceToSlice(list, FromEntity), nil +} + func (i *imlServiceService) ServiceCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) { w := map[string]interface{}{ "as_server": true, @@ -117,6 +129,7 @@ func createEntityHandler(i *Create) *service.Service { Prefix: i.Prefix, Team: i.Team, ServiceType: i.ServiceType.Int(), + Catalogue: i.Catalogue, AsServer: i.AsServer, AsApp: i.AsApp, } @@ -131,6 +144,9 @@ func updateHandler(e *service.Service, i *Edit) { if i.ServiceType != nil { e.ServiceType = (*i.ServiceType).Int() } + if i.Catalogue != nil { + e.Catalogue = *i.Catalogue + } if i.Logo != nil { e.Logo = *i.Logo } diff --git a/service/service/model.go b/service/service/model.go index 1c94c3b..406fc2e 100644 --- a/service/service/model.go +++ b/service/service/model.go @@ -6,6 +6,12 @@ import ( "github.com/eolinker/apipark/stores/service" ) +const ( + InnerService ServiceType = "inner" + PublicService ServiceType = "public" + UnknownService ServiceType = "unknown" +) + type ServiceType string func (s ServiceType) String() string { @@ -14,9 +20,9 @@ func (s ServiceType) String() string { func (s ServiceType) Int() int { switch s { - case "inner": + case InnerService: return 1 - case "public": + case PublicService: return 2 default: return 0 @@ -27,11 +33,11 @@ func ToServiceType(s int) ServiceType { switch s { case 1: - return "inner" + return InnerService case 2: - return "public" + return PublicService default: - return "unknown" + return UnknownService } } @@ -43,6 +49,7 @@ type Service struct { Prefix string Logo string ServiceType ServiceType + Catalogue string AsServer bool AsApp bool CreateTime time.Time @@ -58,6 +65,7 @@ func FromEntity(e *service.Service) *Service { Prefix: e.Prefix, Logo: e.Logo, ServiceType: ToServiceType(e.ServiceType), + Catalogue: e.Catalogue, AsServer: e.AsServer, AsApp: e.AsApp, CreateTime: e.CreateAt, @@ -72,6 +80,7 @@ type Create struct { Team string Prefix string ServiceType ServiceType + Catalogue string AsServer bool AsApp bool } @@ -80,6 +89,7 @@ type Edit struct { Name *string Description *string ServiceType *ServiceType + Catalogue *string Logo *string } diff --git a/service/service/service.go b/service/service/service.go index dcbaf9c..523b073 100644 --- a/service/service/service.go +++ b/service/service/service.go @@ -15,6 +15,7 @@ type IServiceService interface { universally.IServiceEdit[Edit] ServiceCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) AppCountByTeam(ctx context.Context, teamId ...string) (map[string]int64, error) + SearchPublicServices(ctx context.Context, keyword string) ([]*Service, error) Check(ctx context.Context, id string, rule map[string]bool) (*Service, error) AppList(ctx context.Context, appIds ...string) ([]*Service, error) } diff --git a/service/subscribe/iml.go b/service/subscribe/iml.go index e6da918..1ffb99f 100644 --- a/service/subscribe/iml.go +++ b/service/subscribe/iml.go @@ -42,6 +42,16 @@ type imlSubscribeService struct { universally.IServiceEdit[UpdateSubscribe] } +func (i *imlSubscribeService) CountMapByService(ctx context.Context, status int, service ...string) (map[string]int64, error) { + w := make(map[string]interface{}) + if len(service) > 0 { + w["service"] = service + } + + w["apply_status"] = status + return i.store.CountByGroup(ctx, "", w, "service") +} + func (i *imlSubscribeService) ListByServices(ctx context.Context, serviceIds ...string) ([]*Subscribe, error) { w := make(map[string]interface{}) if len(serviceIds) > 0 { @@ -73,10 +83,10 @@ func (i *imlSubscribeService) DeleteByApplication(ctx context.Context, service s return err } -func (i *imlSubscribeService) SubscribersByProject(ctx context.Context, projectIds ...string) ([]*Subscribe, error) { +func (i *imlSubscribeService) SubscribersByProject(ctx context.Context, serviceIds ...string) ([]*Subscribe, error) { w := make(map[string]interface{}) - if len(projectIds) > 0 { - w["project"] = projectIds + if len(serviceIds) > 0 { + w["service"] = serviceIds } w["apply_status"] = ApplyStatusSubscribe @@ -87,18 +97,18 @@ func (i *imlSubscribeService) SubscribersByProject(ctx context.Context, projectI return utils.SliceToSlice(list, FromEntity), nil } -func (i *imlSubscribeService) Subscribers(ctx context.Context, project string, status int) ([]*Subscribe, error) { - list, err := i.store.List(ctx, map[string]interface{}{"apply_status": status, "project": project}, "create_at desc") +func (i *imlSubscribeService) Subscribers(ctx context.Context, service string, status int) ([]*Subscribe, error) { + list, err := i.store.List(ctx, map[string]interface{}{"apply_status": status, "service": service}, "create_at desc") if err != nil { return nil, err } return utils.SliceToSlice(list, FromEntity), nil } -func (i *imlSubscribeService) ListBySubscribeStatus(ctx context.Context, projectId string, status int) ([]*Subscribe, error) { +func (i *imlSubscribeService) ListBySubscribeStatus(ctx context.Context, serviceId string, status int) ([]*Subscribe, error) { w := make(map[string]interface{}) - if projectId != "" { - w["project"] = projectId + if serviceId != "" { + w["service"] = serviceId } w["apply_status"] = status list, err := i.store.List(ctx, w, "create_at desc") @@ -119,17 +129,15 @@ func (i *imlSubscribeService) UpdateSubscribeStatus(ctx context.Context, applica return i.store.Save(ctx, info) } -func (i *imlSubscribeService) MySubscribeServices(ctx context.Context, application string, projectIds []string, serviceIDs []string, partitionIds ...string) ([]*Subscribe, error) { +func (i *imlSubscribeService) MySubscribeServices(ctx context.Context, application string, serviceIDs []string) ([]*Subscribe, error) { w := make(map[string]interface{}) - if len(projectIds) > 0 { - w["project"] = projectIds - } + if len(serviceIDs) > 0 { w["service"] = serviceIDs } - if len(partitionIds) > 0 { - w["partition"] = partitionIds - } + //if len(partitionIds) > 0 { + // w["partition"] = partitionIds + //} w["application"] = application list, err := i.store.List(ctx, w, "create_at desc") if err != nil { @@ -170,10 +178,10 @@ func (i *imlSubscribeService) uniquestHandler(t *CreateSubscribe) []map[string]i func (i *imlSubscribeService) createEntityHandler(t *CreateSubscribe) *subscribe.Subscribe { return &subscribe.Subscribe{ UUID: t.Uuid, - Project: t.Project, Application: t.Application, Service: t.Service, From: t.From, + Applier: t.Applier, CreateAt: time.Now(), ApplyStatus: t.ApplyStatus, } @@ -204,9 +212,17 @@ type imlSubscribeApplyService struct { universally.IServiceEdit[EditApply] } +func (i *imlSubscribeApplyService) GetApply(ctx context.Context, serviceId string, appId string) (*Apply, error) { + info, err := i.store.First(ctx, map[string]interface{}{"service": serviceId, "application": appId}) + if err != nil { + return nil, err + } + return FromApplyEntity(info), err +} + func (i *imlSubscribeApplyService) ListByStatus(ctx context.Context, pid string, status ...int) ([]*Apply, error) { w := make(map[string]interface{}) - w["project"] = pid + w["service"] = pid if len(status) > 0 { w["status"] = status } @@ -267,6 +283,7 @@ func (i *imlSubscribeApplyService) createEntityHandler(t *CreateApply) *subscrib func (i *imlSubscribeApplyService) updateHandler(e *subscribe.Apply, t *EditApply) { if t.Approver != nil { e.Approver = *t.Approver + e.ApproveAt = time.Now() } if t.Status != nil { e.Status = *t.Status @@ -274,8 +291,8 @@ func (i *imlSubscribeApplyService) updateHandler(e *subscribe.Apply, t *EditAppl if t.Opinion != nil { e.Opinion = *t.Opinion } - if t.Approver != nil { - e.Approver = *t.Approver + if t.Applier != nil { + e.Applier = *t.Applier e.ApplyAt = time.Now() } diff --git a/service/subscribe/model.go b/service/subscribe/model.go index 863f782..e231104 100644 --- a/service/subscribe/model.go +++ b/service/subscribe/model.go @@ -7,25 +7,21 @@ import ( ) type Subscribe struct { - Id string - // 被订阅服务相关 - Project string + Id string Service string // 订阅方相关 Application string From int + Applier string ApplyStatus int CreateAt time.Time - //Applier string - //Approver string } type CreateSubscribe struct { - Uuid string - Service string - Project string - + Uuid string + Service string + Applier string Application string ApplyStatus int From int @@ -38,10 +34,10 @@ type UpdateSubscribe struct { func FromEntity(e *subscribe.Subscribe) *Subscribe { return &Subscribe{ Id: e.UUID, - Project: e.Project, Service: e.Service, ApplyStatus: e.ApplyStatus, Application: e.Application, + Applier: e.Applier, From: e.From, CreateAt: e.CreateAt, } @@ -61,13 +57,13 @@ type CreateApply struct { type EditApply struct { Opinion *string Status *int + Applier *string Approver *string } type Apply struct { Id string Service string - Project string Team string Application string ApplyTeam string @@ -84,7 +80,6 @@ func FromApplyEntity(e *subscribe.Apply) *Apply { return &Apply{ Id: e.Uuid, Service: e.Service, - Project: e.Project, Team: e.Team, Application: e.Application, ApplyTeam: e.ApplyTeam, diff --git a/service/subscribe/service.go b/service/subscribe/service.go index 47d004e..b8fc31b 100644 --- a/service/subscribe/service.go +++ b/service/subscribe/service.go @@ -13,11 +13,12 @@ type ISubscribeService interface { universally.IServiceDelete universally.IServiceCreate[CreateSubscribe] universally.IServiceEdit[UpdateSubscribe] + CountMapByService(ctx context.Context, status int, service ...string) (map[string]int64, error) DeleteByApplication(ctx context.Context, service string, application string) error ListByApplication(ctx context.Context, service string, application ...string) ([]*Subscribe, error) ListByServices(ctx context.Context, serviceIds ...string) ([]*Subscribe, error) - MySubscribeServices(ctx context.Context, application string, projectIds []string, serviceIDs []string, partitionIds ...string) ([]*Subscribe, error) + MySubscribeServices(ctx context.Context, application string, serviceIDs []string) ([]*Subscribe, error) UpdateSubscribeStatus(ctx context.Context, application string, service string, status int) error ListBySubscribeStatus(ctx context.Context, projectId string, status int) ([]*Subscribe, error) SubscribersByProject(ctx context.Context, projectIds ...string) ([]*Subscribe, error) @@ -30,6 +31,7 @@ type ISubscribeApplyService interface { universally.IServiceDelete universally.IServiceCreate[CreateApply] universally.IServiceEdit[EditApply] + GetApply(ctx context.Context, serviceId string, appId string) (*Apply, error) ListByStatus(ctx context.Context, pid string, status ...int) ([]*Apply, error) Revoke(ctx context.Context, service string, application string) error RevokeById(ctx context.Context, id string) error diff --git a/stores/service/model.go b/stores/service/model.go index d069bd5..49ddd4b 100644 --- a/stores/service/model.go +++ b/stores/service/model.go @@ -12,6 +12,7 @@ type Service struct { Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team"` // 团队id Logo string `gorm:"type:text;not null;column:logo;comment:logo"` ServiceType int `gorm:"type:int(11);not null;column:service_type;comment:服务类型"` + Catalogue string `gorm:"type:text;not null;column:catalogue;comment:目录"` CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间"` IsDelete int `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` diff --git a/stores/subscribe/model.go b/stores/subscribe/model.go index ea094fc..50e1133 100644 --- a/stores/subscribe/model.go +++ b/stores/subscribe/model.go @@ -5,10 +5,10 @@ import "time" type Subscribe struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` - Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project;"` // 项目id - Service string `gorm:"size:36;not null;column:service;comment:服务id;uniqueIndex:unique_subscribe"` + Service string `gorm:"size:36;not null;column:service;comment:服务id;uniqueIndex:unique_subscribe;uniqueIndex:unique_subscribe"` Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;uniqueIndex:unique_subscribe"` ApplyStatus int `gorm:"type:tinyint(1);not null;column:apply_status;comment:申请状态;index:status;"` + Applier string `gorm:"size:36;not null;column:applier;comment:申请人;index:applier"` From int `gorm:"type:tinyint(1);not null;column:from;comment:来源;index:status;"` CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` ApproveAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:approve_at;comment:审批时间"` @@ -24,12 +24,11 @@ func (s *Subscribe) TableName() string { type Apply struct { Id int64 `gorm:"column:id;type:BIGINT(20);NOT NULL;comment:id;primary_key;comment:主键ID;"` - Uuid string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` // uuid - Service string `gorm:"size:36;not null;column:service;comment:服务id;index:server;"` // 服务id - Project string `gorm:"size:36;not null;column:project;comment:项目id;index:project;"` // 项目id - Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team;"` // 团队id - Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;index:application;"` // 订阅应用id - ApplyTeam string `gorm:"size:36;not null;column:apply_team;comment:申请团队id;index:apply_team;"` // 申请团队id + Uuid string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` // uuid + Service string `gorm:"size:36;not null;column:service;comment:服务id;index:server;uniqueIndex:unique_apply"` // 服务id + Team string `gorm:"size:36;not null;column:team;comment:团队id;index:team;"` // 团队id + Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;index:application;uniqueIndex:unique_apply"` // 订阅应用id + ApplyTeam string `gorm:"size:36;not null;column:apply_team;comment:申请团队id;index:apply_team;"` // 申请团队id Applier string `gorm:"size:36;not null;column:applier;comment:申请人;index:applier;" aovalue:"creator"` ApplyAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:apply_at;comment:申请时间"` Approver string `gorm:"size:36;not null;column:approver;comment:审批人;index:approver;"` From 73e1fd718ed1bbebbce6d38301dd7968c81397aa Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 2 Aug 2024 13:35:57 +0800 Subject: [PATCH 08/19] =?UTF-8?q?=E6=9D=83=E9=99=90=E9=83=A8=E4=BB=BD?= =?UTF-8?q?=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/permit_system/iml.go | 24 +++ controller/permit_system/permit.go | 18 ++ controller/permit_team/iml.go | 18 ++ controller/permit_team/permit.go | 18 ++ middleware/permit/permit.go | 13 +- module/my-team/iml.go | 4 +- module/permit/project/iml.go | 335 ----------------------------- module/permit/project/module.go | 31 --- module/permit/system/iml.go | 323 ++------------------------- module/permit/system/module.go | 28 +-- module/permit/team/iml.go | 280 ++---------------------- module/permit/team/module.go | 9 +- plugins/permit/plugin.go | 14 +- plugins/permit/project.go | 15 -- plugins/permit/system.go | 14 +- plugins/permit/team.go | 8 +- resources/access/access.go | 19 +- resources/access/access.yaml | 155 ++++++++++++- resources/permit/permit.go | 3 +- 19 files changed, 310 insertions(+), 1019 deletions(-) create mode 100644 controller/permit_system/iml.go create mode 100644 controller/permit_system/permit.go create mode 100644 controller/permit_team/iml.go create mode 100644 controller/permit_team/permit.go delete mode 100644 module/permit/project/iml.go delete mode 100644 module/permit/project/module.go delete mode 100644 plugins/permit/project.go diff --git a/controller/permit_system/iml.go b/controller/permit_system/iml.go new file mode 100644 index 0000000..194be50 --- /dev/null +++ b/controller/permit_system/iml.go @@ -0,0 +1,24 @@ +package permit_system + +import ( + "github.com/eolinker/apipark/module/permit/system" + "github.com/eolinker/go-common/autowire" + "github.com/gin-gonic/gin" +) + +var ( + _ ISystemPermitController = (*imlSystemPermitController)(nil) + _ autowire.Complete = (*imlSystemPermitController)(nil) +) + +type imlSystemPermitController struct { + systemPermitModule system.ISystemPermitModule `autowired:""` +} + +func (c *imlSystemPermitController) Permissions(ctx *gin.Context) ([]string, error) { + return c.systemPermitModule.Permissions(ctx) +} + +func (c *imlSystemPermitController) OnComplete() { + +} diff --git a/controller/permit_system/permit.go b/controller/permit_system/permit.go new file mode 100644 index 0000000..2894614 --- /dev/null +++ b/controller/permit_system/permit.go @@ -0,0 +1,18 @@ +package permit_system + +import ( + "reflect" + + "github.com/eolinker/go-common/autowire" + "github.com/gin-gonic/gin" +) + +type ISystemPermitController interface { + Permissions(ctx *gin.Context) ([]string, error) +} + +func init() { + autowire.Auto[ISystemPermitController](func() reflect.Value { + return reflect.ValueOf(new(imlSystemPermitController)) + }) +} diff --git a/controller/permit_team/iml.go b/controller/permit_team/iml.go new file mode 100644 index 0000000..fd956ed --- /dev/null +++ b/controller/permit_team/iml.go @@ -0,0 +1,18 @@ +package permit_team + +import ( + "github.com/eolinker/apipark/module/permit/team" + "github.com/gin-gonic/gin" +) + +var ( + _ ITeamPermitController = (*imlTeamPermitController)(nil) +) + +type imlTeamPermitController struct { + teamPermitModule team.ITeamPermitModule `autowired:""` +} + +func (c *imlTeamPermitController) Permissions(ctx *gin.Context, team string) ([]string, error) { + return c.teamPermitModule.Permissions(ctx, team) +} diff --git a/controller/permit_team/permit.go b/controller/permit_team/permit.go new file mode 100644 index 0000000..c02de0d --- /dev/null +++ b/controller/permit_team/permit.go @@ -0,0 +1,18 @@ +package permit_team + +import ( + "reflect" + + "github.com/eolinker/go-common/autowire" + "github.com/gin-gonic/gin" +) + +type ITeamPermitController interface { + Permissions(ctx *gin.Context, team string) ([]string, error) +} + +func init() { + autowire.Auto[ITeamPermitController](func() reflect.Value { + return reflect.ValueOf(new(imlTeamPermitController)) + }) +} diff --git a/middleware/permit/permit.go b/middleware/permit/permit.go index fd07c74..934067c 100644 --- a/middleware/permit/permit.go +++ b/middleware/permit/permit.go @@ -2,6 +2,9 @@ package permit_middleware import ( "errors" + "net/http" + "reflect" + permit_identity "github.com/eolinker/apipark/middleware/permit/identity" permit_type "github.com/eolinker/apipark/service/permit-type" "github.com/eolinker/eosc/log" @@ -11,8 +14,6 @@ import ( "github.com/eolinker/go-common/utils" "github.com/gin-gonic/gin" "gorm.io/gorm" - "net/http" - "reflect" ) var ( @@ -57,10 +58,10 @@ func (p *PermitMiddleware) Check(method string, path string) (bool, []gin.Handle ginCtx.Abort() return } - if userId == "admin" { - // 超级管理员不校验 - return - } + //if userId == "admin" { + // // 超级管理员不校验 + // return + //} for _, group := range checkSort { accessList, has := accessRules[group] diff --git a/module/my-team/iml.go b/module/my-team/iml.go index 5077af3..9c9788e 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -98,11 +98,11 @@ func (m *imlTeamModule) Search(ctx context.Context, keyword string) ([]*team_dto if err != nil { return nil, err } - serviceNumMap, err := m.serviceService.ServiceCountByTeam(ctx, keyword) + serviceNumMap, err := m.serviceService.ServiceCountByTeam(ctx, teamIDs...) if err != nil { return nil, err } - appNumMap, err := m.serviceService.AppCountByTeam(ctx, keyword) + appNumMap, err := m.serviceService.AppCountByTeam(ctx, teamIDs...) if err != nil { return nil, err } diff --git a/module/permit/project/iml.go b/module/permit/project/iml.go deleted file mode 100644 index 361cf23..0000000 --- a/module/permit/project/iml.go +++ /dev/null @@ -1,335 +0,0 @@ -package project - -import ( - "context" - "errors" - "fmt" - - "github.com/eolinker/ap-account/service/member" - "github.com/eolinker/ap-account/service/role" - "github.com/eolinker/ap-account/service/user" - user_group "github.com/eolinker/ap-account/service/user-group" - permit_identity "github.com/eolinker/apipark/middleware/permit/identity" - permit_dto "github.com/eolinker/apipark/module/permit/dto" - permit_type "github.com/eolinker/apipark/service/permit-type" - "github.com/eolinker/apipark/service/service" - "github.com/eolinker/apipark/service/team" - team_member "github.com/eolinker/apipark/service/team-member" - "github.com/eolinker/eosc/log" - "github.com/eolinker/go-common/access" - "github.com/eolinker/go-common/autowire" - "github.com/eolinker/go-common/permit" - "github.com/eolinker/go-common/utils" - "github.com/gin-gonic/gin" - "gorm.io/gorm" -) - -const ( - templateDomain = "/template/project" -) - -var ( - _ IProjectPermitModule = (*imlProjectPermitModule)(nil) - _ permit_identity.IdentityProjectService = (*imlProjectPermitModule)(nil) - _ autowire.Complete = (*imlProjectPermitModule)(nil) -) - -var ( - specialRolesProject = []*permit_dto.Option{ - permit_type.AnyOne, - permit_type.TeamMaster, - permit_type.ProjectMaster, - permit_type.TeamMember, - permit_type.ProjectMember, - } -) - -type imlProjectPermitModule struct { - projectService service.IServiceService `autowired:""` - teamProject team.ITeamService `autowired:""` - permitService permit.IPermit `autowired:""` - //projectMemberService project_member.IMemberService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - identityTeamService permit_identity.IdentityTeamService `autowired:""` - //userGroupMemberService user_group.IUserGroupMemberService `autowired:""` - userGroupService user_group.IUserGroupService `autowired:""` - userService user.IUserService `autowired:""` - roleService role.IRoleService `autowired:""` - //projectRoleService project_role.IProjectRoleService `autowired:""` -} - -func (m *imlProjectPermitModule) Permissions(ctx *gin.Context, projectId string) ([]string, error) { - pro, err := m.projectService.Get(ctx, projectId) - if err != nil { - return nil, err - } - uid := utils.UserId(ctx) - accessList, _ := access.Get(permit_identity.ProjectGroup) - if uid == "admin" { - return utils.SliceToSlice(accessList, func(s access.Access) string { - return s.Name - }), nil - } - projectIdentity, err := m.getIdentity(ctx, pro, uid) - if err != nil { - return nil, err - } - - projectDomain := fmt.Sprintf("/%s/%s", pro.Team, projectId) - - // 受项目内权限设置生效的的权限 - projectGranted, _ := m.permitService.GrantForDomain(ctx, projectDomain) - if projectGranted == nil { - projectGranted = make(map[string][]string) - } - // 排除掉项目生效的权限,剩下的是模版生效的权限 - templateAccess := utils.SliceToSlice(accessList, func(s access.Access) string { - return s.Name - }, func(a access.Access) bool { - _, has := projectGranted[a.Name] - return !has - }) - myAccess := make([]string, 0, len(accessList)) - if len(projectGranted) > 0 { - projectAccess, _ := m.permitService.Access(ctx, projectDomain, projectIdentity...) - myAccess = append(myAccess, projectAccess...) - } - if len(templateAccess) > 0 { - teamAccess, _ := m.permitService.Access(ctx, templateDomain, projectIdentity...) - myAccess = append(myAccess, teamAccess...) - } - return myAccess, nil -} - -func (m *imlProjectPermitModule) OnComplete() { - autowire.Inject[permit_identity.IdentityProjectService](m) - permit.AddDomainHandler(permit_identity.ProjectGroup, m.domainHandler) -} - -func (m *imlProjectPermitModule) domainHandler(ctx *gin.Context) ([]string, []string, bool) { - projectId := ctx.Query("project") - p, err := m.projectService.Get(ctx, projectId) - if err != nil { - return nil, nil, false - } - - uid := utils.UserId(ctx) - - projectIdentity, err := m.getIdentity(ctx, p, uid) - if err != nil { - return nil, nil, false - } - - return []string{ - fmt.Sprint("/", p.Team, "/", p.Name), - fmt.Sprintf("/%s", p.Team), - templateDomain, - }, projectIdentity, true -} - -func (m *imlProjectPermitModule) IdentifyProject(ctx context.Context, project string, uid string) ([]string, error) { - - p, err := m.projectService.Get(ctx, project) - if err != nil { - return nil, err - } - identities, err := m.getIdentity(ctx, p, uid) - if err != nil { - return nil, nil - } - - return identities, nil -} -func (m *imlProjectPermitModule) getIdentity(ctx context.Context, p *service.Service, uid string) ([]string, error) { - members, err := m.projectMemberService.Members(ctx, []string{p.Id}, []string{uid}) - if err != nil { - log.Info("get project member error", err) - } - - targets := make([]string, 0) - targets = append(targets, permit_type.AnyOne.Key) - //if p.Master == uid { - // targets = append(targets, permit_type.ProjectMaster.Key) - // targets = append(targets, permit_type.ProjectMember.Key) - //} - if len(members) != 0 { - // 用户属于该项目的成员,则是用户的全局用户组身份生效 - targets = append(targets, permit_type.ProjectMember.Key) - userGroupMembers, err := m.userGroupMemberService.Members(ctx, nil, []string{uid}) - if err != nil { - log.Info("get user group member error", err) - } - - for _, mb := range userGroupMembers { - targets = append(targets, permit_type.UserGroup.KeyOf(mb.Come)) - } - } - //roles, err := m.projectRoleService.Roles(ctx, p.Id, uid) - //if err == nil && roles != nil { - // targets = append(targets, utils.SliceToSlice(roles, func(s *project_role.ProjectRole) string { - // return permit_type.Role.KeyOf(s.Rid) - // })...) - //} - - teamIdentity, err := m.identityTeamService.IdentifyTeam(ctx, p.Team, uid) - if err != nil { - return nil, err - } - allIdentity := make([]string, 0, len(targets)+len(teamIdentity)) - allIdentity = append(allIdentity, targets...) - allIdentity = append(allIdentity, teamIdentity...) - - return allIdentity, nil -} -func (m *imlProjectPermitModule) Options(ctx context.Context, projectId string, keyword string) ([]*permit_dto.Option, error) { - p, err := m.projectService.Get(ctx, projectId) - if err != nil { - return nil, err - } - - result := make([]*permit_dto.Option, 0) - result = append(result, permit_dto.SearchOptions(specialRolesProject, keyword)...) - // 用户组 - ugs, err := m.userGroupService.Search(ctx, keyword) - if err == nil && len(ugs) > 0 { - // 用户组 - ugsO := utils.SliceToSlice(ugs, func(r *user_group.UserGroup) *permit_dto.Option { - return permit_type.UserGroup.Target(r.Id, r.Name) - }) - ugsO = permit_dto.SearchOptions(ugsO, keyword) - if len(ugsO) > 0 { - result = append(result, ugsO...) - } - } - roles, err := m.roleService.Search(ctx, keyword) - if err == nil && len(roles) > 0 { - // 角色 - rolesO := utils.SliceToSlice(roles, func(r *role.Role) *permit_dto.Option { - return permit_type.Role.Target(r.Id, r.Name) - }) - rolesO = permit_dto.SearchOptions(rolesO, keyword) - if len(rolesO) > 0 { - result = append(result, rolesO...) - } - } - - if keyword != "" { - users, _ := m.userService.Search(ctx, keyword, -1) - if len(users) > 0 { - // 团队成员 - userIds := utils.SliceToSlice(users, func(r *user.User) string { - return r.UID - }) - teamMembers, _ := m.teamMemberService.Members(ctx, []string{p.Team}, userIds) - projectMember, _ := m.projectMemberService.Members(ctx, []string{p.Id}, userIds) - userMap := utils.SliceToMap(users, func(r *user.User) string { - return r.UID - }) - if len(teamMembers)+len(projectMember) > 0 { - - userOptions := make([]*permit_dto.Option, 0, len(teamMembers)+len(projectMember)) - userOptions = append(userOptions, utils.SliceToSlice(projectMember, func(r *member.Member) *permit_dto.Option { - us := userMap[r.UID] - return permit_type.User.Target(us.UID, us.GetLabel()) - }, func(m *member.Member) bool { - _, has := userMap[m.UID] - delete(userMap, m.UID) - return has - })...) - userOptions = append(userOptions, utils.SliceToSlice(teamMembers, func(r *member.Member) *permit_dto.Option { - us := userMap[r.UID] - return permit_type.User.Target(us.UID, us.GetLabel()) - }, func(m *member.Member) bool { - _, has := userMap[m.UID] - delete(userMap, m.UID) - return has - })...) - result = append(result, userOptions...) - } - - } - } - return result, nil -} - -func (m *imlProjectPermitModule) Grant(ctx *gin.Context, projectId, access string, key string) error { - - domain, err := m.domain(ctx, projectId) - if err != nil { - return fmt.Errorf("project:%w", err) - } - granted, err := m.permitService.Granted(ctx, access, domain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - if len(granted) == 0 { - tmpGranted, err := m.permitService.Granted(ctx, access, templateDomain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - err = m.permitService.Reset(ctx, access, domain, tmpGranted...) - if err != nil { - return err - } - } - return m.permitService.Add(ctx, access, domain, key) -} - -func (m *imlProjectPermitModule) Remove(ctx *gin.Context, projectId string, access string, key string) error { - - domain, err := m.domain(ctx, projectId) - if err != nil { - return fmt.Errorf("project:%w", err) - } - return m.permitService.Remove(ctx, access, domain, key) -} - -func (m *imlProjectPermitModule) ProjectAccess(ctx *gin.Context, projectId string) ([]*permit_dto.Permission, error) { - - domain, err := m.domain(ctx, projectId) - if err != nil { - return nil, fmt.Errorf("project:%w", err) - } - - accesses, has := access.Get(accessGroup) - if !has { - return nil, errors.New("no access for project") - } - - grants, err := m.permitService.GrantForDomain(ctx, domain) - if err != nil { - return nil, err - } - templateGrants, err := m.permitService.GrantForDomain(ctx, templateDomain) - if err != nil { - return nil, err - } - targets := make([]*permit_type.Target, 0, len(grants)) - - result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { - r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - //Description: s.Desc, - Grant: nil, - } - if gs, has := grants[r.Access]; has { - r.Grant = permit_type.TargetsOf(gs...) - } else { - r.Grant = permit_type.TargetsOf(templateGrants[r.Access]...) - } - - targets = append(targets, r.Grant...) - return r - }) - permit_type.CompleteLabels(ctx, targets...) - return result, nil -} -func (m *imlProjectPermitModule) domain(ctx context.Context, projectId string) (string, error) { - - p, err := m.projectService.Get(ctx, projectId) - if err != nil { - return "", err - } - return fmt.Sprint("/", p.Team, "/", p.Name), nil -} diff --git a/module/permit/project/module.go b/module/permit/project/module.go deleted file mode 100644 index 35e4814..0000000 --- a/module/permit/project/module.go +++ /dev/null @@ -1,31 +0,0 @@ -package project - -import ( - "context" - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" - "reflect" -) - -const ( - accessGroup = "project" -) - -type IProjectPermitModule interface { - Grant(ctx *gin.Context, projectId, access string, key string) error - Remove(ctx *gin.Context, projectId string, access string, key string) error - ProjectAccess(ctx *gin.Context, projectId string) ([]*permit_dto.Permission, error) - Options(ctx context.Context, projectId string, keyword string) ([]*permit_dto.Option, error) - Permissions(ctx *gin.Context, projectId string) ([]string, error) -} - -func init() { - - autowire.Auto[IProjectPermitModule](func() reflect.Value { - m := new(imlProjectPermitModule) - - return reflect.ValueOf(m) - }) - -} diff --git a/module/permit/system/iml.go b/module/permit/system/iml.go index 122960d..7a8635e 100644 --- a/module/permit/system/iml.go +++ b/module/permit/system/iml.go @@ -2,337 +2,56 @@ package system import ( "context" - "errors" + "reflect" + "github.com/eolinker/ap-account/service/role" - "github.com/eolinker/ap-account/service/user" - user_group "github.com/eolinker/ap-account/service/user-group" - permit_identity "github.com/eolinker/apipark/middleware/permit/identity" - "github.com/eolinker/apipark/module/permit/dto" - permit_type "github.com/eolinker/apipark/service/permit-type" - "github.com/eolinker/go-common/access" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/permit" "github.com/eolinker/go-common/utils" - "github.com/gin-gonic/gin" - "gorm.io/gorm" - "reflect" ) var ( - _ ISystemPermitModule = (*imlSystemPermitModule)(nil) - _ permit_identity.IdentitySystemService = (*imlSystemPermitModule)(nil) - _ autowire.Complete = (*imlSystemPermitModule)(nil) -) - -var ( - specialRolesForSystem = []*permit_dto.Option{permit_type.AnyOne} - specialRolesTeam = []*permit_dto.Option{ - permit_type.AnyOne, - permit_type.TeamMember, - permit_type.TeamMaster, - } - specialRolesProject = []*permit_dto.Option{ - permit_type.AnyOne, - permit_type.ProjectMember, - permit_type.ProjectMaster, - permit_type.TeamMaster, - permit_type.TeamMember, - } + _ ISystemPermitModule = (*imlSystemPermitModule)(nil) + _ autowire.Complete = (*imlSystemPermitModule)(nil) ) type imlSystemPermitModule struct { - permitService permit.IPermit `autowired:""` - userGroupService user_group.IUserGroupService `autowired:""` - userGroupMemberService user_group.IUserGroupMemberService `autowired:""` - userService user.IUserService `autowired:""` - roleService role.IRoleService `autowired:""` + permitService permit.IPermit `autowired:""` + roleService role.IRoleService `autowired:""` + roleMemberService role.IRoleMemberService `autowired:""` } func (m *imlSystemPermitModule) Permissions(ctx context.Context) ([]string, error) { uid := utils.UserId(ctx) - if uid == "admin" { - accessList, _ := access.Get(permit_identity.SystemGroup) - return utils.SliceToSlice(accessList, func(s access.Access) string { - return s.Name - }), nil - } - identitySystem, err := m.IdentifySystem(ctx, uid) + roleMembers, err := m.roleMemberService.List(ctx, role.SystemTarget(), uid) if err != nil { return nil, err } - return m.permitService.Access(ctx, systemDomain, identitySystem...) -} - -func (m *imlSystemPermitModule) OnComplete() { - autowire.Inject[permit_identity.IdentitySystemService](m) - permit.AddDomainHandler(permit_identity.SystemGroup, m.domain) -} - -func (m *imlSystemPermitModule) RemoveTeamTemplateAccess(ctx context.Context, access, key string) error { - return m.permitService.Remove(ctx, access, teamDomain, key) - -} - -func (m *imlSystemPermitModule) RemoveProjectTemplateAccess(ctx context.Context, access, key string) error { - return m.permitService.Remove(ctx, access, projectDomain, key) -} -func (m *imlSystemPermitModule) roleOptions(ctx context.Context, keyword string) ([]*permit_dto.Option, error) { - roles, err := m.roleService.Search(ctx, keyword) - if err == nil && len(roles) > 0 { - // 角色 - rolesO := utils.SliceToSlice(roles, func(r *role.Role) *permit_dto.Option { - return permit_type.Role.Target(r.Id, r.Name) - }) - return permit_dto.SearchOptions(rolesO, keyword), nil - - } - return nil, nil -} -func (m *imlSystemPermitModule) userGroupOptions(ctx context.Context, keyword string) ([]*permit_dto.Option, error) { - ugs, err := m.userGroupService.Search(ctx, keyword) - if err != nil { - return nil, err + if len(roleMembers) == 0 { + return []string{}, nil } - ugsO := utils.SliceToSlice(ugs, func(r *user_group.UserGroup) *permit_dto.Option { - return permit_type.UserGroup.Target(r.Id, r.Name) + roleIds := utils.SliceToSlice(roleMembers, func(rm *role.Member) string { + return rm.Role }) - return permit_dto.SearchOptions(ugsO, keyword), nil -} -func (m *imlSystemPermitModule) OptionsForSystem(ctx context.Context, keyword string) ([]*permit_dto.Option, error) { - result := make([]*permit_dto.Option, 0, 10) - - specialRoles := permit_dto.SearchOptions(specialRolesForSystem, keyword) - if len(specialRoles) > 0 { - result = append(result, specialRoles...) - } - userGroupOptions, err := m.userGroupOptions(ctx, keyword) - if err != nil { - return nil, err - } - if len(userGroupOptions) > 0 { - result = append(result, userGroupOptions...) - } - //roleOptions, err := m.roleOptions(ctx, keyword) - //if err != nil { - // return nil, err - //} - //result = append(result, roleOptions...) - if keyword != "" { - ul, err := m.userService.Search(ctx, keyword, -1) - if err == nil && len(ul) > 0 { - result = append(result, utils.SliceToSlice(ul, func(r *user.User) *permit_dto.Option { - return permit_type.User.Target(r.UID, r.Username) - - })...) - } - } - return result, nil - -} - -func (m *imlSystemPermitModule) OptionsForTeamTemplate(ctx context.Context, keyword string) ([]*permit_dto.Option, error) { - result := make([]*permit_dto.Option, 0, 10) - - specialRoles := permit_dto.SearchOptions(specialRolesTeam, keyword) - if len(specialRoles) > 0 { - result = append(result, specialRoles...) - } - userGroupOptions, err := m.userGroupOptions(ctx, keyword) - if err != nil { - return nil, err - } - if len(userGroupOptions) > 0 { - result = append(result, userGroupOptions...) - } - roleOptions, err := m.roleOptions(ctx, keyword) + roles, err := m.roleService.List(ctx, roleIds...) if err != nil { return nil, err } - result = append(result, roleOptions...) - return result, nil -} - -func (m *imlSystemPermitModule) OptionsForProjectTemplate(ctx context.Context, keyword string) ([]*permit_dto.Option, error) { - result := make([]*permit_dto.Option, 0, 10) - result = append(result, permit_dto.SearchOptions(specialRolesProject, keyword)...) - - userGroupOptions, err := m.userGroupOptions(ctx, keyword) - if err == nil && len(userGroupOptions) > 0 { - result = append(result, userGroupOptions...) - } - - roleOptions, err := m.roleOptions(ctx, keyword) - if err == nil && len(roleOptions) > 0 { - result = append(result, roleOptions...) - } - return result, nil -} - -func (m *imlSystemPermitModule) GrantTemplateForTeam(ctx context.Context, access, key string) error { - return m.permitService.Add(ctx, access, teamDomain, key) -} - -func (m *imlSystemPermitModule) GrantTemplateForProject(ctx context.Context, access, key string) error { - return m.permitService.Add(ctx, access, projectDomain, key) -} - -func (m *imlSystemPermitModule) TeamAccess(ctx context.Context) ([]*permit_dto.Permission, error) { - - accesses, has := access.Get(teamAccessGroup) - if !has { - return nil, errors.New("no access for team") - } - - grants, err := m.permitService.GrantForDomain(ctx, teamDomain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return nil, err - } - targets := make([]*permit_type.Target, 0, len(grants)) - - result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { - - r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - Description: s.Desc, - Grant: nil, - } - r.Grant = permit_type.TargetsOf(grants[r.Access]...) - targets = append(targets, r.Grant...) - return r - }) - - permit_type.CompleteLabels(ctx, targets...) - return result, nil -} - -func (m *imlSystemPermitModule) ProjectAccess(ctx context.Context) ([]*permit_dto.Permission, error) { - - accesses, has := access.Get(projectAccessGroup) - if !has { - return nil, errors.New("no access for team") - } - - grants, err := m.permitService.GrantForDomain(ctx, projectDomain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return nil, err - } - targets := make([]*permit_type.Target, 0, len(grants)) - - result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { - - r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - Description: s.Desc, - Grant: nil, - } - r.Grant = permit_type.TargetsOf(grants[r.Access]...) - targets = append(targets, r.Grant...) - return r - }) - - permit_type.CompleteLabels(ctx, targets...) - return result, nil -} - -func (m *imlSystemPermitModule) domain(ctx *gin.Context) ([]string, []string, bool) { - - system, err := m.IdentifySystem(ctx, utils.UserId(ctx)) - if err != nil { - return nil, nil, false - } - return []string{systemDomain}, system, true -} -func (m *imlSystemPermitModule) IdentifySystem(ctx context.Context, uid string) ([]string, error) { - if uid == "" { - return nil, errors.New("not login") - } - targets := make([]string, 0) - targets = append(targets, permit_type.User.KeyOf(uid)) - targets = append(targets, permit_type.Special.KeyOf("all")) - members, err := m.userGroupMemberService.FilterMembersForUser(ctx, uid) - if err != nil && len(members) > 0 { - cs := members[uid] - for _, c := range cs { - targets = append(targets, permit_type.UserGroup.KeyOf(c)) - } - } - - return targets, nil -} - -func (m *imlSystemPermitModule) GrantSystem(ctx context.Context, access, key string) error { - return m.permitService.Add(ctx, access, systemDomain, key) -} - -func (m *imlSystemPermitModule) RemoveSystemAccess(ctx context.Context, access, key string) error { - return m.permitService.Remove(ctx, access, systemDomain, key) -} - -func (m *imlSystemPermitModule) SystemAccess(ctx context.Context) ([]*permit_dto.Permission, error) { - - accesses, has := access.Get(accessGroup) - if !has { - return nil, errors.New("no access for system") - } - - result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { - return &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - Description: s.Desc, - Grant: nil, + permits := make(map[string]struct{}) + for _, r := range roles { + for _, p := range r.Permit { + permits[p] = struct{}{} } - }) - grants, err := m.permitService.GrantForDomain(ctx, systemDomain) - if err != nil { - return nil, err - } - targets := make([]*permit_type.Target, 0, len(grants)) - for _, r := range result { - r.Grant = permit_type.TargetsOf(grants[r.Access]...) - targets = append(targets, r.Grant...) } - permit_type.CompleteLabels(ctx, targets...) - return result, nil + return utils.MapToSlice(permits, func(k string, v struct{}) string { + return k + }), nil } -func (m *imlSystemPermitModule) Get(ctx context.Context, ac string) (*permit_dto.Permission, error) { - - accesses, has := access.Get(accessGroup) - if !has { - return nil, errors.New("no access for system") - } - var out *permit_dto.Permission - - for _, a := range accesses { - if a.Name == ac { - out = &permit_dto.Permission{ - Access: a.Name, - Name: a.CName, - Description: a.Desc, - Grant: nil, - } - - break - } - } - - if out == nil { - return nil, errors.New("no access for system") - } - granted, err := m.permitService.Granted(ctx, ac, systemDomain) - if err != nil { - return nil, err - } - - out.Grant = permit_type.TargetsOf(granted...) - permit_type.CompleteLabels(ctx, out.Grant...) - return out, nil +func (m *imlSystemPermitModule) OnComplete() { } func init() { diff --git a/module/permit/system/module.go b/module/permit/system/module.go index b2a2328..4c7f62c 100644 --- a/module/permit/system/module.go +++ b/module/permit/system/module.go @@ -2,38 +2,12 @@ package system import ( "context" - "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" "reflect" -) -const ( - systemDomain = "/" - teamDomain = "/template/team" - projectDomain = "/template/project" - accessGroup = "system" - teamAccessGroup = "team" - projectAccessGroup = "project" + "github.com/eolinker/go-common/autowire" ) type ISystemPermitModule interface { - // GrantSystem 分配系统级权限 - GrantSystem(ctx context.Context, access, key string) error - GrantTemplateForTeam(ctx context.Context, access, key string) error - GrantTemplateForProject(ctx context.Context, access, key string) error - RemoveSystemAccess(ctx context.Context, access, key string) error - RemoveTeamTemplateAccess(ctx context.Context, access, key string) error - RemoveProjectTemplateAccess(ctx context.Context, access, key string) error - - // Access 查询权限授权情况 - SystemAccess(ctx context.Context) ([]*permit_dto.Permission, error) - TeamAccess(ctx context.Context) ([]*permit_dto.Permission, error) - ProjectAccess(ctx context.Context) ([]*permit_dto.Permission, error) - Get(ctx context.Context, access string) (*permit_dto.Permission, error) - OptionsForSystem(ctx context.Context, keyword string) ([]*permit_dto.Option, error) - OptionsForTeamTemplate(ctx context.Context, keyword string) ([]*permit_dto.Option, error) - OptionsForProjectTemplate(ctx context.Context, keyword string) ([]*permit_dto.Option, error) - Permissions(ctx context.Context) ([]string, error) } diff --git a/module/permit/team/iml.go b/module/permit/team/iml.go index 494a312..4ecbeeb 100644 --- a/module/permit/team/iml.go +++ b/module/permit/team/iml.go @@ -2,292 +2,50 @@ package team import ( "context" - "errors" - "fmt" - "github.com/eolinker/ap-account/service/account" - "github.com/eolinker/ap-account/service/member" "github.com/eolinker/ap-account/service/role" - "github.com/eolinker/ap-account/service/user" - user_group "github.com/eolinker/ap-account/service/user-group" - permit_identity "github.com/eolinker/apipark/middleware/permit/identity" - permit_dto "github.com/eolinker/apipark/module/permit/dto" - permit_type "github.com/eolinker/apipark/service/permit-type" - "github.com/eolinker/apipark/service/team" - team_member "github.com/eolinker/apipark/service/team-member" - "github.com/eolinker/go-common/access" "github.com/eolinker/go-common/autowire" - "github.com/eolinker/go-common/permit" "github.com/eolinker/go-common/utils" - "github.com/gin-gonic/gin" - "gorm.io/gorm" ) var ( - _ ITeamPermitModule = (*imlTeamPermitModule)(nil) - _ permit_identity.IdentityTeamService = (*imlTeamPermitModule)(nil) - _ autowire.Complete = (*imlTeamPermitModule)(nil) -) - -const ( - templateDomain = "/template/team" -) - -var ( - specialRolesTeam = []*permit_dto.Option{ - permit_type.AnyOne, - permit_type.ProjectMaster, - permit_type.ProjectMember, - } + _ ITeamPermitModule = (*imlTeamPermitModule)(nil) + _ autowire.Complete = (*imlTeamPermitModule)(nil) ) type imlTeamPermitModule struct { - permitService permit.IPermit `autowired:""` - teamService team.ITeamService `autowired:""` - teamMemberService team_member.ITeamMemberService `autowired:""` - accountService account.IAccountService `autowired:""` - userService user.IUserService `autowired:""` - userGroupService user_group.IUserGroupService `autowired:""` - userGroupMemberService user_group.IUserGroupMemberService `autowired:""` - roleService role.IRoleService `autowired:""` + roleService role.IRoleService `autowired:""` + roleMemberService role.IRoleMemberService `autowired:""` } func (m *imlTeamPermitModule) Permissions(ctx context.Context, teamId string) ([]string, error) { + uid := utils.UserId(ctx) - identifyTeam, err := m.IdentifyTeam(ctx, teamId, uid) + roleMembers, err := m.roleMemberService.List(ctx, role.TeamTarget(teamId), uid) if err != nil { return nil, err } - teamDomain := fmt.Sprintf("/%s", teamId) - accessList, _ := access.Get(permit_identity.TeamGroup) - - // 受团队内权限设置生效的的权限 - teamGranted, _ := m.permitService.GrantForDomain(ctx, teamDomain) - if teamGranted == nil { - teamGranted = make(map[string][]string) - } - // 排除掉项目生效的权限,剩下的是模版生效的权限 - templateAccess := utils.SliceToSlice(accessList, func(s access.Access) string { - return s.Name - }, func(a access.Access) bool { - _, has := teamGranted[a.Name] - return !has + roleIds := utils.SliceToSlice(roleMembers, func(rm *role.Member) string { + return rm.Role }) - myAccess := make([]string, 0, len(accessList)) - if len(teamGranted) > 0 { - projectAccess, _ := m.permitService.Access(ctx, teamDomain, identifyTeam...) - myAccess = append(myAccess, projectAccess...) + if len(roleMembers) == 0 { + return []string{}, nil } - if len(templateAccess) > 0 { - teamAccess, _ := m.permitService.Access(ctx, templateDomain, identifyTeam...) - myAccess = append(myAccess, teamAccess...) - } - return myAccess, nil -} - -func (m *imlTeamPermitModule) OnComplete() { - autowire.Inject[permit_identity.IdentityTeamService](m) - permit.AddDomainHandler(permit_identity.TeamGroup, m.domainHandler) -} - -func (m *imlTeamPermitModule) IdentifyTeam(ctx context.Context, team string, uid string) ([]string, error) { - t, err := m.teamService.Get(ctx, team) + roles, err := m.roleService.List(ctx, roleIds...) if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, errors.New("team not found") - } - } - result := make([]string, 0, 5) - if t.Master == uid { - result = append(result, permit_type.TeamMaster.Key) - result = append(result, permit_type.TeamMember.Key) - } else { - members, err := m.teamMemberService.Members(ctx, []string{t.Id}, []string{uid}) - if err == nil && len(members) > 0 { - result = append(result, permit_type.TeamMember.Key) - } - - } - members, err := m.userGroupMemberService.FilterMembersForUser(ctx, uid) - if err != nil && len(members) > 0 { - cs := members[uid] - for _, c := range cs { - result = append(result, permit_type.UserGroup.KeyOf(c)) - } - } - - return result, nil - -} - -func (m *imlTeamPermitModule) Options(ctx context.Context, teamId string, keyword string) ([]*permit_dto.Option, error) { - t, err := m.teamService.Get(ctx, teamId) - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, errors.New("team not found") - } return nil, err } - result := make([]*permit_dto.Option, 0, 10) - specialRoles := permit_dto.SearchOptions(specialRolesTeam, keyword) - if len(specialRoles) > 0 { - result = append(result, specialRoles...) - } - ugs, err := m.userGroupService.Search(ctx, keyword) - if err == nil && len(ugs) > 0 { - // 用户组 - ugsO := utils.SliceToSlice(ugs, func(r *user_group.UserGroup) *permit_dto.Option { - return permit_type.UserGroup.Target(r.Id, r.Name) - }) - ugsO = permit_dto.SearchOptions(ugsO, keyword) - if len(ugsO) > 0 { - result = append(result, ugsO...) - } - } - - roles, err := m.roleService.Search(ctx, keyword) - if err == nil && len(roles) > 0 { - // 角色 - rolesO := utils.SliceToSlice(roles, func(r *role.Role) *permit_dto.Option { - return permit_type.Role.Target(r.Id, r.Name) - }) - rolesO = permit_dto.SearchOptions(rolesO, keyword) - if len(rolesO) > 0 { - result = append(result, rolesO...) - } - } - // keyword 不为空时,搜索团队成员 - if keyword != "" { - users, _ := m.userService.Search(ctx, keyword, -1) - if len(users) > 0 { - // 团队成员 - members, err := m.teamMemberService.Members(ctx, []string{t.Id}, utils.SliceToSlice(users, func(r *user.User) string { - return r.UID - })) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return nil, err - } - if len(members) > 0 { - userMap := utils.SliceToMap(users, func(r *user.User) string { - return r.UID - }) - ugsO := utils.SliceToSlice(members, func(r *member.Member) *permit_dto.Option { - us := userMap[r.UID] - return permit_type.User.Target(us.UID, us.GetLabel()) - - }, func(m *member.Member) bool { - _, has := userMap[m.UID] - return has - }) - ugsO = permit_dto.SearchOptions(ugsO, keyword) - if len(ugsO) > 0 { - result = append(result, ugsO...) - } - } - + permits := make(map[string]struct{}) + for _, r := range roles { + for _, p := range r.Permit { + permits[p] = struct{}{} } } - return result, nil + return utils.MapToSlice(permits, func(k string, v struct{}) string { + return k + }), nil } -func (m *imlTeamPermitModule) Grant(ctx *gin.Context, teamId, access string, key string) error { - - domain, err := m.domain(ctx, teamId) - if err != nil { - return fmt.Errorf("team:%w", err) - } - - granted, err := m.permitService.Granted(ctx, access, domain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - if len(granted) == 0 { - tmpGranted, err := m.permitService.Granted(ctx, access, templateDomain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - return err - } - err = m.permitService.Reset(ctx, access, domain, tmpGranted...) - if err != nil { - return err - } - } - - return m.permitService.Add(ctx, access, domain, key) -} - -func (m *imlTeamPermitModule) Remove(ctx *gin.Context, teamId string, access string, key string) error { - domain, err := m.domain(ctx, teamId) - if err != nil { - return fmt.Errorf("team:%w", err) - } - return m.permitService.Remove(ctx, access, domain, key) -} - -func (m *imlTeamPermitModule) TeamAccess(ctx *gin.Context, teamId string) ([]*permit_dto.Permission, error) { - domain, err := m.domain(ctx, teamId) - if err != nil { - return nil, fmt.Errorf("team:%w", err) - } - - accesses, has := access.Get(accessGroup) - if !has { - return nil, errors.New("no access for team") - } - - grants, err := m.permitService.GrantForDomain(ctx, domain) - if err != nil { - return nil, err - } - templateGrants, err := m.permitService.GrantForDomain(ctx, templateDomain) - if err != nil { - return nil, err - } - targets := make([]*permit_type.Target, 0, len(grants)) - - result := utils.SliceToSlice(accesses, func(s access.Access) *permit_dto.Permission { - r := &permit_dto.Permission{ - Access: s.Name, - Name: s.CName, - //Description: s.Desc, - Grant: nil, - } - if gs, has := grants[r.Access]; has { - r.Grant = permit_type.TargetsOf(gs...) - } else { - r.Grant = permit_type.TargetsOf(templateGrants[r.Access]...) - } - targets = append(targets, r.Grant...) - return r - }) - permit_type.CompleteLabels(ctx, targets...) - return result, nil -} - -func (m *imlTeamPermitModule) domain(ctx context.Context, teamId string) (string, error) { - _, err := m.teamService.Get(ctx, teamId) - if err != nil { - return "", err - } - return fmt.Sprint("/", teamId), nil -} - -func (m *imlTeamPermitModule) domainHandler(ctx *gin.Context) ([]string, []string, bool) { - teamId := ctx.Query("team") - - t, err := m.teamService.Get(ctx, teamId) - if err != nil { - return nil, nil, false - } - uid := utils.UserId(ctx) - - teamIdentity, err := m.IdentifyTeam(ctx, teamId, uid) - if err != nil { - return nil, nil, false - } - return []string{ - fmt.Sprintf("/%s", t.Id), - templateDomain, - }, teamIdentity, true - +func (m *imlTeamPermitModule) OnComplete() { } diff --git a/module/permit/team/module.go b/module/permit/team/module.go index 8a8c1bc..867d8f3 100644 --- a/module/permit/team/module.go +++ b/module/permit/team/module.go @@ -2,10 +2,9 @@ package team import ( "context" - permit_dto "github.com/eolinker/apipark/module/permit/dto" - "github.com/eolinker/go-common/autowire" - "github.com/gin-gonic/gin" "reflect" + + "github.com/eolinker/go-common/autowire" ) const ( @@ -13,10 +12,6 @@ const ( ) type ITeamPermitModule interface { - Grant(ctx *gin.Context, teamId, access string, key string) error - Remove(ctx *gin.Context, teamId string, access string, key string) error - TeamAccess(ctx *gin.Context, teamId string) ([]*permit_dto.Permission, error) - Options(ctx context.Context, teamId string, keyword string) ([]*permit_dto.Option, error) Permissions(ctx context.Context, teamId string) ([]string, error) } diff --git a/plugins/permit/plugin.go b/plugins/permit/plugin.go index f9e9af1..ce18ff7 100644 --- a/plugins/permit/plugin.go +++ b/plugins/permit/plugin.go @@ -1,6 +1,8 @@ package permit import ( + "github.com/eolinker/apipark/controller/permit_system" + "github.com/eolinker/apipark/controller/permit_team" permit_middleware "github.com/eolinker/apipark/middleware/permit" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/pm3" @@ -13,17 +15,15 @@ var ( ) type pluginPermit struct { - //systemPermitController permit_system.ISystemPermitController `autowired:""` - //teamPermitController permit_team.ITeamPermitController `autowired:""` - //projectPermitController permit_project.IProjectPermitController `autowired:""` - apis []pm3.Api - middlewares []pm3.IMiddleware - permitChecker permit_middleware.IPermitMiddleware `autowired:""` + systemPermitController permit_system.ISystemPermitController `autowired:""` + teamPermitController permit_team.ITeamPermitController `autowired:""` + apis []pm3.Api + middlewares []pm3.IMiddleware + permitChecker permit_middleware.IPermitMiddleware `autowired:""` } func (p *pluginPermit) OnComplete() { p.apis = append(p.apis, p.getSystemApis()...) - p.apis = append(p.apis, p.getSProjectPermitApis()...) p.apis = append(p.apis, p.getSTeamPermitApis()...) p.middlewares = append(p.middlewares, p.permitChecker) } diff --git a/plugins/permit/project.go b/plugins/permit/project.go deleted file mode 100644 index d88828d..0000000 --- a/plugins/permit/project.go +++ /dev/null @@ -1,15 +0,0 @@ -package permit - -import ( - "github.com/eolinker/go-common/pm3" -) - -func (p *pluginPermit) getSProjectPermitApis() []pm3.Api { - return []pm3.Api{ - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permissions", []string{"context", "query:project"}, []string{"permissions"}, p.projectPermitController.List), - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/project/setting/permission", []string{"context", "query:project", "body"}, []string{}, p.projectPermitController.Grant), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/project/setting/permission", []string{"context", "query:project", "query:access", "query:key"}, []string{}, p.projectPermitController.Remove), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/project/setting/permission/options", []string{"context", "query:project", "query:keyword"}, []string{"options"}, p.projectPermitController.Options), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/project", []string{"context", "query:project"}, []string{"access"}, p.projectPermitController.Permissions), - } -} diff --git a/plugins/permit/system.go b/plugins/permit/system.go index 5b6837e..69a4c57 100644 --- a/plugins/permit/system.go +++ b/plugins/permit/system.go @@ -1,21 +1,13 @@ package permit import ( + "net/http" + "github.com/eolinker/go-common/pm3" ) func (p *pluginPermit) getSystemApis() []pm3.Api { return []pm3.Api{ - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permissions", []string{"context"}, []string{"system", "team", "project"}, p.systemPermitController.List), - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission", []string{"context", "body"}, []string{}, p.systemPermitController.Grant), - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/team", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForTeam), - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/system/permission/project", []string{"context", "body"}, []string{}, p.systemPermitController.GrantTemplateForProject), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/team", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/system/permission/project", []string{"context", "query:access", "query:key"}, []string{}, p.systemPermitController.Remove), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.Options), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/team", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForTeamTemplate), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/system/permission/options/project", []string{"context", "query:keyword"}, []string{"options"}, p.systemPermitController.OptionsForProjectTemplate), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/system", []string{"context"}, []string{"access"}, p.systemPermitController.Permissions), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/system", []string{"context"}, []string{"access"}, p.systemPermitController.Permissions), } } diff --git a/plugins/permit/team.go b/plugins/permit/team.go index c2eca53..729e2aa 100644 --- a/plugins/permit/team.go +++ b/plugins/permit/team.go @@ -1,15 +1,13 @@ package permit import ( + "net/http" + "github.com/eolinker/go-common/pm3" ) func (p *pluginPermit) getSTeamPermitApis() []pm3.Api { return []pm3.Api{ - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permissions", []string{"context", "query:team"}, []string{"permissions"}, p.teamPermitController.List), - //pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/team/setting/permission", []string{"context", "query:team", "body"}, []string{}, p.teamPermitController.Grant), - //pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/team/setting/permission", []string{"context", "query:team", "query:access", "query:key"}, []string{}, p.teamPermitController.Remove), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/team/setting/permission/options", []string{"context", "query:team", "query:keyword"}, []string{"options"}, p.teamPermitController.Options), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/team", []string{"context", "query:team"}, []string{"access"}, p.teamPermitController.Permissions), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/profile/permission/team", []string{"context", "query:team"}, []string{"access"}, p.teamPermitController.Permissions), } } diff --git a/resources/access/access.go b/resources/access/access.go index 4a56b8e..25c3884 100644 --- a/resources/access/access.go +++ b/resources/access/access.go @@ -21,8 +21,25 @@ func init() { panic(err) } for group, asl := range ts { - access.Add(group, asl) } + //defaultRoles := access.Roles() + //for group, rs := range defaultRoles { + // p, has := access.GetPermit(group) + // if !has { + // continue + // } + // + // for _, r := range rs { + // for _, pm := range r.Permits { + // apis, err := p.GetPermits(pm) + // if err != nil { + // continue + // } + // permit.AddPermitRule(pm, apis...) + // } + // } + // + //} } diff --git a/resources/access/access.yaml b/resources/access/access.yaml index 6fb4175..6dea86e 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -10,12 +10,25 @@ system: - name: view cname: '查看' value: 'view' + apis: + - "GET:/api/v1/user/accounts" + - "GET:/api/v1/user/departments" - name: manager cname: '管理' value: 'manager' apis: - - "GET:/api/v1/simple/member" - - "GET:/api/v1/simple/organization/member/:id" + - "POST:/api/v1/user/account" + - "PUT:/api/v1/user/account" + - "DELETE:/api/v1/user/account" + - "POST:/api/v1/user/account/enable" + - "POST:/api/v1/user/account/disable" + - "POST:/api/v1/user/department" + - "PUT:/api/v1/user/department" + - "DELETE:/api/v1/user/department" + - "POST:/api/v1/user/department/member" + - "DELETE:/api/v1/user/department/member" + - "POST:/api/v1/user/department/member/remove" + - "POST:/api/v1/account/role" - name: team cname: '团队' value: 'team' @@ -23,9 +36,17 @@ system: - name: view cname: '查看' value: 'view' + apis: + - "GET:/api/v1/manager/teams" + - "GET:/api/v1/manager/team" - name: manager cname: '管理' value: 'manager' + apis: + - "POST:/api/v1/manager/team" + - "PUT:/api/v1/manager/team" + - "DELETE:/api/v1/manager/team" + - name: role cname: '角色' value: 'role' @@ -33,9 +54,15 @@ system: - name: view system role cname: '查看系统角色' value: 'view_system_role' + apis: + - "GET:/api/v1/system/roles" + - "GET:/api/v1/system/role" - name: view team role cname: '查看团队角色' value: 'view_team_role' + apis: + - "GET:/api/v1/team/roles" + - "GET:/api/v1/team/role" - name: API Market cname: 'API市场' value: 'api_market' @@ -47,9 +74,16 @@ system: - name: view cname: '查看' value: 'view' + apis: + - "GET:/api/v1/catalogues" - name: manager cname: '管理' value: 'manager' + apis: + - "POST:/api/v1/catalogue" + - "PUT:/api/v1/catalogue" + - "DELETE:/api/v1/catalogue" + - "PUT:/api/v1/catalogue/sort" - name: devops cname: 运维 value: 'devops' @@ -61,9 +95,14 @@ system: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/cluster/nodes" - name: manager cname: 管理 value: 'manager' + apis: + - "PUT:/api/v1/cluster/reset" + - "POST:/api/v1/cluster/check" - name: ssl certificate cname: 证书 value: 'ssl_certificate' @@ -71,9 +110,17 @@ system: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/certificates" + - "GET:/api/v1/certificate" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/certificate" + - "PUT:/api/v1/certificate" + - "DELETE:/api/v1/certificate" + - name: log configuration cname: 日志 value: 'log_configuration' @@ -81,9 +128,19 @@ system: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/dynamic/{name}/info" + - "GET:/api/v1/dynamic/{name}/list" + - "GET:/api/v1/dynamic/{name}/render" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/dynamic/{name}" + - "PUT:/api/v1/dynamic/{name}/config" + - "DELETE:/api/v1/dynamic/{name}/batch" + - "PUT:/api/v1/dynamic/{name}/online" + - "PUT:/api/v1/dynamic/{name}/offline" - name: workspace cname: 工作空间 value: 'workspace' @@ -95,6 +152,8 @@ system: - name: view all cname: 查看所有应用 value: 'view_all' + apis: + - "GET:/api/v1/apps" - name: service cname: 服务 value: 'service' @@ -102,6 +161,8 @@ system: - name: view all cname: 查看所有服务 value: 'view_all' + apis: + - "GET:/api/v1/services" - name: team cname: 团队 value: 'team' @@ -109,6 +170,8 @@ system: - name: view all cname: 查看所有团队 value: 'view_all' + apis: + - "GET:/api/v1/teams" - name: api market cname: API市场 value: 'api_market' @@ -116,6 +179,9 @@ system: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/catalogue/services" + - "GET:/api/v1/catalogue/service" team: - name: service cname: 服务 @@ -128,9 +194,20 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/service/apis" + - "GET:/api/v1/service/api/detail" + - "GET:/api/v1/service/api/detail/simple" + - "GET:/api/v1/service/api/define" + - "GET:/api/v1/service/apis/simple" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/service/api" + - "PUT:/api/v1/service/api" + - "DELETE:/api/v1/service/api" + - "POST:/api/v1/service/api/copy" - name: upstream cname: 上游 value: 'upstream' @@ -138,9 +215,13 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/service/upstream" - name: manager cname: 管理 value: 'manager' + apis: + - "PUT:/api/v1/service/upstream" - name: release cname: 发布 value: 'release' @@ -148,9 +229,20 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/service/releases" + - "GET:/api/v1/service/release" + - "GET:/api/v1/service/publishs" + - "GET:/api/v1/service/publish/check" + - "GET:/api/v1/service/release/preview" + - "GET:/api/v1/service/publish/status" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/service/publish/release/do" + - "PUT:/api/v1/service/publish/execute" + - "DELETE:/api/v1/service/release" - name: subscription management cname: 订阅方管理 value: 'subscription' @@ -158,16 +250,29 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/service/approval/subscribes" + - "GET:/api/v1/service/approval/subscribe" + - "GET:/api/v1/service/subscribers" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/service/approval/subscribe" + - "POST:/api/v1/service/subscriber" + - "DELETE:/api/v1/service/subscriber" - name: service cname: 服务管理 value: 'service' children: - - name: view - cname: 查看 - value: 'view' + - name: manager + cname: 管理 + value: 'manager' + apis: + - "GET:/api/v1/service/info" + - "PUT:/api/v1/service/info" + - "POST:/api/v1/team/service" + - "DELETE:/api/v1/team/service" - name: application cname: 应用 value: 'application' @@ -179,9 +284,15 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/application/subscriptions" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/catalogue/service/subscribe" + - "POST:/api/v1/application/subscription/cancel" + - "POST:/api/v1/application/subscription/cancel_apply" - name: authorization cname: 访问授权 value: 'authorization' @@ -189,9 +300,17 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/app/authorization" + - "GET:/api/v1/app/authorizations" + - "GET:/api/v1/app/authorization/details" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/app/authorization" + - "PUT:/api/v1/app/authorization" + - "DELETE:/api/v1/app/authorization" - name: application cname: 应用 value: 'application' @@ -199,6 +318,11 @@ team: - name: manager cname: 管理 value: 'manager' + apis: + - "GET:/api/v1/app/info" + - "PUT:/api/v1/app/info" + - "POST:/api/v1/team/app" + - "DELETE:/api/v1/app" - name: team cname: 团队 value: 'team' @@ -210,16 +334,31 @@ team: - name: view cname: 查看 value: 'view' + apis: + - "GET:/api/v1/team/members" + - "GET:/api/v1/team/members/simple" + - "GET:/api/v1/team/members/toadd" - name: manager cname: 管理 value: 'manager' + apis: + - "POST:/api/v1/team/member" + - "DELETE:/api/v1/team/member" + - "PUT:/api/v1/team/member/role" - name: team cname: 团队管理 value: 'team' children: - name: view - cname: 查看 + cname: '查看' value: 'view' + apis: + - "GET:/api/v1/manager/teams" + - "GET:/api/v1/manager/team" - name: manager - cname: 管理 - value: 'manager' \ No newline at end of file + cname: '管理' + value: 'manager' + apis: + - "POST:/api/v1/manager/team" + - "PUT:/api/v1/manager/team" + - "DELETE:/api/v1/manager/team" \ No newline at end of file diff --git a/resources/permit/permit.go b/resources/permit/permit.go index 341f910..ceb7611 100644 --- a/resources/permit/permit.go +++ b/resources/permit/permit.go @@ -2,6 +2,7 @@ package permit import ( _ "embed" + "github.com/eolinker/go-common/permit" "gopkg.in/yaml.v3" ) @@ -14,7 +15,7 @@ var ( func init() { - reset() + //reset() } func reset() { From bbc6e33fbcad2cb020f9cfe3173744260a222e1c Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 2 Aug 2024 14:07:29 +0800 Subject: [PATCH 09/19] =?UTF-8?q?=E6=9D=83=E9=99=90=E9=83=A8=E4=BB=BD?= =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/permit/identity/identity.go | 7 ++-- middleware/permit/permit.go | 52 +++++--------------------- module/permit/system/iml.go | 25 +++++++++++-- 3 files changed, 34 insertions(+), 50 deletions(-) diff --git a/middleware/permit/identity/identity.go b/middleware/permit/identity/identity.go index 5525ab1..ab11078 100644 --- a/middleware/permit/identity/identity.go +++ b/middleware/permit/identity/identity.go @@ -13,9 +13,10 @@ const ( type IdentityTeamService interface { IdentifyTeam(ctx context.Context, team string, uid string) ([]string, error) } -type IdentityProjectService interface { - IdentifyProject(ctx context.Context, project string, uid string) ([]string, error) -} + +// type IdentityProjectService interface { +// IdentifyProject(ctx context.Context, project string, uid string) ([]string, error) +// } type IdentitySystemService interface { IdentifySystem(ctx context.Context, uid string) ([]string, error) } diff --git a/middleware/permit/permit.go b/middleware/permit/permit.go index 934067c..c94f2c4 100644 --- a/middleware/permit/permit.go +++ b/middleware/permit/permit.go @@ -1,23 +1,20 @@ package permit_middleware import ( - "errors" "net/http" "reflect" permit_identity "github.com/eolinker/apipark/middleware/permit/identity" - permit_type "github.com/eolinker/apipark/service/permit-type" "github.com/eolinker/eosc/log" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/permit" "github.com/eolinker/go-common/pm3" "github.com/eolinker/go-common/utils" "github.com/gin-gonic/gin" - "gorm.io/gorm" ) var ( - checkSort = []string{permit_identity.ProjectGroup, permit_identity.TeamGroup, permit_identity.SystemGroup} + checkSort = []string{permit_identity.TeamGroup, permit_identity.SystemGroup} ) type IPermitMiddleware interface { @@ -58,6 +55,7 @@ func (p *PermitMiddleware) Check(method string, path string) (bool, []gin.Handle ginCtx.Abort() return } + //if userId == "admin" { // // 超级管理员不校验 // return @@ -74,48 +72,16 @@ func (p *PermitMiddleware) Check(method string, path string) (bool, []gin.Handle // 当前分组没有配置身份handler continue } - domains, myIdentity, ok := domainHandler(ginCtx) + _, myAccess, ok := domainHandler(ginCtx) if !ok { - // 无效的身份域 - //ginCtx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"code": http.StatusForbidden, "msg": "domain not found", "success": "fail"}) - //ginCtx.Abort() - //return continue } - myIdentitySet := utils.NewSet(myIdentity...) - myIdentitySet.Set(permit_type.AnyOne.Key) - for _, domain := range domains { - grantsOfAccess, err := p.permitService.GrantForDomain(ginCtx, domain) - if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { - //ginCtx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"code": http.StatusForbidden, "msg": "domain not found", "success": "fail"}) - //ginCtx.Abort() - //return - continue - } - if len(grantsOfAccess) == 0 { - // 当前域没有配置权限 - continue - } - checkCount := 0 - for _, access := range accessList { - grants, ok := grantsOfAccess[access] - if !ok { - // 当前域没有配置目标权限 - continue - } - - for _, grant := range grants { - if myIdentitySet.Has(grant) { - // 当前用户有权限 - return - } - } - checkCount++ - - } - if checkCount > 0 { - // 当前域有权限配置,且当前用户没有目标权限,则跳过当前group接下来的domain - break + accessMap := utils.SliceToMapO(myAccess, func(s string) (string, struct{}) { + return s, struct{}{} + }) + for _, acc := range accessList { + if _, ok := accessMap[acc]; ok { + return } } } diff --git a/module/permit/system/iml.go b/module/permit/system/iml.go index 7a8635e..2cd4d3c 100644 --- a/module/permit/system/iml.go +++ b/module/permit/system/iml.go @@ -2,8 +2,11 @@ package system import ( "context" + "errors" "reflect" + "github.com/gin-gonic/gin" + "github.com/eolinker/ap-account/service/role" "github.com/eolinker/go-common/autowire" "github.com/eolinker/go-common/permit" @@ -21,10 +24,11 @@ type imlSystemPermitModule struct { roleMemberService role.IRoleMemberService `autowired:""` } -func (m *imlSystemPermitModule) Permissions(ctx context.Context) ([]string, error) { - +func (m *imlSystemPermitModule) accesses(ctx context.Context) ([]string, error) { uid := utils.UserId(ctx) - + if uid == "" { + return nil, errors.New("not login") + } roleMembers, err := m.roleMemberService.List(ctx, role.SystemTarget(), uid) if err != nil { return nil, err @@ -45,13 +49,26 @@ func (m *imlSystemPermitModule) Permissions(ctx context.Context) ([]string, erro permits[p] = struct{}{} } } - return utils.MapToSlice(permits, func(k string, v struct{}) string { return k }), nil } +func (m *imlSystemPermitModule) Permissions(ctx context.Context) ([]string, error) { + return m.accesses(ctx) +} + +func (m *imlSystemPermitModule) domain(ctx *gin.Context) ([]string, []string, bool) { + + system, err := m.accesses(ctx) + if err != nil { + return nil, nil, false + } + return []string{role.GroupSystem}, system, true +} + func (m *imlSystemPermitModule) OnComplete() { + permit.AddDomainHandler(role.GroupSystem, m.domain) } func init() { From 490dfb13e17c271178afca21e57727e8ee497a08 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 2 Aug 2024 14:31:56 +0800 Subject: [PATCH 10/19] =?UTF-8?q?=E6=9D=83=E9=99=90=E9=83=A8=E4=BB=BD?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/access/access.yaml | 7 +- resources/access/access_test.go | 30 ++++++- resources/access/permit.yaml | 142 ++++++++++++++++++++++++++++++++ 3 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 resources/access/permit.yaml diff --git a/resources/access/access.yaml b/resources/access/access.yaml index 6dea86e..5840608 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -29,6 +29,8 @@ system: - "DELETE:/api/v1/user/department/member" - "POST:/api/v1/user/department/member/remove" - "POST:/api/v1/account/role" + dependents: + - system.organization.member.view - name: team cname: '团队' value: 'team' @@ -46,7 +48,8 @@ system: - "POST:/api/v1/manager/team" - "PUT:/api/v1/manager/team" - "DELETE:/api/v1/manager/team" - + dependents: + - system.organization.team.view - name: role cname: '角色' value: 'role' @@ -84,6 +87,8 @@ system: - "PUT:/api/v1/catalogue" - "DELETE:/api/v1/catalogue" - "PUT:/api/v1/catalogue/sort" + dependents: + - system.api_market.service_classification.view - name: devops cname: 运维 value: 'devops' diff --git a/resources/access/access_test.go b/resources/access/access_test.go index 1e24d46..95d216e 100644 --- a/resources/access/access_test.go +++ b/resources/access/access_test.go @@ -2,7 +2,9 @@ package access import ( "fmt" + "os" "sort" + "strings" "testing" "github.com/eolinker/go-common/access" @@ -16,7 +18,6 @@ func TestPrintlnRoleAccess(t *testing.T) { for _, k := range keys { fmt.Printf("- %s\n", k) } - } team, has := access.GetPermit("team") if has { @@ -27,3 +28,30 @@ func TestPrintlnRoleAccess(t *testing.T) { } } } + +func TestPrintlnAccessAPIs(t *testing.T) { + builder := &strings.Builder{} + printAccesses("system", builder) + printAccesses("team", builder) + os.WriteFile("permit.yaml", []byte(builder.String()), 0644) +} + +func printAccesses(group string, builder *strings.Builder) { + handler, has := access.GetPermit(group) + if has { + keys := handler.AccessKeys() + sort.Strings(keys) + builder.WriteString(fmt.Sprintf("%s:\n", group)) + for _, key := range keys { + apis, err := handler.GetPermits(key) + if err != nil { + continue + } + builder.WriteString(fmt.Sprintf(" %s:\n", key)) + for _, api := range apis { + builder.WriteString(fmt.Sprintf(" - %s\n", api)) + } + } + } + return +} diff --git a/resources/access/permit.yaml b/resources/access/permit.yaml new file mode 100644 index 0000000..971bfe5 --- /dev/null +++ b/resources/access/permit.yaml @@ -0,0 +1,142 @@ +system: + system.api_market.service_classification.manager: + - POST:/api/v1/catalogue + - PUT:/api/v1/catalogue + - DELETE:/api/v1/catalogue + - PUT:/api/v1/catalogue/sort + system.api_market.service_classification.view: + - GET:/api/v1/catalogues + system.devops.cluster.manager: + - PUT:/api/v1/cluster/reset + - POST:/api/v1/cluster/check + system.devops.cluster.view: + - GET:/api/v1/cluster/nodes + system.devops.log_configuration.manager: + - POST:/api/v1/dynamic/{name} + - PUT:/api/v1/dynamic/{name}/config + - DELETE:/api/v1/dynamic/{name}/batch + - PUT:/api/v1/dynamic/{name}/online + - PUT:/api/v1/dynamic/{name}/offline + system.devops.log_configuration.view: + - GET:/api/v1/dynamic/{name}/info + - GET:/api/v1/dynamic/{name}/list + - GET:/api/v1/dynamic/{name}/render + system.devops.ssl_certificate.manager: + - POST:/api/v1/certificate + - PUT:/api/v1/certificate + - DELETE:/api/v1/certificate + system.devops.ssl_certificate.view: + - GET:/api/v1/certificates + - GET:/api/v1/certificate + system.organization.member.manager: + - POST:/api/v1/user/account + - PUT:/api/v1/user/account + - DELETE:/api/v1/user/account + - POST:/api/v1/user/account/enable + - POST:/api/v1/user/account/disable + - POST:/api/v1/user/department + - PUT:/api/v1/user/department + - DELETE:/api/v1/user/department + - POST:/api/v1/user/department/member + - DELETE:/api/v1/user/department/member + - POST:/api/v1/user/department/member/remove + - POST:/api/v1/account/role + system.organization.member.view: + - GET:/api/v1/user/accounts + - GET:/api/v1/user/departments + system.organization.role.view_system_role: + - GET:/api/v1/system/roles + - GET:/api/v1/system/role + system.organization.role.view_team_role: + - GET:/api/v1/team/roles + - GET:/api/v1/team/role + system.organization.team.manager: + - POST:/api/v1/manager/team + - PUT:/api/v1/manager/team + - DELETE:/api/v1/manager/team + system.organization.team.view: + - GET:/api/v1/manager/teams + - GET:/api/v1/manager/team + system.workspace.api_market.view: + - GET:/api/v1/catalogue/services + - GET:/api/v1/catalogue/service + system.workspace.application.view_all: + - GET:/api/v1/apps + system.workspace.service.view_all: + - GET:/api/v1/services + system.workspace.team.view_all: + - GET:/api/v1/teams +team: + team.application.application.manager: + - GET:/api/v1/app/info + - PUT:/api/v1/app/info + - POST:/api/v1/team/app + - DELETE:/api/v1/app + team.application.authorization.manager: + - POST:/api/v1/app/authorization + - PUT:/api/v1/app/authorization + - DELETE:/api/v1/app/authorization + team.application.authorization.view: + - GET:/api/v1/app/authorization + - GET:/api/v1/app/authorizations + - GET:/api/v1/app/authorization/details + team.application.subscription.manager: + - POST:/api/v1/catalogue/service/subscribe + - POST:/api/v1/application/subscription/cancel + - POST:/api/v1/application/subscription/cancel_apply + team.application.subscription.view: + - GET:/api/v1/application/subscriptions + team.service.api.manager: + - POST:/api/v1/service/api + - PUT:/api/v1/service/api + - DELETE:/api/v1/service/api + - POST:/api/v1/service/api/copy + team.service.api.view: + - GET:/api/v1/service/apis + - GET:/api/v1/service/api/detail + - GET:/api/v1/service/api/detail/simple + - GET:/api/v1/service/api/define + - GET:/api/v1/service/apis/simple + team.service.release.manager: + - POST:/api/v1/service/publish/release/do + - PUT:/api/v1/service/publish/execute + - DELETE:/api/v1/service/release + team.service.release.view: + - GET:/api/v1/service/releases + - GET:/api/v1/service/release + - GET:/api/v1/service/publishs + - GET:/api/v1/service/publish/check + - GET:/api/v1/service/release/preview + - GET:/api/v1/service/publish/status + team.service.service.manager: + - GET:/api/v1/service/info + - PUT:/api/v1/service/info + - POST:/api/v1/team/service + - DELETE:/api/v1/team/service + team.service.subscription.manager: + - POST:/api/v1/service/approval/subscribe + - POST:/api/v1/service/subscriber + - DELETE:/api/v1/service/subscriber + team.service.subscription.view: + - GET:/api/v1/service/approval/subscribes + - GET:/api/v1/service/approval/subscribe + - GET:/api/v1/service/subscribers + team.service.upstream.manager: + - PUT:/api/v1/service/upstream + team.service.upstream.view: + - GET:/api/v1/service/upstream + team.team.member.manager: + - POST:/api/v1/team/member + - DELETE:/api/v1/team/member + - PUT:/api/v1/team/member/role + team.team.member.view: + - GET:/api/v1/team/members + - GET:/api/v1/team/members/simple + - GET:/api/v1/team/members/toadd + team.team.team.manager: + - POST:/api/v1/manager/team + - PUT:/api/v1/manager/team + - DELETE:/api/v1/manager/team + team.team.team.view: + - GET:/api/v1/manager/teams + - GET:/api/v1/manager/team From 71959de97663a51611f2aefc9f23b99616e8ae58 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 2 Aug 2024 14:37:41 +0800 Subject: [PATCH 11/19] =?UTF-8?q?=E4=BF=AE=E6=94=B9apipark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 9 ++------- go.sum | 4 ++++ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 2612bad..0a62eff 100644 --- a/go.mod +++ b/go.mod @@ -5,9 +5,9 @@ go 1.21 //toolchain go1.21.1 require ( - github.com/eolinker/ap-account v1.0.2 + github.com/eolinker/ap-account v1.0.3 github.com/eolinker/eosc v0.17.3 - github.com/eolinker/go-common v1.0.0 + github.com/eolinker/go-common v1.0.1 github.com/gabriel-vasile/mimetype v1.4.4 github.com/gin-gonic/gin v1.10.0 github.com/google/uuid v1.6.0 @@ -65,8 +65,3 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.5.2 // indirect ) - -replace ( - github.com/eolinker/ap-account => ../ap-account - github.com/eolinker/go-common => ../go-common -) diff --git a/go.sum b/go.sum index 55db0a8..d2c53a2 100644 --- a/go.sum +++ b/go.sum @@ -23,8 +23,12 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/eolinker/ap-account v1.0.3 h1:0FLGezl1SzPFwCp83sGSwU0Wzt0kSX3gGm5L876yTuo= +github.com/eolinker/ap-account v1.0.3/go.mod h1:MViCOvUaS2QrVift1Be3yGjjMywzICL9317eOxoixSI= github.com/eolinker/eosc v0.17.3 h1:sr2yT+v/AsqEdciRaaZZj0zL9pTufR5RvDW6+65hraQ= github.com/eolinker/eosc v0.17.3/go.mod h1:xgq816hpanlMXFtZw7Ztdctb1eEk9UPHchY4NfFO6Cw= +github.com/eolinker/go-common v1.0.1 h1:Uan6QmXAlPiX6hc1ptSIHWvaWXNA+VlBjC4gCaDEiz0= +github.com/eolinker/go-common v1.0.1/go.mod h1:Kb/jENMN1mApnodvRgV4YwO9FJby1Jkt2EUjrBjvSX4= github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I= github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= From 2b1e511437cb25cd60c7ce212b95802e16b26945 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 5 Aug 2024 10:28:05 +0800 Subject: [PATCH 12/19] =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=B9=BF=E5=9C=BA?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E8=AF=A6=E6=83=85=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/certificate/certificate.go | 4 +- controller/certificate/iml.go | 8 +- controller/dynamic-module/iml.go | 20 ++--- controller/service/iml.go | 4 + controller/service/service.go | 1 + go.mod | 5 ++ module/catalogue/dto/output.go | 12 +-- module/catalogue/iml.go | 20 ++++- module/certificate/certificate.go | 4 +- module/certificate/impl.go | 14 ++-- module/dynamic-module/dto/input.go | 18 ++--- module/dynamic-module/dto/output.go | 10 +-- module/dynamic-module/iml.go | 107 +++++++++++++++++--------- module/service/iml.go | 78 ++++++++++++++++++- module/service/module.go | 1 + module/team/iml.go | 8 +- plugins/core/certificate.go | 10 +-- plugins/core/dynamic-module.go | 2 - plugins/core/service.go | 2 + service/cluster/cluster.go | 23 +++--- service/team/model.go | 1 - stores/subscribe/model.go | 2 +- stores/team/model.go | 19 +++-- 23 files changed, 252 insertions(+), 121 deletions(-) diff --git a/controller/certificate/certificate.go b/controller/certificate/certificate.go index 748cc3e..b037e7c 100644 --- a/controller/certificate/certificate.go +++ b/controller/certificate/certificate.go @@ -9,9 +9,9 @@ import ( ) type ICertificateController interface { - Create(ctx *gin.Context, partitionId string, create *certificate_dto.FileInput) error + Create(ctx *gin.Context, create *certificate_dto.FileInput) error Update(ctx *gin.Context, id string, edit *certificate_dto.FileInput) error - ListForPartition(ctx *gin.Context, partitionId string) ([]*certificate_dto.Certificate, error) + ListForPartition(ctx *gin.Context) ([]*certificate_dto.Certificate, error) Detail(ctx *gin.Context, id string) (*certificate_dto.Certificate, *certificate_dto.File, error) Delete(ctx *gin.Context, id string) (string, error) } diff --git a/controller/certificate/iml.go b/controller/certificate/iml.go index 2936e27..178d136 100644 --- a/controller/certificate/iml.go +++ b/controller/certificate/iml.go @@ -14,16 +14,16 @@ type imlCertificate struct { module certificate.ICertificateModule `autowired:""` } -func (c *imlCertificate) Create(ctx *gin.Context, partitionId string, create *certificate_dto.FileInput) error { - return c.module.Create(ctx, partitionId, create) +func (c *imlCertificate) Create(ctx *gin.Context, create *certificate_dto.FileInput) error { + return c.module.Create(ctx, create) } func (c *imlCertificate) Update(ctx *gin.Context, id string, edit *certificate_dto.FileInput) error { return c.module.Update(ctx, id, edit) } -func (c *imlCertificate) ListForPartition(ctx *gin.Context, partitionId string) ([]*certificate_dto.Certificate, error) { - return c.module.List(ctx, partitionId) +func (c *imlCertificate) ListForPartition(ctx *gin.Context) ([]*certificate_dto.Certificate, error) { + return c.module.List(ctx) } func (c *imlCertificate) Detail(ctx *gin.Context, id string) (*certificate_dto.Certificate, *certificate_dto.File, error) { diff --git a/controller/dynamic-module/iml.go b/controller/dynamic-module/iml.go index 5e67f77..f292509 100644 --- a/controller/dynamic-module/iml.go +++ b/controller/dynamic-module/iml.go @@ -79,7 +79,7 @@ func (i *imlDynamicModuleController) Get(ctx *gin.Context, module string, id str return i.module.Get(ctx, module, id) } -func (i *imlDynamicModuleController) List(ctx *gin.Context, module string, keyword string, partitionId string, page string, pageSize string) ([]map[string]interface{}, *dynamic_module_dto.PluginInfo, int64, error) { +func (i *imlDynamicModuleController) List(ctx *gin.Context, module string, keyword string, clusterId string, page string, pageSize string) ([]map[string]interface{}, *dynamic_module_dto.PluginInfo, int64, error) { p, err := strconv.Atoi(page) if err != nil { p = 1 @@ -93,15 +93,15 @@ func (i *imlDynamicModuleController) List(ctx *gin.Context, module string, keywo if err != nil { return nil, nil, 0, err } - if partitionId == "" { - partitionId = "[]" - } - ids := make([]string, 0) - err = json.Unmarshal([]byte(partitionId), &ids) - if err != nil { - return nil, nil, 0, err - } - plugin, err := i.module.PluginInfo(ctx, module, ids...) + //if clusterId == "" { + // clusterId = "[]" + //} + //ids := make([]string, 0) + //err = json.Unmarshal([]byte(clusterId), &ids) + //if err != nil { + // return nil, nil, 0, err + //} + plugin, err := i.module.PluginInfo(ctx, module) if err != nil { return nil, nil, 0, err } diff --git a/controller/service/iml.go b/controller/service/iml.go index 0f5b26f..120aaa8 100644 --- a/controller/service/iml.go +++ b/controller/service/iml.go @@ -59,6 +59,10 @@ type imlAppController struct { module service.IAppModule `autowired:""` } +func (i *imlAppController) Search(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) { + return i.module.Search(ctx, teamId, keyword) +} + func (i *imlAppController) CreateApp(ctx *gin.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) { return i.module.CreateApp(ctx, teamID, input) } diff --git a/controller/service/service.go b/controller/service/service.go index 5b057b0..69cf4c9 100644 --- a/controller/service/service.go +++ b/controller/service/service.go @@ -35,6 +35,7 @@ type IAppController interface { CreateApp(ctx *gin.Context, teamID string, project *service_dto.CreateApp) (*service_dto.App, error) UpdateApp(ctx *gin.Context, appId string, project *service_dto.UpdateApp) (*service_dto.App, error) + Search(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) SearchMyApps(ctx *gin.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) // SimpleApps 获取简易项目列表 SimpleApps(ctx *gin.Context, keyword string) ([]*service_dto.SimpleAppItem, error) diff --git a/go.mod b/go.mod index 0a62eff..524a440 100644 --- a/go.mod +++ b/go.mod @@ -65,3 +65,8 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gorm.io/driver/mysql v1.5.2 // indirect ) + + +replace ( + github.com/eolinker/ap-account v1.0.3 => ../ap-account +) \ No newline at end of file diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index 684e114..1fbf528 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -25,14 +25,16 @@ type ServiceDetail struct { Document string `json:"document"` Basic *ServiceBasic `json:"basic"` Apis []*ServiceApi `json:"apis"` - //DisableApis []*ServiceApiBasic `json:"disable_apis"` } type ServiceBasic struct { - //Service auto.Label `json:"service" aolabel:"service"` - Team auto.Label `json:"team" aolabel:"team"` - ApiNum int `json:"api_num"` - SubscriberNum int `json:"subscriber_num"` + Team auto.Label `json:"team" aolabel:"team"` + ApiNum int `json:"api_num"` + AppNum int `json:"app_num"` + Tags []auto.Label `json:"tags" aolabel:"tag"` + Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` + Version string `json:"version"` + UpdateTime auto.TimeLabel `json:"update_time"` } type ServiceApiBasic struct { diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index a99c59b..07edba2 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -252,15 +252,27 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca if err != nil { return nil, err } - + tags, err := i.serviceTagService.List(ctx, []string{sid}, nil) + if err != nil { + return nil, err + } + tagIds := utils.SliceToSlice(tags, func(t *service_tag.Tag) string { + return t.Tid + }, func(t *service_tag.Tag) bool { + return t.Sid == sid + }) return &catalogue_dto.ServiceDetail{ Name: s.Name, Description: s.Description, Document: docStr, Basic: &catalogue_dto.ServiceBasic{ - Team: auto.UUID(s.Team), - ApiNum: len(apis), - SubscriberNum: int(countMap[s.Id]), + Team: auto.UUID(s.Team), + ApiNum: len(apis), + AppNum: int(countMap[s.Id]), + Tags: auto.List(tagIds), + Catalogue: auto.UUID(s.Catalogue), + Version: r.Version, + UpdateTime: auto.TimeLabel(r.CreateAt), }, Apis: apis, }, nil diff --git a/module/certificate/certificate.go b/module/certificate/certificate.go index 726f4a1..000b662 100644 --- a/module/certificate/certificate.go +++ b/module/certificate/certificate.go @@ -11,9 +11,9 @@ import ( ) type ICertificateModule interface { - Create(ctx context.Context, clusterId string, create *certificate_dto.FileInput) error + Create(ctx context.Context, create *certificate_dto.FileInput) error Update(ctx context.Context, id string, edit *certificate_dto.FileInput) error - List(ctx context.Context, clusterId string) ([]*certificate_dto.Certificate, error) + List(ctx context.Context) ([]*certificate_dto.Certificate, error) Detail(ctx context.Context, id string) (*certificate_dto.Certificate, *certificate_dto.File, error) Delete(ctx context.Context, id string) error } diff --git a/module/certificate/impl.go b/module/certificate/impl.go index e3b978e..4ff6bf3 100644 --- a/module/certificate/impl.go +++ b/module/certificate/impl.go @@ -75,7 +75,7 @@ func (m *imlCertificate) initGateway(ctx context.Context, clusterId string, clie return certificateClient.Online(ctx, certs...) } -func (m *imlCertificate) save(ctx context.Context, id string, partitionId string, create *certificatedto.FileInput) (*certificatedto.Certificate, error) { +func (m *imlCertificate) save(ctx context.Context, id string, clusterId string, create *certificatedto.FileInput) (*certificatedto.Certificate, error) { keyData, err := base64.StdEncoding.DecodeString(create.Key) if err != nil { @@ -86,7 +86,7 @@ func (m *imlCertificate) save(ctx context.Context, id string, partitionId string if err != nil { return nil, fmt.Errorf("decode cert error: %w", err) } - o, err := m.service.Save(ctx, id, partitionId, keyData, certData) + o, err := m.service.Save(ctx, id, clusterId, keyData, certData) if err != nil { return nil, err } @@ -115,12 +115,12 @@ func (m *imlCertificate) syncGateway(ctx context.Context, clusterId string, rele return dynamicClient.Offline(ctx, releaseInfo) } -func (m *imlCertificate) Create(ctx context.Context, clusterId string, create *certificatedto.FileInput) error { +func (m *imlCertificate) Create(ctx context.Context, create *certificatedto.FileInput) error { return m.transaction.Transaction(ctx, func(ctx context.Context) error { id := uuid.New().String() version := time.Now().Format("20060102150405") - err := m.syncGateway(ctx, clusterId, &gateway.DynamicRelease{ + err := m.syncGateway(ctx, cluster.DefaultClusterID, &gateway.DynamicRelease{ BasicItem: &gateway.BasicItem{ ID: id, Description: "", @@ -137,7 +137,7 @@ func (m *imlCertificate) Create(ctx context.Context, clusterId string, create *c if err != nil { return err } - _, err = m.save(ctx, id, clusterId, create) + _, err = m.save(ctx, id, cluster.DefaultClusterID, create) if err != nil { return err } @@ -183,8 +183,8 @@ func (m *imlCertificate) Update(ctx context.Context, id string, edit *certificat return nil }) } -func (m *imlCertificate) List(ctx context.Context, clusterId string) ([]*certificatedto.Certificate, error) { - certs, err := m.service.List(ctx, clusterId) +func (m *imlCertificate) List(ctx context.Context) ([]*certificatedto.Certificate, error) { + certs, err := m.service.List(ctx, cluster.DefaultClusterID) if err != nil { return nil, err } diff --git a/module/dynamic-module/dto/input.go b/module/dynamic-module/dto/input.go index 8c13a53..241aead 100644 --- a/module/dynamic-module/dto/input.go +++ b/module/dynamic-module/dto/input.go @@ -1,19 +1,19 @@ package dynamic_module_dto type CreateDynamicModule struct { - Id string `json:"id"` - Name string `json:"title"` - Driver string `json:"driver"` - Description string `json:"description"` - Config map[string]PartitionConfig `json:"config"` + Id string `json:"id"` + Name string `json:"title"` + Driver string `json:"driver"` + Description string `json:"description"` + Config map[string]interface{} `json:"config"` } -type PartitionConfig map[string]interface{} +//type PartitionConfig map[string]interface{} type EditDynamicModule struct { - Name *string `json:"title"` - Description *string `json:"description"` - Config *map[string]PartitionConfig `json:"config"` + Name *string `json:"title"` + Description *string `json:"description"` + Config *map[string]interface{} `json:"config"` } type ClusterInput struct { diff --git a/module/dynamic-module/dto/output.go b/module/dynamic-module/dto/output.go index ad66372..fe65ddb 100644 --- a/module/dynamic-module/dto/output.go +++ b/module/dynamic-module/dto/output.go @@ -5,11 +5,11 @@ import ( ) type DynamicModule struct { - Id string `json:"id"` - Name string `json:"title"` - Driver string `json:"driver"` - Description string `json:"description"` - Config map[string]PartitionConfig `json:"config"` + Id string `json:"id"` + Name string `json:"title"` + Driver string `json:"driver"` + Description string `json:"description"` + Config map[string]interface{} `json:"config"` } type PluginBasic struct { diff --git a/module/dynamic-module/iml.go b/module/dynamic-module/iml.go index 1bf0ead..ab8c2a0 100644 --- a/module/dynamic-module/iml.go +++ b/module/dynamic-module/iml.go @@ -47,9 +47,9 @@ func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, if !has { return fmt.Errorf("模块【%s】不存在", module) } - if len(clusterInput.Clusters) == 0 { - return fmt.Errorf("上线分区失败,分区为空") - } + //if len(clusterInput.Clusters) == 0 { + // return fmt.Errorf("上线分区失败,分区为空") + //} id = strings.ToLower(fmt.Sprintf("%s_%s", id, module)) info, err := i.dynamicModuleService.Get(ctx, id) @@ -57,21 +57,13 @@ func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, return fmt.Errorf("上线失败,配置不存在") } clusters, err := i.clusterService.List(ctx, clusterInput.Clusters...) - if err != nil { + if err != nil || len(clusters) == 0 { return fmt.Errorf("上线失败,集群不存在") } return i.transaction.Transaction(ctx, func(ctx context.Context) error { - data := make(map[string]*gateway.DynamicRelease) - err = json.Unmarshal([]byte(info.Config), &data) - if err != nil { - return err - } for _, c := range clusters { - cfg, ok := data[c.Uuid] - if !ok { - continue - } + // 插入发布历史 err = i.dynamicModulePublishService.Create(ctx, &dynamic_module.CreateDynamicModulePublish{ ID: uuid.New().String(), @@ -84,6 +76,7 @@ func (i *imlDynamicModule) Online(ctx context.Context, module string, id string, return err } err = i.dynamicClient(ctx, c.Uuid, module, func(dynamicClient gateway.IDynamicClient) error { + cfg := &gateway.DynamicRelease{} err = json.Unmarshal([]byte(info.Config), &cfg) if err != nil { return err @@ -114,12 +107,22 @@ func (i *imlDynamicModule) Offline(ctx context.Context, module string, id string if !has { return fmt.Errorf("模块【%s】不存在", module) } - if len(clusterInput.Clusters) == 0 { - return fmt.Errorf("下线分区失败,分区为空") - } + //if len(clusterInput.Clusters) == 0 { + // return fmt.Errorf("下线分区失败,分区为空") + //} return i.transaction.Transaction(ctx, func(ctx context.Context) error { id = strings.ToLower(fmt.Sprintf("%s_%s", id, module)) + if len(clusterInput.Clusters) == 0 { + clusters, err := i.clusterService.List(ctx) + if err != nil { + return err + } + clusterInput.Clusters = make([]string, 0) + for _, c := range clusters { + clusterInput.Clusters = append(clusterInput.Clusters, c.Uuid) + } + } for _, clusterId := range clusterInput.Clusters { err := i.dynamicClient(ctx, clusterId, module, func(dynamicClient gateway.IDynamicClient) error { return dynamicClient.Offline(ctx, &gateway.DynamicRelease{ @@ -422,7 +425,7 @@ func (i *imlDynamicModule) Get(ctx context.Context, module string, id string) (* if err != nil { return nil, err } - cfg := make(map[string]dynamic_module_dto.PartitionConfig) + cfg := make(map[string]interface{}) err = json.Unmarshal([]byte(info.Config), &cfg) if err != nil { return nil, err @@ -463,31 +466,65 @@ func (i *imlDynamicModule) List(ctx context.Context, module string, keyword stri userIDs := utils.SliceToSlice(list, func(s *dynamic_module.DynamicModule) string { return s.Updater }) + clusters, err := i.clusterService.List(ctx) + if err != nil { + return nil, 0, err + } + userMap := i.userService.GetLabels(ctx, userIDs...) items := make([]map[string]interface{}, 0, len(list)) suffix := fmt.Sprintf("_%s", module) - for _, l := range list { - item := map[string]interface{}{ - "id": strings.TrimSuffix(l.ID, suffix), - "title": l.Name, - "driver": l.Driver, - "description": l.Description, - "updater": userMap[l.Updater], - "update_time": l.UpdateAt.Format("2006-01-02 15:04:05"), - } - - tmp := make(map[string]interface{}) - err = json.Unmarshal([]byte(l.Config), &tmp) - if err == nil { - for _, column := range d.Define().Columns() { - if _, ok := item[column]; ok { - continue + for _, c := range clusters { + err = i.dynamicClient(ctx, c.Uuid, module, func(dynamicClient gateway.IDynamicClient) error { + versions, err := dynamicClient.Versions(ctx, map[string]string{ + "module": module, + }) + if err != nil { + log.Error("get versions error", err) + } + for _, l := range list { + status := "未发布" + id := strings.TrimSuffix(l.ID, suffix) + + item := map[string]interface{}{ + "id": id, + "title": l.Name, + "driver": l.Driver, + "description": l.Description, + "updater": userMap[l.Updater], + "update_time": l.UpdateAt.Format("2006-01-02 15:04:05"), } - item[column] = tmp[column] + tmp := make(map[string]interface{}) + err = json.Unmarshal([]byte(l.Config), &tmp) + if err == nil { + for _, column := range d.Define().Columns() { + if _, ok := item[column]; ok { + continue + } + item[column] = tmp[column] + + } + } + if versions != nil { + if v, ok := versions[strings.ToLower(l.ID)]; ok { + if v == l.Version { + status = "已发布" + } else { + status = "待发布" + } + } + } + item["status"] = status + items = append(items, item) } + return nil + }) + if err != nil { + return nil, 0, err } - items = append(items, item) + } + return items, total, nil } diff --git a/module/service/iml.go b/module/service/iml.go index 28dc32c..45f584a 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -194,9 +194,9 @@ func (i *imlServiceModule) Search(ctx context.Context, teamID string, keyword st if err != nil { return nil, err } - list, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"team": teamID}, "update_at desc") + list, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"team": teamID, "as_server": true}, "update_at desc") } else { - list, err = i.serviceService.Search(ctx, keyword, nil, "update_at desc") + list, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"as_server": true}, "update_at desc") } if err != nil { return nil, err @@ -425,6 +425,80 @@ type imlAppModule struct { transaction store.ITransaction `autowired:""` } +func (i *imlAppModule) Search(ctx context.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) { + var services []*service.Service + var err error + if teamId != "" { + _, err = i.teamService.Get(ctx, teamId) + if err != nil { + return nil, err + } + services, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"team": teamId, "as_app": true}, "update_at desc") + } else { + services, err = i.serviceService.Search(ctx, keyword, map[string]interface{}{"as_app": true}, "update_at desc") + } + if err != nil { + return nil, err + } + + serviceIds := utils.SliceToSlice(services, func(p *service.Service) string { + return p.Id + }) + + subscribers, err := i.subscribeService.SubscriptionsByApplication(ctx, serviceIds...) + if err != nil { + return nil, err + } + + subscribeCount := map[string]int64{} + subscribeVerifyCount := map[string]int64{} + verifyTmp := map[string]struct{}{} + subscribeTmp := map[string]struct{}{} + for _, s := range subscribers { + key := fmt.Sprintf("%s-%s", s.Service, s.Application) + switch s.ApplyStatus { + case subscribe.ApplyStatusSubscribe: + if _, ok := subscribeTmp[key]; !ok { + subscribeTmp[key] = struct{}{} + subscribeCount[s.Application]++ + } + case subscribe.ApplyStatusReview: + if _, ok := verifyTmp[key]; !ok { + verifyTmp[key] = struct{}{} + subscribeVerifyCount[s.Application]++ + } + default: + + } + } + items := make([]*service_dto.AppItem, 0, len(services)) + for _, model := range services { + subscribeNum := subscribeCount[model.Id] + verifyNum := subscribeVerifyCount[model.Id] + items = append(items, &service_dto.AppItem{ + Id: model.Id, + Name: model.Name, + Description: model.Description, + CreateTime: auto.TimeLabel(model.CreateTime), + UpdateTime: auto.TimeLabel(model.UpdateTime), + Team: auto.UUID(model.Team), + SubscribeNum: subscribeNum, + SubscribeVerifyNum: verifyNum, + CanDelete: subscribeNum == 0, + }) + } + sort.Slice(items, func(i, j int) bool { + if items[i].SubscribeNum != items[j].SubscribeNum { + return items[i].SubscribeNum > items[j].SubscribeNum + } + if items[i].SubscribeVerifyNum != items[j].SubscribeVerifyNum { + return items[i].SubscribeVerifyNum > items[j].SubscribeVerifyNum + } + return items[i].Name < items[j].Name + }) + return items, nil +} + func (i *imlAppModule) CreateApp(ctx context.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) { if input.Id == "" { diff --git a/module/service/module.go b/module/service/module.go index ffdf52e..75217d8 100644 --- a/module/service/module.go +++ b/module/service/module.go @@ -36,6 +36,7 @@ type IServiceModule interface { type IAppModule interface { CreateApp(ctx context.Context, teamID string, input *service_dto.CreateApp) (*service_dto.App, error) UpdateApp(ctx context.Context, appId string, input *service_dto.UpdateApp) (*service_dto.App, error) + Search(ctx context.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) SearchMyApps(ctx context.Context, teamId string, keyword string) ([]*service_dto.AppItem, error) // SimpleApps 获取简易项目列表 SimpleApps(ctx context.Context, keyword string) ([]*service_dto.SimpleAppItem, error) diff --git a/module/team/iml.go b/module/team/iml.go index 458c82b..4f71056 100644 --- a/module/team/iml.go +++ b/module/team/iml.go @@ -80,6 +80,9 @@ func (m *imlTeamModule) Create(ctx context.Context, input *team_dto.CreateTeam) } err := m.transaction.Transaction(ctx, func(ctx context.Context) error { + if input.Master == "" { + input.Master = utils.UserId(ctx) + } err := m.service.Create(ctx, &team.CreateTeam{ Id: input.Id, Name: input.Name, @@ -88,15 +91,12 @@ func (m *imlTeamModule) Create(ctx context.Context, input *team_dto.CreateTeam) if err != nil { return err } - if input.Master == "" { - input.Master = utils.UserId(ctx) - } err = m.memberService.AddMemberTo(ctx, input.Id, input.Master) if err != nil { return err } - supperRole, err := m.roleService.GetDefaultRole(ctx, role.GroupTeam) + supperRole, err := m.roleService.GetSupperRole(ctx, role.GroupTeam) if err != nil { return err } diff --git a/plugins/core/certificate.go b/plugins/core/certificate.go index f4db8fe..cb3fa5e 100644 --- a/plugins/core/certificate.go +++ b/plugins/core/certificate.go @@ -8,10 +8,10 @@ import ( func (p *plugin) certificateApi() []pm3.Api { return []pm3.Api{ - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partition/certificates", []string{"context", "query:partition"}, []string{"certificates"}, p.certificateController.ListForPartition), - pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/partition/certificate", []string{"context", "query:id"}, []string{"certificate", "cert"}, p.certificateController.Detail), - pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/partition/certificate", []string{"context", "query:partition", "body"}, nil, p.certificateController.Create), - pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/partition/certificate", []string{"context", "query:id", "body"}, nil, p.certificateController.Update), - pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/partition/certificate", []string{"context", "query:id"}, []string{"id"}, p.certificateController.Delete), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/certificates", []string{"context"}, []string{"certificates"}, p.certificateController.ListForPartition), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/certificate", []string{"context", "query:id"}, []string{"certificate", "cert"}, p.certificateController.Detail), + pm3.CreateApiWidthDoc(http.MethodPost, "/api/v1/certificate", []string{"context", "body"}, nil, p.certificateController.Create), + pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/certificate", []string{"context", "query:id", "body"}, nil, p.certificateController.Update), + pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/certificate", []string{"context", "query:id"}, []string{"id"}, p.certificateController.Delete), } } diff --git a/plugins/core/dynamic-module.go b/plugins/core/dynamic-module.go index 483ed61..a37cdad 100644 --- a/plugins/core/dynamic-module.go +++ b/plugins/core/dynamic-module.go @@ -17,7 +17,5 @@ func (p *plugin) DynamicModuleApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/dynamics/:group", []string{"context", "rest:group"}, []string{"dynamics"}, p.dynamicModuleController.ModuleDrivers), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/dynamic/:name/online", []string{"context", "rest:name", "query:id", "body"}, nil, p.dynamicModuleController.Online), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/dynamic/:name/offline", []string{"context", "rest:name", "query:id", "body"}, nil, p.dynamicModuleController.Offline), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name/status", []string{"context", "rest:name", "query:keyword", "query:page", "query:page_size"}, []string{"list"}, p.dynamicModuleController.PartitionStatuses), - //pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/dynamic/:name", []string{"context", "rest:name", "query:id"}, []string{"info"}, p.dynamicModuleController.PartitionStatus), } } diff --git a/plugins/core/service.go b/plugins/core/service.go index 57d087f..4d3f8c8 100644 --- a/plugins/core/service.go +++ b/plugins/core/service.go @@ -13,6 +13,7 @@ func (p *plugin) ServiceApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/service/info", []string{"context", "query:service", "body"}, []string{"service"}, p.serviceController.Edit), pm3.CreateApiWidthDoc(http.MethodDelete, "/api/v1/service/info", []string{"context", "query:service"}, nil, p.serviceController.Delete), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_services", []string{"context", "query:team", "query:keyword"}, []string{"services"}, p.serviceController.SearchMyServices), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/services", []string{"context", "query:team", "query:keyword"}, []string{"services"}, p.serviceController.Search), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/services/mine", []string{"context", "query:keyword"}, []string{"services"}, p.serviceController.MySimple), @@ -24,6 +25,7 @@ func (p *plugin) ServiceApis() []pm3.Api { pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps", []string{"context", "query:keyword"}, []string{"apps"}, p.appController.SimpleApps), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/simple/apps/mine", []string{"context", "query:keyword"}, []string{"apps"}, p.appController.MySimpleApps), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/my_apps", []string{"context", "query:team", "query:keyword"}, []string{"apps"}, p.appController.SearchMyApps), + pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/apps", []string{"context", "query:team", "query:keyword"}, []string{"apps"}, p.appController.Search), pm3.CreateApiWidthDoc(http.MethodPut, "/api/v1/app/info", []string{"context", "query:app", "body"}, []string{"app"}, p.appController.UpdateApp), pm3.CreateApiWidthDoc(http.MethodGet, "/api/v1/service/doc", []string{"context", "query:service"}, []string{"doc"}, p.serviceController.ServiceDoc), diff --git a/service/cluster/cluster.go b/service/cluster/cluster.go index 248284c..b3e7575 100644 --- a/service/cluster/cluster.go +++ b/service/cluster/cluster.go @@ -25,8 +25,8 @@ var ( type IClusterService interface { CountByPartition(ctx context.Context) (map[string]int, error) List(ctx context.Context, clusterIds ...string) ([]*Cluster, error) - ListByClusters(ctx context.Context, partitionId string, ids ...string) ([]*Cluster, error) - Search(ctx context.Context, keyword string, partitionId ...string) ([]*Cluster, error) + ListByClusters(ctx context.Context, ids ...string) ([]*Cluster, error) + Search(ctx context.Context, keyword string, clusterId ...string) ([]*Cluster, error) Create(ctx context.Context, name string, resume string, address string) (*Cluster, error) UpdateInfo(ctx context.Context, id string, name *string, resume *string) (*Cluster, error) UpdateAddress(ctx context.Context, id string, address string) ([]*Node, error) @@ -56,11 +56,8 @@ func (s *imlClusterService) GatewayClient(ctx context.Context, id string) (gatew }) } -func (s *imlClusterService) ListByClusters(ctx context.Context, partitionId string, ids ...string) ([]*Cluster, error) { +func (s *imlClusterService) ListByClusters(ctx context.Context, ids ...string) ([]*Cluster, error) { wm := make(map[string]interface{}) - if partitionId != "" { - wm["partition"] = partitionId - } if len(ids) > 0 { wm["uuid"] = ids @@ -391,7 +388,7 @@ func (s *imlClusterService) Nodes(ctx context.Context, clusterIds ...string) ([] func (s *imlClusterService) CountByPartition(ctx context.Context) (map[string]int, error) { return s.store.Count(ctx) } -func (s *imlClusterService) Search(ctx context.Context, keyword string, partitionId ...string) ([]*Cluster, error) { +func (s *imlClusterService) Search(ctx context.Context, keyword string, clusterId ...string) ([]*Cluster, error) { wheres := make([]string, 0, 2) value := make([]interface{}, 0, 3) if keyword != "" { @@ -399,13 +396,13 @@ func (s *imlClusterService) Search(ctx context.Context, keyword string, partitio value = append(value, "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%") } - if len(partitionId) > 0 { - if len(partitionId) == 1 { - wheres = append(wheres, "`partition` = ?") - value = append(value, partitionId[0]) + if len(clusterId) > 0 { + if len(clusterId) == 1 { + wheres = append(wheres, "`uuid` = ?") + value = append(value, clusterId[0]) } else { - wheres = append(wheres, "`partition` in (?)") - value = append(value, partitionId) + wheres = append(wheres, "`uuid` in (?)") + value = append(value, clusterId) } } diff --git a/service/team/model.go b/service/team/model.go index d97f26b..87cfdc8 100644 --- a/service/team/model.go +++ b/service/team/model.go @@ -35,7 +35,6 @@ type CreateTeam struct { Id string `json:"id" ` Name string `json:"name" ` Description string `json:"description"` - //Master string `json:"master" ` } type EditTeam struct { Name *string `json:"name" ` diff --git a/stores/subscribe/model.go b/stores/subscribe/model.go index 50e1133..265f031 100644 --- a/stores/subscribe/model.go +++ b/stores/subscribe/model.go @@ -5,7 +5,7 @@ import "time" type Subscribe struct { Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` UUID string `gorm:"size:36;not null;column:uuid;comment:uuid;uniqueIndex:uuid;"` - Service string `gorm:"size:36;not null;column:service;comment:服务id;uniqueIndex:unique_subscribe;uniqueIndex:unique_subscribe"` + Service string `gorm:"size:36;not null;column:service;comment:服务id;uniqueIndex:unique_subscribe"` Application string `gorm:"size:36;not null;column:application;comment:应用id,项目id,系统id;uniqueIndex:unique_subscribe"` ApplyStatus int `gorm:"type:tinyint(1);not null;column:apply_status;comment:申请状态;index:status;"` Applier string `gorm:"size:36;not null;column:applier;comment:申请人;index:applier"` diff --git a/stores/team/model.go b/stores/team/model.go index 4a920fb..4ab5aba 100644 --- a/stores/team/model.go +++ b/stores/team/model.go @@ -5,16 +5,15 @@ import ( ) type Team struct { - Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` - UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` - Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` - Description string `gorm:"size:255;not null;column:description;comment:description"` - //Master string `gorm:"size:36;not null;column:master;comment:负责人id"` // 负责人id - Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id - Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id - CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` - UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` - IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` + Id int64 `gorm:"column:id;type:BIGINT(20);AUTO_INCREMENT;NOT NULL;comment:id;primary_key;comment:主键ID;"` + UUID string `gorm:"type:varchar(36);not null;column:uuid;uniqueIndex:uuid;comment:UUID;"` + Name string `gorm:"type:varchar(100);not null;column:name;comment:name"` + Description string `gorm:"size:255;not null;column:description;comment:description"` + Creator string `gorm:"size:36;not null;column:creator;comment:创建人id" aovalue:"creator"` // 创建人id + Updater string `gorm:"size:36;not null;column:updater;comment:修改人id" aovalue:"updater"` // 修改人id + CreateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP;column:create_at;comment:创建时间"` + UpdateAt time.Time `gorm:"type:timestamp;NOT NULL;DEFAULT:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;column:update_at;comment:修改时间" json:"update_at"` + IsDelete bool `gorm:"type:tinyint(1);not null;column:is_delete;comment:是否删除"` } func (t *Team) IdValue() int64 { From 9d06cfd9a5236cf230e5bb2a710e857aa5bbd8e7 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 5 Aug 2024 10:33:25 +0800 Subject: [PATCH 13/19] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 7 ++----- go.sum | 4 ++-- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 524a440..8198890 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.21 //toolchain go1.21.1 require ( - github.com/eolinker/ap-account v1.0.3 + github.com/eolinker/ap-account v1.0.5 github.com/eolinker/eosc v0.17.3 github.com/eolinker/go-common v1.0.1 github.com/gabriel-vasile/mimetype v1.4.4 @@ -66,7 +66,4 @@ require ( gorm.io/driver/mysql v1.5.2 // indirect ) - -replace ( - github.com/eolinker/ap-account v1.0.3 => ../ap-account -) \ No newline at end of file +//replace github.com/eolinker/ap-account v1.0.4 => ../ap-account diff --git a/go.sum b/go.sum index d2c53a2..91b4922 100644 --- a/go.sum +++ b/go.sum @@ -23,8 +23,8 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/eolinker/ap-account v1.0.3 h1:0FLGezl1SzPFwCp83sGSwU0Wzt0kSX3gGm5L876yTuo= -github.com/eolinker/ap-account v1.0.3/go.mod h1:MViCOvUaS2QrVift1Be3yGjjMywzICL9317eOxoixSI= +github.com/eolinker/ap-account v1.0.5 h1:Dx47BL6iPN+6DPuAlzK9fkIgfGBZ5QOrbuocX9p+Aa0= +github.com/eolinker/ap-account v1.0.5/go.mod h1:MViCOvUaS2QrVift1Be3yGjjMywzICL9317eOxoixSI= github.com/eolinker/eosc v0.17.3 h1:sr2yT+v/AsqEdciRaaZZj0zL9pTufR5RvDW6+65hraQ= github.com/eolinker/eosc v0.17.3/go.mod h1:xgq816hpanlMXFtZw7Ztdctb1eEk9UPHchY4NfFO6Cw= github.com/eolinker/go-common v1.0.1 h1:Uan6QmXAlPiX6hc1ptSIHWvaWXNA+VlBjC4gCaDEiz0= From cf58fb9a1ac34f280f49ca43f432797a9c050d2c Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 5 Aug 2024 13:52:02 +0800 Subject: [PATCH 14/19] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=9B=A2=E9=98=9F?= =?UTF-8?q?=E6=97=A0=E6=9D=83=E9=99=90=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- module/permit/team/iml.go | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/module/permit/team/iml.go b/module/permit/team/iml.go index 4ecbeeb..a624f80 100644 --- a/module/permit/team/iml.go +++ b/module/permit/team/iml.go @@ -2,6 +2,11 @@ package team import ( "context" + "errors" + + "github.com/eolinker/go-common/permit" + + "github.com/gin-gonic/gin" "github.com/eolinker/ap-account/service/role" "github.com/eolinker/go-common/autowire" @@ -48,4 +53,47 @@ func (m *imlTeamPermitModule) Permissions(ctx context.Context, teamId string) ([ } func (m *imlTeamPermitModule) OnComplete() { + permit.AddDomainHandler(role.GroupTeam, m.domain) +} + +func (m *imlTeamPermitModule) accesses(ctx context.Context, teamId string) ([]string, error) { + uid := utils.UserId(ctx) + if uid == "" { + return nil, errors.New("not login") + } + roleMembers, err := m.roleMemberService.List(ctx, role.TeamTarget(teamId), uid) + if err != nil { + return nil, err + } + if len(roleMembers) == 0 { + return []string{}, nil + } + roleIds := utils.SliceToSlice(roleMembers, func(rm *role.Member) string { + return rm.Role + }) + roles, err := m.roleService.List(ctx, roleIds...) + if err != nil { + return nil, err + } + permits := make(map[string]struct{}) + for _, r := range roles { + for _, p := range r.Permit { + permits[p] = struct{}{} + } + } + return utils.MapToSlice(permits, func(k string, v struct{}) string { + return k + }), nil +} + +func (m *imlTeamPermitModule) domain(ctx *gin.Context) ([]string, []string, bool) { + teamId := ctx.Query("team") + if teamId == "" { + return nil, nil, false + } + accesses, err := m.accesses(ctx, teamId) + if err != nil { + return nil, nil, false + } + return []string{role.GroupTeam}, accesses, true } From 6baf85126113bdc3cdf09e0d3a4debe9206d6401 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 8 Aug 2024 01:09:08 +0800 Subject: [PATCH 15/19] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=9B=A2=E9=98=9F?= =?UTF-8?q?=E3=80=81=E5=8F=91=E5=B8=83=E7=9A=84=E4=B8=80=E7=B3=BB=E5=88=97?= =?UTF-8?q?bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/publish/iml.go | 3 +- module/dynamic-module/iml.go | 2 +- module/my-team/iml.go | 3 ++ module/publish/iml.go | 59 ++++++++++++++++++------------------ module/publish/module.go | 2 +- module/service/iml.go | 12 ++++---- 6 files changed, 42 insertions(+), 39 deletions(-) diff --git a/controller/publish/iml.go b/controller/publish/iml.go index 6eb2b0b..7b00c8f 100644 --- a/controller/publish/iml.go +++ b/controller/publish/iml.go @@ -44,8 +44,9 @@ func (c *imlPublishController) ReleaseDo(ctx *gin.Context, serviceId string, inp c.releaseModule.Delete(ctx, serviceId, newReleaseId) return nil, err } - err = c.publishModule.ReleaseDo(ctx, serviceId, input) + err = c.publishModule.Publish(ctx, serviceId, apply.Id) if err != nil { + c.releaseModule.Delete(ctx, serviceId, newReleaseId) return nil, err } return apply, err diff --git a/module/dynamic-module/iml.go b/module/dynamic-module/iml.go index ab8c2a0..8a3d695 100644 --- a/module/dynamic-module/iml.go +++ b/module/dynamic-module/iml.go @@ -307,7 +307,7 @@ func (i *imlDynamicModule) PluginInfo(ctx context.Context, module string, cluste fields = append(fields, &driver.Field{ Name: "status", - Title: fmt.Sprintf("状态:"), + Title: fmt.Sprintf("状态"), Attr: "status", Enum: []string{ "已发布", diff --git a/module/my-team/iml.go b/module/my-team/iml.go index 9c9788e..b481235 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -265,6 +265,9 @@ func (m *imlTeamModule) Members(ctx context.Context, id string, keyword string) if err != nil { return nil, err } + if len(users) == 0 { + return make([]*team_dto.Member, 0), nil + } userIds := utils.SliceToSlice(users, func(s *user.User) string { return s.UID }) diff --git a/module/publish/iml.go b/module/publish/iml.go index 92ec131..548ed50 100644 --- a/module/publish/iml.go +++ b/module/publish/iml.go @@ -6,7 +6,6 @@ import ( "fmt" "time" - dto2 "github.com/eolinker/apipark/module/release/dto" "github.com/eolinker/go-common/store" "github.com/eolinker/apipark/service/service" @@ -50,35 +49,35 @@ type imlPublishModule struct { transaction store.ITransaction `autowired:""` } -func (m *imlPublishModule) ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error { - return m.transaction.Transaction(ctx, func(ctx context.Context) error { - newReleaseId, err := m.releaseModule.Create(ctx, serviceId, &dto2.CreateInput{ - Version: input.Version, - Remark: input.VersionRemark, - }) - if err != nil { - return err - } - apply, err := m.Apply(ctx, serviceId, &dto.ApplyInput{ - Release: newReleaseId, - Remark: input.PublishRemark, - }) - if err != nil { - return err - } - err = m.Accept(ctx, serviceId, apply.Id, "") - if err != nil { - m.releaseModule.Delete(ctx, serviceId, newReleaseId) - return err - } - err = m.Publish(ctx, serviceId, apply.Id) - if err != nil { - m.releaseModule.Delete(ctx, serviceId, newReleaseId) - } - - return nil - }) -} +//func (m *imlPublishModule) ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error { +// return m.transaction.Transaction(ctx, func(ctx context.Context) error { +// newReleaseId, err := m.releaseModule.Create(ctx, serviceId, &dto2.CreateInput{ +// Version: input.Version, +// Remark: input.VersionRemark, +// }) +// if err != nil { +// return err +// } +// apply, err := m.Apply(ctx, serviceId, &dto.ApplyInput{ +// Release: newReleaseId, +// Remark: input.PublishRemark, +// }) +// if err != nil { +// return err +// } +// err = m.Accept(ctx, serviceId, apply.Id, "") +// if err != nil { +// m.releaseModule.Delete(ctx, serviceId, newReleaseId) +// return err +// } +// err = m.Publish(ctx, serviceId, apply.Id) +// if err != nil { +// m.releaseModule.Delete(ctx, serviceId, newReleaseId) +// } +// +// return nil +// }) +//} func (m *imlPublishModule) initGateway(ctx context.Context, partitionId string, clientDriver gateway.IClientDriver) error { diff --git a/module/publish/module.go b/module/publish/module.go index a15c951..e524687 100644 --- a/module/publish/module.go +++ b/module/publish/module.go @@ -12,7 +12,7 @@ import ( type IPublishModule interface { CheckPublish(ctx context.Context, serviceId string, releaseId string) (*dto.DiffOut, error) - ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error + //ReleaseDo(ctx context.Context, serviceId string, input *dto.ApplyOnReleaseInput) error Apply(ctx context.Context, serviceId string, input *dto.ApplyInput) (*dto.Publish, error) Stop(ctx context.Context, serviceId string, id string) error diff --git a/module/service/iml.go b/module/service/iml.go index 45f584a..6a81d35 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -210,15 +210,15 @@ func (i *imlServiceModule) Search(ctx context.Context, teamID string, keyword st if err != nil { return nil, err } - serviceCountMap, err := i.serviceService.CountByGroup(ctx, "", map[string]interface{}{"service": serviceIds}, "service") - if err != nil { - return nil, err - } + //serviceCountMap, err := i.serviceService.CountByGroup(ctx, "", map[string]interface{}{"uuid": serviceIds}, "service") + //if err != nil { + // return nil, err + //} items := make([]*service_dto.ServiceItem, 0, len(list)) for _, model := range list { apiCount := apiCountMap[model.Id] - serviceCount := serviceCountMap[model.Id] + //serviceCount := serviceCountMap[model.Id] items = append(items, &service_dto.ServiceItem{ Id: model.Id, Name: model.Name, @@ -227,7 +227,7 @@ func (i *imlServiceModule) Search(ctx context.Context, teamID string, keyword st UpdateTime: auto.TimeLabel(model.UpdateTime), Team: auto.UUID(model.Team), ApiNum: apiCount, - CanDelete: apiCount == 0 && serviceCount == 0, + CanDelete: apiCount == 0, }) } return items, nil From 32f8c65658cf3a85cc1e15caa16903684f74f2c0 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 8 Aug 2024 16:06:09 +0800 Subject: [PATCH 16/19] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9D=83=E9=99=90?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/access/access.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/access/access.yaml b/resources/access/access.yaml index 5840608..53d0ee6 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -176,7 +176,7 @@ system: cname: 查看所有团队 value: 'view_all' apis: - - "GET:/api/v1/teams" + - "GET:/api/v1/manager/teams" - name: api market cname: API市场 value: 'api_market' From 103e342f3d26674dc1631382726c0614e6024916 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 8 Aug 2024 16:08:04 +0800 Subject: [PATCH 17/19] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=88=86=E7=B1=BB?= =?UTF-8?q?=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/access/access.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/access/access.yaml b/resources/access/access.yaml index 53d0ee6..ddac7ea 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -77,8 +77,8 @@ system: - name: view cname: '查看' value: 'view' - apis: - - "GET:/api/v1/catalogues" +# apis: +# - "GET:/api/v1/catalogues" - name: manager cname: '管理' value: 'manager' From 4df57fd1ede9583a2ed2d34da806a263d6a1aaee Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Fri, 9 Aug 2024 11:42:52 +0800 Subject: [PATCH 18/19] =?UTF-8?q?=E6=9D=83=E9=99=90=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- module/my-team/iml.go | 8 ++++---- module/service/dto/input.go | 1 + module/service/iml.go | 1 + resources/access/access.yaml | 1 - service/service/iml.go | 1 + service/service/model.go | 1 + 6 files changed, 8 insertions(+), 5 deletions(-) diff --git a/module/my-team/iml.go b/module/my-team/iml.go index b481235..84451b8 100644 --- a/module/my-team/iml.go +++ b/module/my-team/iml.go @@ -45,11 +45,11 @@ func (m *imlTeamModule) UpdateMemberRole(ctx context.Context, id string, input * return err } return m.transaction.Transaction(ctx, func(ctx context.Context) error { + err = m.roleMemberService.RemoveUserRole(ctx, role.TeamTarget(id), input.Users...) + if err != nil { + return err + } for _, roleId := range input.Roles { - err = m.roleMemberService.RemoveUserRole(ctx, roleId, input.Users...) - if err != nil { - return err - } for _, userId := range input.Users { err = m.roleMemberService.Add(ctx, &role.AddMember{ Role: roleId, diff --git a/module/service/dto/input.go b/module/service/dto/input.go index 3607450..c258de5 100644 --- a/module/service/dto/input.go +++ b/module/service/dto/input.go @@ -6,6 +6,7 @@ type CreateService struct { Prefix string `json:"prefix"` Description string `json:"description"` ServiceType string `json:"service_type"` + Logo string `json:"logo"` Catalogue string `json:"catalogue" aocheck:"catalogue"` AsApp *bool `json:"as_app"` AsServer *bool `json:"as_server"` diff --git a/module/service/iml.go b/module/service/iml.go index 6a81d35..bff74cd 100644 --- a/module/service/iml.go +++ b/module/service/iml.go @@ -246,6 +246,7 @@ func (i *imlServiceModule) Create(ctx context.Context, teamID string, input *ser ServiceType: service.ServiceType(input.ServiceType), Catalogue: input.Catalogue, Prefix: input.Prefix, + Logo: input.Logo, } if mo.ServiceType == service.PublicService && mo.Catalogue == "" { return nil, fmt.Errorf("catalogue can not be empty") diff --git a/resources/access/access.yaml b/resources/access/access.yaml index ddac7ea..fbed5b8 100644 --- a/resources/access/access.yaml +++ b/resources/access/access.yaml @@ -341,7 +341,6 @@ team: value: 'view' apis: - "GET:/api/v1/team/members" - - "GET:/api/v1/team/members/simple" - "GET:/api/v1/team/members/toadd" - name: manager cname: 管理 diff --git a/service/service/iml.go b/service/service/iml.go index 788f7c6..8171b93 100644 --- a/service/service/iml.go +++ b/service/service/iml.go @@ -126,6 +126,7 @@ func createEntityHandler(i *Create) *service.Service { CreateAt: now, UpdateAt: now, Description: i.Description, + Logo: i.Logo, Prefix: i.Prefix, Team: i.Team, ServiceType: i.ServiceType.Int(), diff --git a/service/service/model.go b/service/service/model.go index 406fc2e..d2ffc63 100644 --- a/service/service/model.go +++ b/service/service/model.go @@ -79,6 +79,7 @@ type Create struct { Description string Team string Prefix string + Logo string ServiceType ServiceType Catalogue string AsServer bool From 48550df382bd89f03e0b2055c8d0c60d2f8f9471 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 12 Aug 2024 09:31:59 +0800 Subject: [PATCH 19/19] =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E8=AF=A6=E6=83=85?= =?UTF-8?q?=E6=96=B0=E5=A2=9ELogo=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- module/catalogue/dto/output.go | 1 + module/catalogue/iml.go | 1 + 2 files changed, 2 insertions(+) diff --git a/module/catalogue/dto/output.go b/module/catalogue/dto/output.go index 1fbf528..309aa06 100644 --- a/module/catalogue/dto/output.go +++ b/module/catalogue/dto/output.go @@ -35,6 +35,7 @@ type ServiceBasic struct { Catalogue auto.Label `json:"catalogue" aolabel:"catalogue"` Version string `json:"version"` UpdateTime auto.TimeLabel `json:"update_time"` + Logo string `json:"logo"` } type ServiceApiBasic struct { diff --git a/module/catalogue/iml.go b/module/catalogue/iml.go index 07edba2..1adbd5b 100644 --- a/module/catalogue/iml.go +++ b/module/catalogue/iml.go @@ -273,6 +273,7 @@ func (i *imlCatalogueModule) ServiceDetail(ctx context.Context, sid string) (*ca Catalogue: auto.UUID(s.Catalogue), Version: r.Version, UpdateTime: auto.TimeLabel(r.CreateAt), + Logo: s.Logo, }, Apis: apis, }, nil