diff --git a/assembly/locator.go b/assembly/locator.go index c191ddb..c6c487d 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -43,26 +43,21 @@ func (l Locator) Config(cfg conf.Remote) Config { txManager := transaction.NewManager(l.db) accessListRep := repository.NewAccessList(l.db) applicationRep := repository.NewApplication(l.db) - domainRep := repository.NewDomain(l.db) appGroupRep := repository.NewAppGroup(l.db) tokenRep := repository.NewToken(l.db) secureService := secure.NewService(tokenRep, accessListRep) accessListService := service.NewAccessList(txManager, accessListRep, applicationRep) - applicationService := service.NewApplication(txManager, applicationRep, domainRep, appGroupRep, tokenRep) - domainService := service.NewDomain(domainRep) - serviceService := service.NewService(domainRep, appGroupRep) + applicationService := service.NewApplication(txManager, applicationRep, appGroupRep, tokenRep) jwtService := service.NewTokenSource() tokenService := service.NewToken(jwtService, applicationService, txManager, - applicationRep, domainRep, appGroupRep, tokenRep, + applicationRep, appGroupRep, tokenRep, ) secureController := controller.NewSecure(secureService) accessListController := controller.NewAccessList(accessListService) applicationController := controller.NewApplication(applicationService) - domainController := controller.NewDomain(domainService) - serviceController := controller.NewService(serviceService) tokenController := controller.NewToken(tokenService) appGroupService := service.NewAppGroup(appGroupRep) @@ -70,8 +65,6 @@ func (l Locator) Config(cfg conf.Remote) Config { c := routes.Controllers{ Secure: secureController, AccessList: accessListController, - Domain: domainController, - Service: serviceController, Application: applicationController, Token: tokenController, AppGroup: appGroupController, diff --git a/controller/application.go b/controller/application.go index d00b294..32c804b 100644 --- a/controller/application.go +++ b/controller/application.go @@ -13,17 +13,16 @@ import ( //nolint:interfacebloat type ApplicationService interface { - GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) + GetById(ctx context.Context, appId int) (*domain.Application, error) GetByToken(ctx context.Context, token string) (*domain.GetApplicationByTokenResponse, error) - GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) - GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) - SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) - CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) + GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error) + GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error) + CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) Delete(ctx context.Context, idList []int) (int, error) NextId(ctx context.Context) (int, error) GetAll(ctx context.Context) ([]domain.Application, error) - Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) - Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) + Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) + Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) } type Application struct { @@ -44,12 +43,12 @@ func NewApplication(service ApplicationService) Application { // @Accept json // @Produce json // @Param body body domain.Identity true "Идентификатор приложения" -// @Success 200 {object} domain.ApplicationWithTokens +// @Success 200 {object} domain.Application // @Failure 400 {object} apierrors.Error // @Failure 404 {object} apierrors.Error // @Failure 500 {object} apierrors.Error // @Router /application/get_application_by_id [POST] -func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) { +func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.Application, error) { result, err := c.service.GetById(ctx, req.Id) switch { case errors.Is(err, domain.ErrApplicationNotFound): @@ -100,44 +99,31 @@ func (c Application) GetByToken(ctx context.Context, req domain.GetApplicationBy // // @Tags application // @Summary Получить список приложений -// @Description Возвращает массив приложений с токенами по их идентификаторам +// @Description Возвращает массив приложений их идентификаторам // @Accept json // @Produce json // @Param body body []integer false "Массив идентификаторов приложений" -// @Success 200 {array} domain.ApplicationWithTokens +// @Success 200 {array} domain.Application // @Failure 500 {object} apierrors.Error // @Router /application/get_applications [POST] -func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) { +func (c Application) GetByIdList(ctx context.Context, req []int) ([]domain.Application, error) { return c.service.GetByIdList(ctx, req) } -// GetByServiceId godoc +// GetByAppGroup godoc // // @Tags application -// @Summary Получить список приложений по идентификатору сервиса -// @Description Возвращает список приложений по запрошенному идентификатору сервиса +// @Summary Получить список приложений по идентификатору группы +// @Description Возвращает список приложений по идентификатору группы // @Accept json // @Produce json -// @Param body body domain.Identity true "Идентификатор сервиса" -// @Success 200 {array} domain.ApplicationWithTokens +// @Param body body domain.Identity true "Тело запроса" +// @Success 200 {array} domain.Application +// @Failure 400 {object} apierrors.Error // @Failure 500 {object} apierrors.Error -// @Router /application/get_applications_by_service_id [POST] -func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) { - return c.service.GetByServiceId(ctx, req.Id) -} - -// GetSystemTree godoc -// -// @Tags application -// @Summary Метод получения системного дерева -// @Description Возвращает описание взаимосвязей сервисов и приложений -// @Accept json -// @Produce json -// @Success 200 {array} domain.DomainWithService -// @Failure 500 {object} apierrors.Error -// @Router /application/get_system_tree [POST] -func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) { - return c.service.SystemTree(ctx, domain.DefaultSystemId) +// @Router /application/get_by_app_group [POST] +func (c Application) GetByAppGroup(ctx context.Context, req domain.Identity) ([]domain.Application, error) { + return c.service.GetByAppGroup(ctx, req.Id) } // CreateUpdate godoc @@ -148,19 +134,19 @@ func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithSer // @Accept json // @Produce json // @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens +// @Success 200 {object} domain.Application // @Failure 400 {object} apierrors.Error // @Failure 404 {object} apierrors.Error // @Failure 409 {object} apierrors.Error // @Failure 500 {object} apierrors.Error // @Router /application/create_update_application [POST] -func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { +func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) { result, err := c.service.CreateUpdate(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupNotFound): return nil, apierrors.NewBusinessError( domain.ErrCodeAppGroupNotFound, - fmt.Sprintf("service with id %d not found", req.ServiceId), + fmt.Sprintf("service with id %d not found", req.ApplicationGroupId), err, ) case errors.Is(err, domain.ErrApplicationDuplicateName): @@ -248,12 +234,12 @@ func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { // @Accept json // @Produce json // @Param body body domain.CreateApplicationRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens +// @Success 200 {object} domain.Application // @Failure 400 {object} apierrors.Error // @Failure 409 {object} apierrors.Error // @Failure 500 {object} apierrors.Error // @Router /application/create_application [POST] -func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { +func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) { result, err := c.service.Create(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupNotFound): @@ -289,13 +275,13 @@ func (c Application) Create(ctx context.Context, req domain.CreateApplicationReq // @Accept json // @Produce json // @Param body body domain.UpdateApplicationRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens +// @Success 200 {object} domain.Application // @Failure 400 {object} apierrors.Error // @Failure 404 {object} apierrors.Error // @Failure 409 {object} apierrors.Error // @Failure 500 {object} apierrors.Error // @Router /application/update_application [POST] -func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { +func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) { result, err := c.service.Update(ctx, req) switch { case errors.Is(err, domain.ErrApplicationNotFound): diff --git a/controller/domain.go b/controller/domain.go deleted file mode 100644 index 7e40923..0000000 --- a/controller/domain.go +++ /dev/null @@ -1,142 +0,0 @@ -package controller - -import ( - "context" - "fmt" - - "isp-system-service/domain" - - "github.com/pkg/errors" - "github.com/txix-open/isp-kit/grpc/apierrors" - "google.golang.org/grpc/codes" -) - -type DomainService interface { - GetById(ctx context.Context, id int) (*domain.Domain, error) - GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) - CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) - Delete(ctx context.Context, idList []int) (int, error) -} - -type Domain struct { - service DomainService -} - -func NewDomain(service DomainService) Domain { - return Domain{ - service: service, - } -} - -// GetById godoc -// -// @Tags domain -// @Summary Получить домен по идентификатору -// @Description Возвращает описание домена по его идентификатору -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор домена" -// @Success 200 {object} domain.Domain -// @Failure 404 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /domain/get_domain_by_id [POST] -func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) { - result, err := c.service.GetById(ctx, req.Id) - switch { - case errors.Is(err, domain.ErrDomainNotFound): - return nil, apierrors.New( - codes.NotFound, - domain.ErrCodeDomainNotFound, - fmt.Sprintf("domain with id %d not found", req.Id), - err, - ) - case err != nil: - return nil, err - default: - return result, nil - } -} - -// GetBySystemId godoc -// -// @Tags domain -// @Summary Получить домены по идентификатору системы -// @Description Возвращает список доменов по системному идентификатору -// @Accept json -// @Produce json -// @Param body body integer false "Идентификатор системы" -// @Success 200 {array} domain.Domain -// @Failure 500 {object} apierrors.Error -// @Router /domain/get_domains_by_system_id [POST] -func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) { - return c.service.GetBySystemId(ctx, domain.DefaultSystemId) -} - -// CreateUpdate godoc -// -// @Tags domain -// @Summary Создать/обновить домен -// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу -// @Accept json -// @Produce json -// @Param body body domain.DomainCreateUpdateRequest true "Объект домена" -// @Success 200 {object} domain.Domain -// @Failure 500 {object} apierrors.Error -// @Router /domain/create_update_domain [POST] -func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) { - result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId) - switch { - case errors.Is(err, domain.ErrSystemNotFound): - return nil, apierrors.NewBusinessError( - domain.ErrCodeSystemNotFound, - fmt.Sprintf("system with id %d not found", domain.DefaultSystemId), - err, - ) - case errors.Is(err, domain.ErrDomainNotFound): - return nil, apierrors.New( - codes.NotFound, - domain.ErrCodeDomainNotFound, - fmt.Sprintf("domain with id %d not found", req.Id), - err, - ) - case errors.Is(err, domain.ErrDomainDuplicateName): - return nil, apierrors.New( - codes.AlreadyExists, - domain.ErrCodeDomainDuplicateName, - fmt.Sprintf("domain with name %s already exists", req.Name), - err, - ) - case err != nil: - return nil, err - default: - return result, nil - } -} - -// Delete godoc -// -// @Tags domain -// @Summary Удаление доменов -// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов доменов" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /domain/delete_domains [POST] -func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { - if len(req) == 0 { - return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest, - "At least one id are required", errors.New("invalid id count")) - } - - result, err := c.service.Delete(ctx, req) - if err != nil { - return nil, err - } - - return &domain.DeleteResponse{ - Deleted: result, - }, nil -} diff --git a/controller/service.go b/controller/service.go deleted file mode 100644 index f081369..0000000 --- a/controller/service.go +++ /dev/null @@ -1,161 +0,0 @@ -package controller - -import ( - "context" - "fmt" - - "isp-system-service/domain" - - "github.com/pkg/errors" - "github.com/txix-open/isp-kit/grpc/apierrors" - "google.golang.org/grpc/codes" -) - -type ServiceService interface { - GetById(ctx context.Context, id int) (*domain.Service, error) - GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) - GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) - CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) - Delete(ctx context.Context, idList []int) (int, error) -} - -type Service struct { - service ServiceService -} - -func NewService(service ServiceService) Service { - return Service{ - service: service, - } -} - -// GetById godoc -// -// @Tags service -// @Summary Получить сервис по идентификатору -// @Description Возвращает описание сервиса по его идентификатору -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор сервиса" -// @Success 200 {object} domain.Service -// @Failure 404 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /service/get_service_by_id [POST] -func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) { - result, err := c.service.GetById(ctx, req.Id) - switch { - case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, apierrors.New( - codes.NotFound, - domain.ErrCodeAppGroupNotFound, - fmt.Sprintf("service with id %d not found", req.Id), - err, - ) - case err != nil: - return nil, err - default: - return result, nil - } -} - -// Get godoc -// -// @Tags service -// @Summary Получить список сервисов -// @Description Возвращает список сервисов по их идентификаторам -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов сервисов" -// @Success 200 {array} domain.Service -// @Failure 500 {object} apierrors.Error -// @Router /service/get_service [POST] -func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) { - return c.service.GetByIdList(ctx, req) -} - -// GetByDomainId godoc -// -// @Tags service -// @Summary Получить список сервисов по идентификатору домена -// @Description Возвращает список сервисов по идентификатору домена -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор домена" -// @Success 200 {array} domain.Service -// @Failure 500 {object} apierrors.Error -// @Router /service/get_services_by_domain_id [POST] -func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) { - return c.service.GetByDomainId(ctx, req.Id) -} - -// CreateUpdate godoc -// -// @Tags service -// @Summary Создать/обновить сервис -// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу -// @Accept json -// @Produce json -// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса" -// @Success 200 {object} domain.Service -// @Failure 400 {object} apierrors.Error -// @Failure 404 {object} apierrors.Error -// @Failure 409 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /service/create_update_service [POST] -func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { - result, err := c.service.CreateUpdate(ctx, req) - switch { - case errors.Is(err, domain.ErrDomainNotFound): - return nil, apierrors.NewBusinessError( - domain.ErrCodeDomainNotFound, - fmt.Sprintf("domain with id %d not found", req.DomainId), - err, - ) - case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, apierrors.New( - codes.NotFound, - domain.ErrCodeAppGroupNotFound, - fmt.Sprintf("service with id %d not found", req.Id), - err, - ) - case errors.Is(err, domain.ErrAppGroupDuplicateName): - return nil, apierrors.New( - codes.AlreadyExists, - domain.ErrCodeAppGroupNotFound, - fmt.Sprintf("service with name %s already exists", req.Name), - err, - ) - case err != nil: - return nil, err - default: - return result, nil - } -} - -// Delete godoc -// -// @Tags service -// @Summary Удалить сервисы -// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов -// @Accept json -// @Produce json -// @Param body body []integer true "Массив идентификаторов сервисов" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /service/delete_service [POST] -func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { - if len(req) == 0 { - return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest, - "At least one id are required", errors.New("invalid id count")) - } - - result, err := c.service.Delete(ctx, req) - if err != nil { - return nil, err - } - - return &domain.DeleteResponse{ - Deleted: result, - }, nil -} diff --git a/controller/token.go b/controller/token.go index 63f65fc..c8c36f6 100644 --- a/controller/token.go +++ b/controller/token.go @@ -71,13 +71,6 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma fmt.Sprintf("service for app_id id %d not found", req.AppId), err, ) - case errors.Is(err, domain.ErrDomainNotFound): - return nil, apierrors.New( - codes.NotFound, - domain.ErrCodeDomainNotFound, - fmt.Sprintf("domain for app_id id %d not found", req.AppId), - err, - ) case err != nil: return nil, err default: diff --git a/docs/swagger.json b/docs/swagger.json index 1e50ecd..1949d58 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -38,9 +38,7 @@ "responses": { "200": { "description": "OK", - "schema": { - "type": "object" - } + "schema": {} }, "404": { "description": "Not Found", @@ -83,9 +81,7 @@ "responses": { "200": { "description": "OK", - "schema": { - "type": "object" - } + "schema": {} }, "404": { "description": "Not Found", @@ -271,7 +267,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } }, "400": { @@ -323,7 +319,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } }, "400": { @@ -461,7 +457,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } }, "400": { @@ -539,7 +535,7 @@ }, "/application/get_applications": { "post": { - "description": "Возвращает массив приложений с токенами по их идентификаторам", + "description": "Возвращает массив приложений их идентификаторам", "consumes": [ "application/json" ], @@ -569,7 +565,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } } }, @@ -582,9 +578,9 @@ } } }, - "/application/get_applications_by_service_id": { + "/application/get_by_app_group": { "post": { - "description": "Возвращает список приложений по запрошенному идентификатору сервиса", + "description": "Возвращает список приложений по идентификатору группы", "consumes": [ "application/json" ], @@ -594,10 +590,10 @@ "tags": [ "application" ], - "summary": "Получить список приложений по идентификатору сервиса", + "summary": "Получить список приложений по идентификатору группы", "parameters": [ { - "description": "Идентификатор сервиса", + "description": "Тело запроса", "name": "body", "in": "body", "required": true, @@ -612,41 +608,15 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } } }, - "500": { - "description": "Internal Server Error", + "400": { + "description": "Bad Request", "schema": { "$ref": "#/definitions/apierrors.Error" } - } - } - } - }, - "/application/get_system_tree": { - "post": { - "description": "Возвращает описание взаимосвязей сервисов и приложений", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "application" - ], - "summary": "Метод получения системного дерева", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.DomainWithService" - } - } }, "500": { "description": "Internal Server Error", @@ -714,7 +684,7 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/domain.ApplicationWithTokens" + "$ref": "#/definitions/domain.Application" } }, "400": { @@ -981,182 +951,6 @@ } } }, - "/domain/create_update_domain": { - "post": { - "description": "Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "domain" - ], - "summary": "Создать/обновить домен", - "parameters": [ - { - "description": "Объект домена", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.DomainCreateUpdateRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Domain" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/domain/delete_domains": { - "post": { - "description": "Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "domain" - ], - "summary": "Удаление доменов", - "parameters": [ - { - "description": "Массив идентификаторов доменов", - "name": "body", - "in": "body", - "schema": { - "type": "array", - "items": { - "type": "integer" - } - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.DeleteResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/domain/get_domain_by_id": { - "post": { - "description": "Возвращает описание домена по его идентификатору", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "domain" - ], - "summary": "Получить домен по идентификатору", - "parameters": [ - { - "description": "Идентификатор домена", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.Identity" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Domain" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/domain/get_domains_by_system_id": { - "post": { - "description": "Возвращает список доменов по системному идентификатору", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "domain" - ], - "summary": "Получить домены по идентификатору системы", - "parameters": [ - { - "description": "Идентификатор системы", - "name": "body", - "in": "body", - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.Domain" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, "/secure/authenticate": { "post": { "description": "Проверяет наличие токена в системе,", @@ -1243,247 +1037,6 @@ } } }, - "/service/create_update_service": { - "post": { - "description": "Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "service" - ], - "summary": "Создать/обновить сервис", - "parameters": [ - { - "description": "Объект сервиса", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.ServiceCreateUpdateRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Service" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/service/delete_service": { - "post": { - "description": "Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "service" - ], - "summary": "Удалить сервисы", - "parameters": [ - { - "description": "Массив идентификаторов сервисов", - "name": "body", - "in": "body", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "integer" - } - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.DeleteResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/service/get_service": { - "post": { - "description": "Возвращает список сервисов по их идентификаторам", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "service" - ], - "summary": "Получить список сервисов", - "parameters": [ - { - "description": "Массив идентификаторов сервисов", - "name": "body", - "in": "body", - "schema": { - "type": "array", - "items": { - "type": "integer" - } - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.Service" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/service/get_service_by_id": { - "post": { - "description": "Возвращает описание сервиса по его идентификатору", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "service" - ], - "summary": "Получить сервис по идентификатору", - "parameters": [ - { - "description": "Идентификатор сервиса", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.Identity" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/domain.Service" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, - "/service/get_services_by_domain_id": { - "post": { - "description": "Возвращает список сервисов по идентификатору домена", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "service" - ], - "summary": "Получить список сервисов по идентификатору домена", - "parameters": [ - { - "description": "Идентификатор домена", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.Identity" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.Service" - } - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/apierrors.Error" - } - } - } - } - }, "/token/create_token": { "post": { "description": "Создает токен и привязывает его к приложению", @@ -1774,6 +1327,9 @@ "domain.Application": { "type": "object", "properties": { + "applicationGroupId": { + "type": "integer" + }, "createdAt": { "type": "string" }, @@ -1786,9 +1342,6 @@ "name": { "type": "string" }, - "serviceId": { - "type": "integer" - }, "type": { "type": "string" }, @@ -1800,11 +1353,14 @@ "domain.ApplicationCreateUpdateRequest": { "type": "object", "required": [ + "applicationGroupId", "name", - "serviceId", "type" ], "properties": { + "applicationGroupId": { + "type": "integer" + }, "description": { "type": "string" }, @@ -1814,9 +1370,6 @@ "name": { "type": "string" }, - "serviceId": { - "type": "integer" - }, "type": { "type": "string", "enum": [ @@ -1826,29 +1379,6 @@ } } }, - "domain.ApplicationSimple": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "tokens": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.Token" - } - }, - "type": { - "type": "string" - } - } - }, "domain.ApplicationWithTokens": { "type": "object", "properties": { @@ -1871,15 +1401,6 @@ }, "applicationId": { "type": "integer" - }, - "domainId": { - "type": "integer" - }, - "serviceId": { - "type": "integer" - }, - "systemId": { - "type": "integer" } } }, @@ -1986,66 +1507,6 @@ } } }, - "domain.Domain": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "systemId": { - "type": "integer" - }, - "updatedAt": { - "type": "string" - } - } - }, - "domain.DomainCreateUpdateRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "domain.DomainWithService": { - "type": "object", - "properties": { - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "services": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.ServiceWithApps" - } - } - } - }, "domain.GetApplicationByTokenRequest": { "type": "object", "required": [ @@ -2122,70 +1583,6 @@ } } }, - "domain.Service": { - "type": "object", - "properties": { - "createdAt": { - "type": "string" - }, - "description": { - "type": "string" - }, - "domainId": { - "type": "integer" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - }, - "updatedAt": { - "type": "string" - } - } - }, - "domain.ServiceCreateUpdateRequest": { - "type": "object", - "required": [ - "domainId", - "name" - ], - "properties": { - "description": { - "type": "string" - }, - "domainId": { - "type": "integer" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "domain.ServiceWithApps": { - "type": "object", - "properties": { - "apps": { - "type": "array", - "items": { - "$ref": "#/definitions/domain.ApplicationSimple" - } - }, - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, "domain.Token": { "type": "object", "properties": { diff --git a/domain/application.go b/domain/application.go index 9ced13a..421225a 100644 --- a/domain/application.go +++ b/domain/application.go @@ -10,21 +10,21 @@ const ( ) type Application struct { - Id int - Name string - Description string - ServiceId int - Type string - CreatedAt time.Time - UpdatedAt time.Time + Id int + Name string + Description string + ApplicationGroupId int + Type string + CreatedAt time.Time + UpdatedAt time.Time } type ApplicationCreateUpdateRequest struct { - Id int - Name string `validate:"required"` - Description string - ServiceId int `validate:"required"` - Type string `validate:"required,oneof=SYSTEM MOBILE"` + Id int + Name string `validate:"required"` + Description string + ApplicationGroupId int `validate:"required"` + Type string `validate:"required,oneof=SYSTEM MOBILE"` } type ApplicationWithTokens struct { @@ -32,14 +32,6 @@ type ApplicationWithTokens struct { Tokens []Token } -type ApplicationSimple struct { - Id int - Name string - Description string - Type string - Tokens []Token -} - type CreateApplicationRequest struct { Id int `validate:"required"` Name string `validate:"required"` diff --git a/domain/domain.go b/domain/domain.go deleted file mode 100644 index 97138de..0000000 --- a/domain/domain.go +++ /dev/null @@ -1,27 +0,0 @@ -package domain - -import ( - "time" -) - -type DomainCreateUpdateRequest struct { - Id int - Name string `validate:"required"` - Description string -} - -type Domain struct { - Id int - Name string - Description string - SystemId int - CreatedAt time.Time - UpdatedAt time.Time -} - -type DomainWithService struct { - Id int - Name string - Description string - Services []*ServiceWithApps -} diff --git a/domain/error.go b/domain/error.go index 5cf7fc9..a135a7c 100644 --- a/domain/error.go +++ b/domain/error.go @@ -20,14 +20,9 @@ const ( ) var ( - ErrDomainNotFound = errors.New("domain not found") - ErrDomainDuplicateName = errors.New("domain name already exist") - ErrAppGroupNotFound = errors.New("application group not found") ErrAppGroupDuplicateName = errors.New("application group name already exist") - ErrSystemNotFound = errors.New("system not found") - ErrApplicationNotFound = errors.New("application not found") ErrApplicationDuplicateName = errors.New("application name already exist") ErrApplicationDuplicateId = errors.New("application id already exist") diff --git a/domain/secure.go b/domain/secure.go index 18d1b47..7526700 100644 --- a/domain/secure.go +++ b/domain/secure.go @@ -12,9 +12,6 @@ type AuthenticateResponse struct { type AuthData struct { AppName string - SystemId int - DomainId int - ServiceId int ApplicationId int } diff --git a/domain/service.go b/domain/service.go deleted file mode 100644 index 63ed02a..0000000 --- a/domain/service.go +++ /dev/null @@ -1,28 +0,0 @@ -package domain - -import ( - "time" -) - -type Service struct { - Id int - Name string - Description string - DomainId int - CreatedAt time.Time - UpdatedAt time.Time -} - -type ServiceCreateUpdateRequest struct { - Id int - Name string `validate:"required"` - Description string - DomainId int `validate:"required"` -} - -type ServiceWithApps struct { - Id int - Name string - Description string - Apps []*ApplicationSimple -} diff --git a/domain/system.go b/domain/system.go deleted file mode 100644 index 7fa0aea..0000000 --- a/domain/system.go +++ /dev/null @@ -1,5 +0,0 @@ -package domain - -const ( - DefaultSystemId = 1 -) diff --git a/entity/app_group.go b/entity/app_group.go index 9638e77..fc3dc1a 100644 --- a/entity/app_group.go +++ b/entity/app_group.go @@ -9,7 +9,6 @@ type AppGroup struct { Id int Name string Description sql.NullString - DomainId int CreatedAt time.Time UpdatedAt time.Time } diff --git a/entity/domain.go b/entity/domain.go deleted file mode 100644 index 08dc9e8..0000000 --- a/entity/domain.go +++ /dev/null @@ -1,14 +0,0 @@ -package entity - -import ( - "time" -) - -type Domain struct { - Id int - Name string - Description *string - SystemId int - CreatedAt time.Time - UpdatedAt time.Time -} diff --git a/entity/token.go b/entity/token.go index 8c22b67..360ccac 100644 --- a/entity/token.go +++ b/entity/token.go @@ -13,8 +13,6 @@ type Token struct { type AuthData struct { AppName string - SystemId int - DomainId int ApplicationGroupId int AppId int ExpireTime int diff --git a/main.go b/main.go index 358d4e1..22648f7 100644 --- a/main.go +++ b/main.go @@ -23,8 +23,7 @@ var ( // @host localhost:9000 // @BasePath /api/system -//go:generate swag init --parseDependency -//go:generate rm -f docs/swagger.yaml docs/docs.go +//go:generate swag init -pd -ot json -eot json func main() { boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport) app := boot.App diff --git a/migrations/20260824081843_drop_domain_and_system_table.sql b/migrations/20260824081843_drop_domain_and_system_table.sql new file mode 100644 index 0000000..7371ac7 --- /dev/null +++ b/migrations/20260824081843_drop_domain_and_system_table.sql @@ -0,0 +1,24 @@ +-- +goose Up +ALTER TABLE application_group + DROP CONSTRAINT fk_domain_id__domain_id; +ALTER TABLE application_group + DROP CONSTRAINT uq_name_domain_name; + +ALTER TABLE application_group + DROP COLUMN domain_id; + +ALTER TABLE application_group + ADD CONSTRAINT uq_application_group_name UNIQUE ("name"); + +ALTER TABLE domain + DROP CONSTRAINT fk_system_id__system_id; + +ALTER TABLE domain + DROP CONSTRAINT uq_name_system_id; + +DROP TABLE domain; +DROP TABLE system; + +-- +goose Down + +-- irreversible migration \ No newline at end of file diff --git a/repository/app_group.go b/repository/app_group.go index 1248ce1..657b157 100644 --- a/repository/app_group.go +++ b/repository/app_group.go @@ -15,6 +15,10 @@ import ( "github.com/txix-open/isp-kit/metrics/sql_metrics" ) +const ( + applicationGroupUniqueNameConstraint = "uq_application_group_name" +) + type AppGroup struct { db db.DB } @@ -29,7 +33,7 @@ func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupById") q := ` - SELECT id, name, description, domain_id, created_at, updated_at + SELECT id, name, description, created_at, updated_at FROM application_group WHERE id = $1 ` @@ -49,7 +53,7 @@ func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]enti ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByIdList") q, arg, err := query.New(). - Select("id", "name", "description", "domain_id", "created_at", "updated_at"). + Select("id", "name", "description", "created_at", "updated_at"). From("application_group"). Where(squirrel.Eq{"id": idList}). OrderBy("created_at DESC"). @@ -67,38 +71,16 @@ func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]enti return result, nil } -func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByDomainId") - - q, arg, err := query.New(). - Select("id", "name", "description", "domain_id", "created_at", "updated_at"). - From("application_group"). - Where(squirrel.Eq{"domain_id": domainIdList}). - OrderBy("created_at DESC"). - ToSql() - if err != nil { - return nil, errors.WithMessage(err, "build query") - } - - result := make([]entity.AppGroup, 0) - err = r.db.Select(ctx, &result, q, arg...) - if err != nil { - return nil, errors.WithMessagef(err, "exec query %s", q) - } - - return result, nil -} - -func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByNameAndDomainId") +func (r AppGroup) GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByName") q := ` - SELECT id, name, description, domain_id, created_at, updated_at + SELECT id, name, description, created_at, updated_at FROM application_group - WHERE name = $1 AND domain_id = $2 + WHERE name = $1 ` result := entity.AppGroup{} - err := r.db.SelectRow(ctx, &result, q, name, domainId) + err := r.db.SelectRow(ctx, &result, q, name) switch { case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrAppGroupNotFound @@ -109,18 +91,18 @@ func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, } } -func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) { +func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error) { ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.CreateAppGroup") q := ` INSERT INTO application_group - (name, description, domain_id) - VALUES ($1, $2, $3) - ON CONFLICT (name, domain_id) DO NOTHING - RETURNING id, name, description, domain_id, created_at, updated_at + (name, description) + VALUES ($1, $2) + ON CONFLICT (name) DO NOTHING + RETURNING id, name, description, created_at, updated_at ` result := entity.AppGroup{} - err := r.db.SelectRow(ctx, &result, q, name, desc, domainId) + err := r.db.SelectRow(ctx, &result, q, name, desc) switch { case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrAppGroupDuplicateName @@ -138,7 +120,7 @@ func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, descr UPDATE application_group SET name = $1, description = $2 WHERE id = $3 - RETURNING id, name, description, domain_id, created_at, updated_at + RETURNING id, name, description, created_at, updated_at ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, description, id) @@ -183,7 +165,7 @@ func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAllAppGroups") q, arg, err := query.New(). - Select("id", "name", "description", "domain_id", "created_at", "updated_at"). + Select("id", "name", "description", "created_at", "updated_at"). From("application_group"). OrderBy("created_at DESC"). ToSql() diff --git a/repository/application.go b/repository/application.go index dd3c4b2..5aac24a 100644 --- a/repository/application.go +++ b/repository/application.go @@ -15,6 +15,12 @@ import ( "github.com/txix-open/isp-kit/metrics/sql_metrics" ) +const ( + applicationPkConstraintName = "application_pkey" + applicationUniqueNameConstraintName = "uq_name_application_group_id" + applicationFkAppGroupConstraintName = "fk_application_group_id" +) + type Application struct { db db.DB } @@ -89,26 +95,6 @@ func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGrou return result, nil } -func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByNameAndAppGroupId") - - q := ` - SELECT id, name, description, application_group_id, type, created_at, updated_at - FROM application - WHERE name = $1 AND application_group_id = $2 - ` - result := entity.Application{} - err := r.db.SelectRow(ctx, &result, q, name, serviceId) - switch { - case errors.Is(err, sql.ErrNoRows): - return nil, nil // nolint:nilnil - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil - } -} - func (r Application) CreateApplication( ctx context.Context, id int, diff --git a/repository/consts.go b/repository/consts.go deleted file mode 100644 index fec1087..0000000 --- a/repository/consts.go +++ /dev/null @@ -1,9 +0,0 @@ -package repository - -const ( - applicationPkConstraintName = "application_pkey" - applicationUniqueNameConstraintName = "uq_name_application_group_id" - applicationFkAppGroupConstraintName = "fk_application_group_id" - - applicationGroupUniqueNameConstraint = "uq_name_domain_name" -) diff --git a/repository/domain.go b/repository/domain.go deleted file mode 100644 index 860f49a..0000000 --- a/repository/domain.go +++ /dev/null @@ -1,166 +0,0 @@ -package repository - -import ( - "context" - "database/sql" - - "isp-system-service/domain" - "isp-system-service/entity" - - "github.com/Masterminds/squirrel" - "github.com/pkg/errors" - "github.com/txix-open/isp-kit/db" - "github.com/txix-open/isp-kit/db/query" - "github.com/txix-open/isp-kit/metrics/sql_metrics" -) - -type Domain struct { - db db.DB -} - -func NewDomain(db db.DB) Domain { - return Domain{ - db: db, - } -} - -func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainById") - - q := ` - SELECT id, name, description, system_id, created_at, updated_at - FROM domain - WHERE id = $1 - ` - result := entity.Domain{} - err := r.db.SelectRow(ctx, &result, q, id) - switch { - case errors.Is(err, sql.ErrNoRows): - return nil, domain.ErrDomainNotFound - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil - } -} - -func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByIdList") - - q, args, err := query.New(). - Select("id", "name", "description", "system_id", "created_at", "updated_at"). - From("domain"). - Where(squirrel.Eq{"id": idList}). - ToSql() - if err != nil { - return nil, errors.WithMessage(err, "build query") - } - - result := make([]entity.Domain, 0) - err = r.db.Select(ctx, &result, q, args...) - if err != nil { - return nil, errors.WithMessage(err, "select db") - } - - return result, nil -} - -func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainBySystemId") - - q := ` - SELECT id, name, description, system_id, created_at, updated_at - FROM domain - WHERE system_id = $1 - ORDER BY created_at DESC - ` - result := make([]entity.Domain, 0) - err := r.db.Select(ctx, &result, q, systemId) - if err != nil { - return nil, errors.WithMessagef(err, "exec query %s", q) - } - - return result, nil -} - -func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByNameAndSystemId") - - q := ` - SELECT id, name, description, system_id, created_at, updated_at - FROM domain - WHERE name = $1 AND system_id = $2 - ` - result := entity.Domain{} - err := r.db.SelectRow(ctx, &result, q, name, systemId) - switch { - case errors.Is(err, sql.ErrNoRows): - return nil, domain.ErrDomainNotFound - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil - } -} - -func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.CreateDomain") - - q := ` - INSERT INTO domain - (name, description, system_id) - VALUES ($1, $2, $3) - RETURNING id, name, description, system_id, created_at, updated_at - ` - result := entity.Domain{} - err := r.db.SelectRow(ctx, &result, q, name, desc, systemId) - if err != nil { - return nil, errors.WithMessagef(err, "exec query %s", q) - } - return &result, nil -} - -func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.UpdateDomain") - - q := ` - UPDATE domain - SET name = $1, description = $2 - WHERE id = $3 - RETURNING id, name, description, system_id, created_at, updated_at -` - result := entity.Domain{} - err := r.db.SelectRow(ctx, &result, q, name, description, id) - switch { - case errors.Is(err, sql.ErrNoRows): - return nil, domain.ErrDomainNotFound - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil - } -} - -func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) { - ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.DeleteDomain") - - q, args, err := query.New(). - Delete("domain"). - Where(squirrel.Eq{"id": idList}). - ToSql() - if err != nil { - return 0, errors.WithMessagef(err, "build query") - } - - result, err := r.db.Exec(ctx, q, args...) - if err != nil { - return 0, errors.WithMessagef(err, "exec query %s", q) - } - - rowsAffected, err := result.RowsAffected() - if err != nil { - return 0, errors.WithMessagef(err, "get rows affected") - } - - return int(rowsAffected), nil -} diff --git a/repository/token.go b/repository/token.go index 413d594..c83e6bd 100644 --- a/repository/token.go +++ b/repository/token.go @@ -112,14 +112,12 @@ func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthD ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AuthDataByToken") q := ` -SELECT system_id, domain_id, application_group_id, app_id, application.name AS app_name , token.expire_time, token.created_at +SELECT application_group_id, app_id, application.name AS app_name , token.expire_time, token.created_at FROM token - LEFT JOIN application - ON token.app_id = application.id - LEFT JOIN application_group - ON application.application_group_id = application_group.id - LEFT JOIN domain - ON application_group.domain_id = domain.id +LEFT JOIN application + ON token.app_id = application.id +LEFT JOIN application_group + ON application.application_group_id = application_group.id WHERE token = $1 ` result := entity.AuthData{} diff --git a/routes/routes.go b/routes/routes.go index c945d1c..4217a88 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -12,8 +12,6 @@ import ( type Controllers struct { AccessList controller.AccessList - Domain controller.Domain - Service controller.Service Application controller.Application AppGroup controller.AppGroup Token controller.Token @@ -33,11 +31,9 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux { } func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { - return concatCluster( + return concatEndpoints( secureCluster(c), accessListCluster(c), - domainCluster(c), - serviceCluster(c), applicationCluster(c), tokenCluster(c), applicationGroupCluster(c), @@ -95,62 +91,6 @@ func accessListCluster(c Controllers) []cluster.EndpointDescriptor { } } -func domainCluster(c Controllers) []cluster.EndpointDescriptor { - return []cluster.EndpointDescriptor{ - { - Path: "system/domain/get_domains_by_system_id", - Inner: true, - Handler: c.Domain.GetBySystemId, - }, - { - Path: "system/domain/create_update_domain", - Inner: true, - Handler: c.Domain.CreateUpdate, - }, - { - Path: "system/domain/get_domain_by_id", - Inner: true, - Handler: c.Domain.GetById, - }, - { - Path: "system/domain/delete_domains", - Inner: true, - Handler: c.Domain.Delete, - }, - } -} - -// deprecated -func serviceCluster(c Controllers) []cluster.EndpointDescriptor { - return []cluster.EndpointDescriptor{ - { - Path: "system/service/get_service", - Inner: true, - Handler: c.Service.Get, - }, - { - Path: "system/service/get_services_by_domain_id", - Inner: true, - Handler: c.Service.GetByDomainId, - }, - { - Path: "system/service/create_update_service", - Inner: true, - Handler: c.Service.CreateUpdate, - }, - { - Path: "system/service/get_service_by_id", - Inner: true, - Handler: c.Service.GetById, - }, - { - Path: "system/service/delete_service", - Inner: true, - Handler: c.Service.Delete, - }, - } -} - func applicationCluster(c Controllers) []cluster.EndpointDescriptor { return []cluster.EndpointDescriptor{ { @@ -160,10 +100,10 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Handler: c.Application.GetByIdList, }, { - Path: "system/application/get_applications_by_service_id", - Inner: true, + Path: "system/application/get_by_app_group", Extra: cluster.RequireAdminPermission("application_group_view"), - Handler: c.Application.GetByServiceId, //? + Inner: true, + Handler: c.Application.GetByAppGroup, }, { Path: "system/application/create_update_application", @@ -189,11 +129,6 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Extra: cluster.RequireAdminPermission("application_group_app_delete"), Handler: c.Application.Delete, }, - { - Path: "system/application/get_system_tree", - Inner: true, - Handler: c.Application.GetSystemTree, - }, { Path: "system/application/next_id", Inner: true, @@ -286,9 +221,9 @@ func commonEndpoints() []cluster.EndpointDescriptor { ) } -func concatCluster(clusters ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { +func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { var result []cluster.EndpointDescriptor - for _, c := range clusters { + for _, c := range endpoints { result = append(result, c...) } return result diff --git a/service/app_group.go b/service/app_group.go index 685770e..503041e 100644 --- a/service/app_group.go +++ b/service/app_group.go @@ -19,7 +19,7 @@ func NewAppGroup(repo AppGroupRepo) AppGroup { } func (s AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) { - appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description, 1) + appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "create appGroup") } diff --git a/service/application.go b/service/application.go index ac437d4..acb5e03 100644 --- a/service/application.go +++ b/service/application.go @@ -20,7 +20,6 @@ type ApplicationTxRunner interface { type Application struct { txRunner ApplicationTxRunner appRepo ApplicationRepo - domainRepo DomainRepo serviceRepo AppGroupRepo tokenRepo TokenRepo } @@ -28,31 +27,24 @@ type Application struct { func NewApplication( txRunner ApplicationTxRunner, applicationRepo ApplicationRepo, - domainRepo DomainRepo, appGroupRepo AppGroupRepo, tokenRepo TokenRepo, ) Application { return Application{ txRunner: txRunner, appRepo: applicationRepo, - domainRepo: domainRepo, serviceRepo: appGroupRepo, tokenRepo: tokenRepo, } } -func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) { - application, err := s.appRepo.GetApplicationById(ctx, appId) +func (s Application) GetById(ctx context.Context, appId int) (*domain.Application, error) { + app, err := s.appRepo.GetApplicationById(ctx, appId) if err != nil { return nil, errors.WithMessage(err, "get application by id") } - arr, err := s.EnrichWithTokens(ctx, []entity.Application{*application}) - if err != nil { - return nil, errors.WithMessage(err, "enrich application with tokens") - } - - return arr[0], nil + return new(s.convertApplication(*app)), nil } func (s Application) GetByToken(ctx context.Context, tokenStr string) (*domain.GetApplicationByTokenResponse, error) { @@ -74,127 +66,53 @@ func (s Application) GetByToken(ctx context.Context, tokenStr string) (*domain.G }, nil } -func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) { - res, err := s.appRepo.GetApplicationByIdList(ctx, idList) +func (s Application) GetByIdList(ctx context.Context, idList []int) ([]domain.Application, error) { + apps, err := s.appRepo.GetApplicationByIdList(ctx, idList) if err != nil { return nil, errors.WithMessage(err, "get application by id list") } - return s.EnrichWithTokens(ctx, res) -} - -func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) { - arr, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{id}) - if err != nil { - return nil, errors.WithMessage(err, "get application by app_group_id") + result := make([]domain.Application, len(apps)) + for i, a := range apps { + result[i] = s.convertApplication(a) } - - return s.EnrichWithTokens(ctx, arr) -} - -func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) { - domainEntityList, err := s.domainRepo.GetDomainBySystemId(ctx, systemId) - if err != nil { - return nil, errors.WithMessage(err, "get domains by system_id") - } - if len(domainEntityList) == 0 { - return []*domain.DomainWithService{}, nil - } - - result := make([]*domain.DomainWithService, len(domainEntityList)) - resultByDomainId := make(map[int]*domain.DomainWithService, len(domainEntityList)) - domainIdList := make([]int, len(domainEntityList)) - for i, domainEntity := range domainEntityList { - domainIdList[i] = domainEntity.Id - description := "" - if domainEntity.Description != nil { - description = *domainEntity.Description - } - r := &domain.DomainWithService{ - Id: domainEntity.Id, - Name: domainEntity.Name, - Description: description, - Services: make([]*domain.ServiceWithApps, 0), - } - resultByDomainId[domainEntity.Id] = r - result[i] = r - } - - serviceEntityList, err := s.serviceRepo.GetAppGroupByDomainId(ctx, domainIdList) - if err != nil { - return nil, errors.WithMessage(err, "get service by domain_id") - } - - serviceIdList := make([]int, len(serviceEntityList)) - resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList)) - for i, serviceEntity := range serviceEntityList { - serviceIdList[i] = serviceEntity.Id - resultService := &domain.ServiceWithApps{ - Id: serviceEntity.Id, - Name: serviceEntity.Name, - Description: serviceEntity.Description.String, - Apps: make([]*domain.ApplicationSimple, 0), - } - r := resultByDomainId[serviceEntity.DomainId] - r.Services = append(r.Services, resultService) - resultServiceByServiceId[serviceEntity.Id] = resultService - } - - applicationEntityList, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, serviceIdList) - if err != nil { - return nil, errors.WithMessage(err, "get application by service_id") - } - - for _, applicationEntity := range applicationEntityList { - resultService := resultServiceByServiceId[applicationEntity.ApplicationGroupId] - resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{ - Id: applicationEntity.Id, - Name: applicationEntity.Name, - Type: applicationEntity.Type, - Description: applicationEntity.Description.String, - Tokens: make([]domain.Token, 0), - }) - } - return result, nil } -func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { - if req.Id == 0 { - _, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) - if err != nil { - return nil, errors.WithMessage(err, "get application by name and service_id") - } - - appId, err := s.appRepo.NextApplicationId(ctx) - if err != nil { - return nil, errors.WithMessage(err, "next app id") - } - - app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ServiceId, req.Type) - if err != nil { - return nil, errors.WithMessage(err, "create application") - } - - result, err := s.EnrichWithTokens(ctx, []entity.Application{*app}) - if err != nil { - return nil, errors.WithMessage(err, "enrich application with tokens") - } - - return result[0], nil - } - - app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) +func (s Application) GetByAppGroup(ctx context.Context, appGroupId int) ([]domain.Application, error) { + apps, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{appGroupId}) if err != nil { - return nil, errors.WithMessage(err, "update application") + return nil, errors.WithMessage(err, "get apps by app group ids") } - result, err := s.EnrichWithTokens(ctx, []entity.Application{*app}) + result := make([]domain.Application, len(apps)) + for i, a := range apps { + result[i] = s.convertApplication(a) + } + return result, nil +} + +func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.Application, error) { + if req.Id != 0 { + app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) + if err != nil { + return nil, errors.WithMessage(err, "update application") + } + + return new(s.convertApplication(*app)), nil + } + + appId, err := s.appRepo.NextApplicationId(ctx) if err != nil { - return nil, errors.WithMessage(err, "enrich application with tokens") + return nil, errors.WithMessage(err, "next app id") } - return result[0], nil + app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ApplicationGroupId, req.Type) + if err != nil { + return nil, errors.WithMessage(err, "create application") + } + + return new(s.convertApplication(*app)), nil } func (s Application) Delete(ctx context.Context, idList []int) (int, error) { @@ -267,40 +185,32 @@ func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) { return result, nil } -func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { +func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.Application, error) { app, err := s.appRepo.CreateApplication(ctx, req.Id, req.Name, req.Description, req.ApplicationGroupId, req.Type) if err != nil { return nil, errors.WithMessage(err, "create application") } - return &domain.ApplicationWithTokens{ - App: s.convertApplication(*app), - Tokens: make([]domain.Token, 0), - }, nil + return new(s.convertApplication(*app)), nil } -func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { +func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.Application, error) { app, err := s.appRepo.UpdateApplicationWithNewId(ctx, req.OldId, req.NewId, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update application") } - result, err := s.EnrichWithTokens(ctx, []entity.Application{*app}) - if err != nil { - return nil, errors.WithMessage(err, "enrich application with tokens") - } - - return result[0], nil + return new(s.convertApplication(*app)), nil } func (s Application) convertApplication(req entity.Application) domain.Application { return domain.Application{ - Id: req.Id, - Name: req.Name, - Description: req.Description.String, - ServiceId: req.ApplicationGroupId, - Type: req.Type, - CreatedAt: req.CreatedAt, - UpdatedAt: req.UpdatedAt, + Id: req.Id, + Name: req.Name, + Description: req.Description.String, + ApplicationGroupId: req.ApplicationGroupId, + Type: req.Type, + CreatedAt: req.CreatedAt, + UpdatedAt: req.UpdatedAt, } } diff --git a/service/baseline/service.go b/service/baseline/service.go index e085137..fa97078 100644 --- a/service/baseline/service.go +++ b/service/baseline/service.go @@ -12,8 +12,7 @@ import ( const adminAppId = 1 type Transaction interface { - CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) - CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) + CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) @@ -75,12 +74,7 @@ func (s Service) transaction(ctx context.Context, tx Transaction) error { s.logger.Info(ctx, "initial admin ui token is empty, run baseline") - domain, err := tx.CreateDomain(ctx, "root", "", 1) - if err != nil { - return errors.WithMessage(err, "create domain") - } - - service, err := tx.CreateAppGroup(ctx, "rootService", "", domain.Id) + service, err := tx.CreateAppGroup(ctx, "rootService", "") if err != nil { return errors.WithMessage(err, "create service") } diff --git a/service/domain.go b/service/domain.go deleted file mode 100644 index c0fa211..0000000 --- a/service/domain.go +++ /dev/null @@ -1,109 +0,0 @@ -package service - -import ( - "context" - - "isp-system-service/domain" - "isp-system-service/entity" - - "github.com/pkg/errors" -) - -type Domain struct { - repo DomainRepo -} - -func NewDomain(repo DomainRepo) Domain { - return Domain{ - repo: repo, - } -} - -func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) { - domainEntity, err := s.repo.GetDomainById(ctx, id) - if err != nil { - return nil, errors.WithMessage(err, "get domain by id") - } - - result := s.convertDomain(*domainEntity) - return &result, nil -} - -func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) { - domainEntity, err := s.repo.GetDomainBySystemId(ctx, systemId) - if err != nil { - return nil, errors.WithMessage(err, "get domain by system_id") - } - - result := make([]domain.Domain, len(domainEntity)) - for i := range domainEntity { - result[i] = s.convertDomain(domainEntity[i]) - } - return result, nil -} - -func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) { - existed, err := s.repo.GetDomainByNameAndSystemId(ctx, req.Name, systemId) - switch { - case errors.Is(err, domain.ErrDomainNotFound): - case err != nil: - return nil, errors.WithMessage(err, "get domain by name and system_id") - } - - if req.Id == 0 { - if existed != nil { - return nil, domain.ErrDomainDuplicateName - } - - domainEntity, err := s.repo.CreateDomain(ctx, req.Name, req.Description, systemId) - if err != nil { - return nil, errors.WithMessage(err, "create domain") - } - - result := s.convertDomain(*domainEntity) - return &result, nil - } - - if existed != nil && existed.Id != req.Id { - return nil, domain.ErrDomainDuplicateName - } - - _, err = s.repo.GetDomainById(ctx, req.Id) - if err != nil { - return nil, errors.WithMessage(err, "get domain by id") - } - - domainEntity, err := s.repo.UpdateDomain(ctx, req.Id, req.Name, req.Description) - if err != nil { - return nil, errors.WithMessage(err, "update domain") - } - - result := s.convertDomain(*domainEntity) - return &result, nil -} - -func (s Domain) Delete(ctx context.Context, idList []int) (int, error) { - result, err := s.repo.DeleteDomain(ctx, idList) - if err != nil { - return 0, errors.WithMessage(err, "delete domain") - } - - return result, nil -} - -func (s Domain) convertDomain(req entity.Domain) domain.Domain { - desc := "" - if req.Description != nil { - desc = *req.Description - } - result := domain.Domain{ - Id: req.Id, - Name: req.Name, - Description: desc, - SystemId: req.SystemId, - CreatedAt: req.CreatedAt, - UpdatedAt: req.UpdatedAt, - } - - return result -} diff --git a/service/interfaces.go b/service/interfaces.go index 528c352..d368a16 100644 --- a/service/interfaces.go +++ b/service/interfaces.go @@ -10,20 +10,10 @@ type TokenRepo interface { GetTokenById(ctx context.Context, token string) (*entity.Token, error) } -type DomainRepo interface { - GetDomainById(ctx context.Context, id int) (*entity.Domain, error) - GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) - GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) - CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) - UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) - DeleteDomain(ctx context.Context, idList []int) (int, error) -} - type ApplicationRepo interface { GetApplicationById(ctx context.Context, id int) (*entity.Application, error) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) - GetApplicationByNameAndAppGroupId(ctx context.Context, name string, appGroupId int) (*entity.Application, error) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) UpdateApplicationWithNewId(ctx context.Context, oldId int, newId int, name string, description string) (*entity.Application, error) @@ -34,10 +24,9 @@ type ApplicationRepo interface { type AppGroupRepo interface { GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) - GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) - GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) - CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) + GetAppGroupByName(ctx context.Context, name string) (*entity.AppGroup, error) + CreateAppGroup(ctx context.Context, name string, desc string) (*entity.AppGroup, error) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) DeleteAppGroup(ctx context.Context, idList []int) (int, error) } diff --git a/service/secure/service.go b/service/secure/service.go index e5c51a1..9359610 100644 --- a/service/secure/service.go +++ b/service/secure/service.go @@ -46,9 +46,6 @@ func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthDa return &domain.AuthData{ AppName: authData.AppName, - SystemId: authData.SystemId, - DomainId: authData.DomainId, - ServiceId: authData.ApplicationGroupId, ApplicationId: authData.AppId, }, nil } diff --git a/service/service.go b/service/service.go deleted file mode 100644 index a16c69c..0000000 --- a/service/service.go +++ /dev/null @@ -1,115 +0,0 @@ -package service - -import ( - "context" - - "isp-system-service/domain" - "isp-system-service/entity" - - "github.com/pkg/errors" -) - -type Service struct { - domainRepo DomainRepo - serviceRepo AppGroupRepo -} - -func NewService( - domainRepo DomainRepo, - serviceRepo AppGroupRepo, -) Service { - return Service{ - domainRepo: domainRepo, - serviceRepo: serviceRepo, - } -} - -func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, id) - if err != nil { - return nil, errors.WithMessage(err, "get service by id") - } - - result := s.convertService(*serviceEntity) - return &result, nil -} - -func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetAppGroupByIdList(ctx, idList) - if err != nil { - return nil, errors.WithMessage(err, "get system by id list") - } - - result := make([]domain.Service, len(serviceEntity)) - for i := range serviceEntity { - result[i] = s.convertService(serviceEntity[i]) - } - return result, nil -} - -func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetAppGroupByDomainId(ctx, []int{domainId}) - if err != nil { - return nil, errors.WithMessage(err, "get system by id list") - } - - result := make([]domain.Service, len(serviceEntity)) - for i := range serviceEntity { - result[i] = s.convertService(serviceEntity[i]) - } - return result, nil -} - -func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { - req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed - - _, err := s.domainRepo.GetDomainById(ctx, req.DomainId) - if err != nil { - return nil, errors.WithMessage(err, "get domain by id") - } - - if req.Id == 0 { - serviceEntity, err := s.serviceRepo.CreateAppGroup(ctx, req.Name, req.Description, req.DomainId) - if err != nil { - return nil, errors.WithMessage(err, "create service") - } - - result := s.convertService(*serviceEntity) - return &result, nil - } - - _, err = s.serviceRepo.GetAppGroupById(ctx, req.Id) - if err != nil { - return nil, errors.WithMessage(err, "get service by id") - } - - serviceEntity, err := s.serviceRepo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description) - if err != nil { - return nil, errors.WithMessage(err, "update service") - } - - result := s.convertService(*serviceEntity) - return &result, nil -} - -func (s Service) Delete(ctx context.Context, idList []int) (int, error) { - result, err := s.serviceRepo.DeleteAppGroup(ctx, idList) - if err != nil { - return 0, errors.WithMessage(err, "delete service") - } - - return result, nil -} - -func (s Service) convertService(req entity.AppGroup) domain.Service { - result := domain.Service{ - Id: req.Id, - Name: req.Name, - Description: req.Description.String, - DomainId: req.DomainId, - CreatedAt: req.CreatedAt, - UpdatedAt: req.UpdatedAt, - } - - return result -} diff --git a/service/token.go b/service/token.go index 5a37acf..6f23223 100644 --- a/service/token.go +++ b/service/token.go @@ -35,7 +35,6 @@ type Token struct { appEnricher AppEnricher tx TokenTxRunner appRepo ApplicationRepo - domainRepo DomainRepo serviceRepo AppGroupRepo tokenRepo TokenRepo } @@ -45,7 +44,6 @@ func NewToken( appEnricher AppEnricher, tx TokenTxRunner, appRepo ApplicationRepo, - domainRepo DomainRepo, appGroupRepo AppGroupRepo, tokenRepo TokenRepo, ) Token { @@ -54,7 +52,6 @@ func NewToken( jwt: jwtGenerate, tx: tx, appRepo: appRepo, - domainRepo: domainRepo, serviceRepo: appGroupRepo, tokenRepo: tokenRepo, } @@ -80,16 +77,6 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma return nil, errors.WithMessage(err, "get application by id") } - serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, applicationEntity.ApplicationGroupId) - if err != nil { - return nil, errors.WithMessage(err, "get service by id") - } - - _, err = s.domainRepo.GetDomainById(ctx, serviceEntity.DomainId) - if err != nil { - return nil, errors.WithMessage(err, "get domain by id") - } - token, err := s.jwt.CreateApplicationToken() if err != nil { return nil, errors.WithMessage(err, "create application token") diff --git a/tests/access_list_test.go b/tests/access_list_test.go index 25d388b..fa1588c 100644 --- a/tests/access_list_test.go +++ b/tests/access_list_test.go @@ -44,19 +44,10 @@ func (s *AccessListSuite) SetupTest() { _, s.api = grpct.TestServer(s.test, config.Handler) s.accessListRepo = repository.NewAccessList(s.testDb) - createdDomain, err := repository.NewDomain(s.testDb).CreateDomain( - s.T().Context(), - fake.It[string](), - fake.It[string](), - 1, - ) - s.Require().NoError(err) - appGroup, err := repository.NewAppGroup(s.testDb).CreateAppGroup( s.T().Context(), fake.It[string](), fake.It[string](), - createdDomain.Id, ) s.Require().NoError(err) diff --git a/tests/app_group_test.go b/tests/app_group_test.go index fa6ea07..2bd49b0 100644 --- a/tests/app_group_test.go +++ b/tests/app_group_test.go @@ -29,7 +29,6 @@ type AppGroupSuite struct { test *test.Test testDb *dbt.TestDb - domainRepo repository.Domain appGroupRepo repository.AppGroup api *client.Client } @@ -42,17 +41,7 @@ func (s *AppGroupSuite) SetupTest() { locator := assembly.NewLocator(s.testDb, s.test.Logger()) config := locator.Config(conf.Remote{}) _, s.api = grpct.TestServer(s.test, config.Handler) - s.domainRepo = repository.NewDomain(s.testDb) s.appGroupRepo = repository.NewAppGroup(s.testDb) - - q := ` - INSERT INTO domain - (id, name, description, system_id) - VALUES ($1, $2, $3, $4) - RETURNING id, name, description, system_id, created_at, updated_at - ` - _, err := s.testDb.Exec(s.T().Context(), q, 1, fake.It[string](), fake.It[string](), 1) - s.Require().NoError(err) } func (s *AppGroupSuite) TestGetByIdList() { @@ -96,7 +85,6 @@ func (s *AppGroupSuite) TestGetByIdList_EmptyDescription() { s.T().Context(), fake.It[string](), "", - 1, ) s.Require().NoError(err) appGroups = append(appGroups, domain.AppGroup{ @@ -281,7 +269,6 @@ func (s *AppGroupSuite) createAppGroup() *entity.AppGroup { s.T().Context(), fake.It[string](), fake.It[string](), - 1, ) s.Require().NoError(err) return appGroup diff --git a/tests/application_test.go b/tests/application_test.go index c263a0b..435f37f 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -29,7 +29,6 @@ type ApplicationSuite struct { test *test.Test testDb *dbt.TestDb - domainRepo repository.Domain appRepo repository.Application appGroupRepo repository.AppGroup tokenRepo repository.Token @@ -44,7 +43,6 @@ func (s *ApplicationSuite) SetupTest() { locator := assembly.NewLocator(s.testDb, s.test.Logger()) config := locator.Config(conf.Remote{}) _, s.api = grpct.TestServer(s.test, config.Handler) - s.domainRepo = repository.NewDomain(s.testDb) s.appRepo = repository.NewApplication(s.testDb) s.appGroupRepo = repository.NewAppGroup(s.testDb) s.tokenRepo = repository.NewToken(s.testDb) @@ -68,8 +66,44 @@ func (s *ApplicationSuite) TestGetAllApplications() { s.Require().ElementsMatch(expectedApps, result) } +func (s *ApplicationSuite) Test_GetByAppId() { + expectedApps := s.insertApps(2) + + result := []domain.Application{} + err := s.api.Invoke("system/application/get_by_app_group"). + JsonRequestBody(domain.Identity{ + Id: expectedApps[0].ApplicationGroupId, + }). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + for i := range result { + s.Require().NotEmpty(result[i].CreatedAt) + result[i].CreatedAt = time.Time{} + + s.Require().NotEmpty(result[i].UpdatedAt) + result[i].UpdatedAt = time.Time{} + } + s.Require().ElementsMatch(expectedApps, result) +} + +func (s *ApplicationSuite) Test_GetByAppId_NotFoundAny() { + insertedApps := s.insertApps(2) + + result := []domain.Application{} + err := s.api.Invoke("system/application/get_by_app_group"). + JsonRequestBody(domain.Identity{ + Id: fake.It[int]() + insertedApps[0].ApplicationGroupId, + }). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + s.Require().Empty(result) +} + func (s *ApplicationSuite) TestCreate_HappyPath() { - result := domain.ApplicationWithTokens{} + result := domain.Application{} appGroup := s.createAppGroup() apiReq := domain.CreateApplicationRequest{ @@ -85,21 +119,20 @@ func (s *ApplicationSuite) TestCreate_HappyPath() { Do(s.T().Context()) s.Require().NoError(err) - s.Require().NotEmpty(result.App.CreatedAt) - result.App.CreatedAt = time.Time{} + s.Require().NotEmpty(result.CreatedAt) + result.CreatedAt = time.Time{} - s.Require().NotEmpty(result.App.UpdatedAt) - result.App.UpdatedAt = time.Time{} + s.Require().NotEmpty(result.UpdatedAt) + result.UpdatedAt = time.Time{} expectedApp := domain.Application{ - Id: apiReq.Id, - Name: apiReq.Name, - Description: apiReq.Description, - Type: apiReq.Type, - ServiceId: apiReq.ApplicationGroupId, + Id: apiReq.Id, + Name: apiReq.Name, + Description: apiReq.Description, + Type: apiReq.Type, + ApplicationGroupId: apiReq.ApplicationGroupId, } - s.Require().Equal(expectedApp, result.App) - s.Require().Empty(result.Tokens) + s.Require().Equal(expectedApp, result) } func (s *ApplicationSuite) TestCreate_AppGroupNotFound() { @@ -125,7 +158,7 @@ func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() { Id: inserted[0].Id + 1, Name: inserted[0].Name, Type: domain.ApplicationSystemType, - ApplicationGroupId: inserted[0].ServiceId, + ApplicationGroupId: inserted[0].ApplicationGroupId, } err := s.api.Invoke("system/application/create_application"). @@ -143,7 +176,7 @@ func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { Id: inserted[0].Id, Name: inserted[0].Name, Type: domain.ApplicationSystemType, - ApplicationGroupId: inserted[0].ServiceId, + ApplicationGroupId: inserted[0].ApplicationGroupId, } err := s.api.Invoke("system/application/create_application"). @@ -163,28 +196,27 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { Description: fake.It[string](), } - var result domain.ApplicationWithTokens + var result domain.Application err := s.api.Invoke("system/application/update_application"). JsonRequestBody(apiReq). JsonResponseBody(&result). Do(s.T().Context()) s.Require().NoError(err) - s.Require().NotEmpty(result.App.CreatedAt) - result.App.CreatedAt = time.Time{} + s.Require().NotEmpty(result.CreatedAt) + result.CreatedAt = time.Time{} - s.Require().NotEmpty(result.App.UpdatedAt) - result.App.UpdatedAt = time.Time{} + s.Require().NotEmpty(result.UpdatedAt) + result.UpdatedAt = time.Time{} expectedApp := domain.Application{ - Id: apiReq.NewId, - Name: apiReq.Name, - Description: apiReq.Description, - Type: inserted[0].Type, - ServiceId: inserted[0].ServiceId, + Id: apiReq.NewId, + Name: apiReq.Name, + Description: apiReq.Description, + Type: inserted[0].Type, + ApplicationGroupId: inserted[0].ApplicationGroupId, } - s.Require().Equal(expectedApp, result.App) - s.Require().Empty(result.Tokens) + s.Require().Equal(expectedApp, result) app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.NewId) s.Require().NoError(err) @@ -194,7 +226,7 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { Name: apiReq.Name, Description: app.Description, Type: inserted[0].Type, - ApplicationGroupId: inserted[0].ServiceId, + ApplicationGroupId: inserted[0].ApplicationGroupId, } s.Require().NotEmpty(app.CreatedAt) @@ -261,7 +293,7 @@ func (s *ApplicationSuite) TestGetByToken() { token := fake.It[string]() expectedApp := domain.GetApplicationByTokenResponse{ ApplicationId: insertedApps[0].Id, - ApplicationGroupId: insertedApps[0].ServiceId, + ApplicationGroupId: insertedApps[0].ApplicationGroupId, } _, err := s.tokenRepo.SaveToken(s.T().Context(), token, expectedApp.ApplicationId, fake.It[int]()) s.Require().NoError(err) @@ -289,19 +321,10 @@ func (s *ApplicationSuite) TestGetByToken_NotFound() { } func (s *ApplicationSuite) createAppGroup() *entity.AppGroup { - createdDomain, err := s.domainRepo.CreateDomain( - s.T().Context(), - fake.It[string](), - fake.It[string](), - 1, - ) - s.Require().NoError(err) - appGroup, err := s.appGroupRepo.CreateAppGroup( s.T().Context(), fake.It[string](), fake.It[string](), - createdDomain.Id, ) s.Require().NoError(err) return appGroup @@ -329,13 +352,13 @@ func (s *ApplicationSuite) insertApps(appsCount uint) []domain.Application { s.Require().NotEmpty(createdApp.UpdatedAt) toExpect = append(toExpect, domain.Application{ - Id: createdApp.Id, - Name: createdApp.Name, - Description: createdApp.Description.String, - ServiceId: createdApp.ApplicationGroupId, - Type: createdApp.Type, - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, + Id: createdApp.Id, + Name: createdApp.Name, + Description: createdApp.Description.String, + ApplicationGroupId: createdApp.ApplicationGroupId, + Type: createdApp.Type, + CreatedAt: time.Time{}, + UpdatedAt: time.Time{}, }) } return toExpect diff --git a/tests/general_insert_db_test.go b/tests/general_insert_db_test.go index 33bf508..5c08823 100644 --- a/tests/general_insert_db_test.go +++ b/tests/general_insert_db_test.go @@ -6,22 +6,12 @@ import ( "github.com/txix-open/isp-kit/test/dbt" ) -func InsertDomain(db *dbt.TestDb, value entity.Domain) { - q := ` - INSERT INTO domain - (id, name, description, system_id, created_at, updated_at) - VALUES - (:id, :name, :description, 1, :created_at, :updated_at) -` - db.Must().ExecNamed(q, value) -} - func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) { q := ` INSERT INTO application_group - (id, name, description, domain_id, created_at, updated_at) + (id, name, description, created_at, updated_at) VALUES - (:id, :name, :description, :domain_id, :created_at, :updated_at) + (:id, :name, :description, :created_at, :updated_at) ` db.Must().ExecNamed(q, value) } diff --git a/tests/secure_test.go b/tests/secure_test.go index 9f87ca7..7f5f4ca 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -42,11 +42,8 @@ func (s *SecureSuite) SetupSuite() { _, s.api = grpct.TestServer(s.test, config.Handler) createdTime := time.Now().UTC() - InsertDomain(s.testDb, entity.Domain{ - Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime, - }) InsertAppGroup(s.testDb, entity.AppGroup{ - Id: 5, Name: "test_application_group", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime, + Id: 5, Name: "test_application_group", CreatedAt: createdTime, UpdatedAt: createdTime, }) InsertApplication(s.testDb, entity.Application{ Id: 7, Name: "test_application", ApplicationGroupId: 5, CreatedAt: createdTime, UpdatedAt: createdTime, @@ -72,9 +69,6 @@ func (s *SecureSuite) TestAuthenticate_Success() { ErrorReason: "", AuthData: &domain.AuthData{ AppName: "test_application", - SystemId: 1, - DomainId: 3, - ServiceId: 5, ApplicationId: 7, }, }, result) @@ -114,9 +108,6 @@ func (s *SecureSuite) TestAuthenticate_NotExpired() { ErrorReason: "", AuthData: &domain.AuthData{ AppName: "test_application", - SystemId: 1, - DomainId: 3, - ServiceId: 5, ApplicationId: 7, }, }, result) diff --git a/transaction/manager.go b/transaction/manager.go index fc76758..d47e323 100644 --- a/transaction/manager.go +++ b/transaction/manager.go @@ -87,7 +87,6 @@ func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Conte type baselineTx struct { repository.Locker - repository.Domain repository.AppGroup repository.Application repository.AccessList @@ -98,7 +97,6 @@ func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { return txTx(ctx, baselineTx{ Locker: repository.NewLocker(tx), - Domain: repository.NewDomain(tx), AppGroup: repository.NewAppGroup(tx), Application: repository.NewApplication(tx), AccessList: repository.NewAccessList(tx),