From 2127a66b079c2949e6c74fe75d8c0674c94dfe63 Mon Sep 17 00:00:00 2001 From: deo002 Date: Tue, 29 Oct 2024 10:53:42 +0530 Subject: [PATCH] feat(admin_obligation_types): Admin apis to create, delete and get obligation types Signed-off-by: deo002 --- cmd/laas/docs/docs.go | 181 ++++++++++++++++++++++- cmd/laas/docs/swagger.json | 181 ++++++++++++++++++++++- cmd/laas/docs/swagger.yaml | 117 ++++++++++++++- pkg/api/api.go | 6 + pkg/api/obligationTypes.go | 284 +++++++++++++++++++++++++++++++++++++ pkg/api/obligations.go | 20 +-- pkg/models/types.go | 29 ++-- pkg/utils/util.go | 13 ++ 8 files changed, 803 insertions(+), 28 deletions(-) create mode 100644 pkg/api/obligationTypes.go diff --git a/cmd/laas/docs/docs.go b/cmd/laas/docs/docs.go index c3d2aee..65f252f 100644 --- a/cmd/laas/docs/docs.go +++ b/cmd/laas/docs/docs.go @@ -1270,6 +1270,160 @@ const docTemplate = `{ } } }, + "/obligations/types": { + "get": { + "security": [ + { + "ApiKeyAuth": [], + "{}": [] + } + ], + "description": "Get all active obligation types from the service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Get all active obligation types", + "operationId": "GetAllObligationType", + "parameters": [ + { + "type": "boolean", + "description": "Active obligation only", + "name": "active", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/models.ObligationTypeResponse" + } + }, + "404": { + "description": "No obligation types in DB", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Create an obligation type", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Create an obligation type", + "operationId": "CreateObligationType", + "parameters": [ + { + "description": "Obligation type to create", + "name": "obligation_type", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/models.ObligationType" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/models.ObligationTypeResponse" + } + }, + "400": { + "description": "invalid json body", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "409": { + "description": "obligation type already exists", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "500": { + "description": "something went wrong while creating new obligation type", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + } + }, + "/obligations/types/{type}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deactivate an obligation type", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Deactivate obligation type", + "operationId": "DeleteObligationType", + "parameters": [ + { + "type": "string", + "description": "Obligation Type", + "name": "type", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "cannot delete obligation type 'RISK' as it's still referenced by some obligations", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "404": { + "description": "obligation type 'RISK' not found", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "500": { + "description": "something went wrong while deleting obligation type", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + } + }, "/obligations/{topic}": { "get": { "security": [ @@ -2370,12 +2524,31 @@ const docTemplate = `{ }, "models.ObligationType": { "type": "object", + "required": [ + "type" + ], "properties": { - "id": { - "type": "integer" - }, "type": { - "type": "string" + "type": "string", + "example": "PERMISSION" + } + } + }, + "models.ObligationTypeResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/models.ObligationType" + } + }, + "paginationmeta": { + "$ref": "#/definitions/models.PaginationMeta" + }, + "status": { + "type": "integer", + "example": 200 } } }, diff --git a/cmd/laas/docs/swagger.json b/cmd/laas/docs/swagger.json index 3e251d7..d7a1f82 100644 --- a/cmd/laas/docs/swagger.json +++ b/cmd/laas/docs/swagger.json @@ -1263,6 +1263,160 @@ } } }, + "/obligations/types": { + "get": { + "security": [ + { + "ApiKeyAuth": [], + "{}": [] + } + ], + "description": "Get all active obligation types from the service", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Get all active obligation types", + "operationId": "GetAllObligationType", + "parameters": [ + { + "type": "boolean", + "description": "Active obligation only", + "name": "active", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/models.ObligationTypeResponse" + } + }, + "404": { + "description": "No obligation types in DB", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + }, + "post": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Create an obligation type", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Create an obligation type", + "operationId": "CreateObligationType", + "parameters": [ + { + "description": "Obligation type to create", + "name": "obligation_type", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/models.ObligationType" + } + } + ], + "responses": { + "201": { + "description": "Created", + "schema": { + "$ref": "#/definitions/models.ObligationTypeResponse" + } + }, + "400": { + "description": "invalid json body", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "409": { + "description": "obligation type already exists", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "500": { + "description": "something went wrong while creating new obligation type", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + } + }, + "/obligations/types/{type}": { + "delete": { + "security": [ + { + "ApiKeyAuth": [] + } + ], + "description": "Deactivate an obligation type", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Obligations" + ], + "summary": "Deactivate obligation type", + "operationId": "DeleteObligationType", + "parameters": [ + { + "type": "string", + "description": "Obligation Type", + "name": "type", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "cannot delete obligation type 'RISK' as it's still referenced by some obligations", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "404": { + "description": "obligation type 'RISK' not found", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + }, + "500": { + "description": "something went wrong while deleting obligation type", + "schema": { + "$ref": "#/definitions/models.LicenseError" + } + } + } + } + }, "/obligations/{topic}": { "get": { "security": [ @@ -2363,12 +2517,31 @@ }, "models.ObligationType": { "type": "object", + "required": [ + "type" + ], "properties": { - "id": { - "type": "integer" - }, "type": { - "type": "string" + "type": "string", + "example": "PERMISSION" + } + } + }, + "models.ObligationTypeResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/definitions/models.ObligationType" + } + }, + "paginationmeta": { + "$ref": "#/definitions/models.PaginationMeta" + }, + "status": { + "type": "integer", + "example": 200 } } }, diff --git a/cmd/laas/docs/swagger.yaml b/cmd/laas/docs/swagger.yaml index 38ae564..2fd8fab 100644 --- a/cmd/laas/docs/swagger.yaml +++ b/cmd/laas/docs/swagger.yaml @@ -483,10 +483,23 @@ definitions: type: object models.ObligationType: properties: - id: - type: integer type: + example: PERMISSION type: string + required: + - type + type: object + models.ObligationTypeResponse: + properties: + data: + items: + $ref: '#/definitions/models.ObligationType' + type: array + paginationmeta: + $ref: '#/definitions/models.PaginationMeta' + status: + example: 200 + type: integer type: object models.ObligationUpdateDTO: properties: @@ -1571,6 +1584,106 @@ paths: summary: Get topic and types of all active obligations tags: - Obligations + /obligations/types: + get: + consumes: + - application/json + description: Get all active obligation types from the service + operationId: GetAllObligationType + parameters: + - description: Active obligation only + in: query + name: active + required: true + type: boolean + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/models.ObligationTypeResponse' + "404": + description: No obligation types in DB + schema: + $ref: '#/definitions/models.LicenseError' + security: + - '{}': [] + ApiKeyAuth: [] + summary: Get all active obligation types + tags: + - Obligations + post: + consumes: + - application/json + description: Create an obligation type + operationId: CreateObligationType + parameters: + - description: Obligation type to create + in: body + name: obligation_type + required: true + schema: + $ref: '#/definitions/models.ObligationType' + produces: + - application/json + responses: + "201": + description: Created + schema: + $ref: '#/definitions/models.ObligationTypeResponse' + "400": + description: invalid json body + schema: + $ref: '#/definitions/models.LicenseError' + "409": + description: obligation type already exists + schema: + $ref: '#/definitions/models.LicenseError' + "500": + description: something went wrong while creating new obligation type + schema: + $ref: '#/definitions/models.LicenseError' + security: + - ApiKeyAuth: [] + summary: Create an obligation type + tags: + - Obligations + /obligations/types/{type}: + delete: + consumes: + - application/json + description: Deactivate an obligation type + operationId: DeleteObligationType + parameters: + - description: Obligation Type + in: path + name: type + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + "400": + description: cannot delete obligation type 'RISK' as it's still referenced + by some obligations + schema: + $ref: '#/definitions/models.LicenseError' + "404": + description: obligation type 'RISK' not found + schema: + $ref: '#/definitions/models.LicenseError' + "500": + description: something went wrong while deleting obligation type + schema: + $ref: '#/definitions/models.LicenseError' + security: + - ApiKeyAuth: [] + summary: Deactivate obligation type + tags: + - Obligations /search: post: consumes: diff --git a/pkg/api/api.go b/pkg/api/api.go index 3e25dbc..57109fe 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -133,6 +133,9 @@ func Router() *gin.Engine { obligations.POST("import", ImportObligations) obligations.PATCH(":topic", UpdateObligation) obligations.DELETE(":topic", DeleteObligation) + obligations.GET("/types", GetAllObligationType) + obligations.POST("/types", CreateObligationType) + obligations.DELETE("/types/:type", DeleteObligationType) } obMap := authorizedv1.Group("/obligation_maps") { @@ -218,6 +221,9 @@ func Router() *gin.Engine { obligations.POST("import", ImportObligations) obligations.PATCH(":topic", UpdateObligation) obligations.DELETE(":topic", DeleteObligation) + obligations.GET("/types", GetAllObligationType) + obligations.POST("/types", CreateObligationType) + obligations.DELETE("/types/:type", DeleteObligationType) } obMap := authorizedv1.Group("/obligation_maps") { diff --git a/pkg/api/obligationTypes.go b/pkg/api/obligationTypes.go new file mode 100644 index 0000000..447a960 --- /dev/null +++ b/pkg/api/obligationTypes.go @@ -0,0 +1,284 @@ +// SPDX-FileCopyrightText: 2024 Siemens AG +// SPDX-FileContributor: Dearsh Oberoi +// +// SPDX-License-Identifier: GPL-2.0-only + +package api + +import ( + "errors" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/fossology/LicenseDb/pkg/db" + "github.com/fossology/LicenseDb/pkg/models" + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +// GetAllObligationType retrieves a list of all obligation types +// +// @Summary Get all active obligation types +// @Description Get all active obligation types from the service +// @Id GetAllObligationType +// @Tags Obligations +// @Accept json +// @Produce json +// @Param active query bool true "Active obligation only" +// @Success 200 {object} models.ObligationTypeResponse +// @Failure 404 {object} models.LicenseError "No obligation types in DB" +// @Security ApiKeyAuth || {} +// @Router /obligations/types [get] +func GetAllObligationType(c *gin.Context) { + var obligationTypes []models.ObligationType + active := c.Query("active") + if active == "" { + active = "true" + } + var parsedActive bool + parsedActive, err := strconv.ParseBool(active) + if err != nil { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: "Invalid active value", + Error: fmt.Sprintf("Parsing failed for value '%s'", active), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return + } + + query := db.DB.Model(&models.ObligationType{}) + query.Where("active = ?", parsedActive) + if err = query.Find(&obligationTypes).Error; err != nil { + er := models.LicenseError{ + Status: http.StatusInternalServerError, + Message: "Unable to fetch obligation types", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusInternalServerError, er) + return + } + + res := models.ObligationTypeResponse{ + Data: obligationTypes, + Status: http.StatusOK, + Meta: &models.PaginationMeta{ + ResourceCount: len(obligationTypes), + }, + } + + c.JSON(http.StatusOK, res) +} + +// CreateObligationType creates a new obligation type. +// +// @Summary Create an obligation type +// @Description Create an obligation type +// @Id CreateObligationType +// @Tags Obligations +// @Accept json +// @Produce json +// @Param obligation_type body models.ObligationType true "Obligation type to create" +// @Success 201 {object} models.ObligationTypeResponse +// @Failure 400 {object} models.LicenseError "invalid json body" +// @Failure 409 {object} models.LicenseError "obligation type already exists" +// @Failure 500 {object} models.LicenseError "something went wrong while creating new obligation type" +// @Security ApiKeyAuth +// @Router /obligations/types [post] +func CreateObligationType(c *gin.Context) { + var obType models.ObligationType + if err := c.ShouldBindJSON(&obType); err != nil { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: "invalid json body", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return + } + + validate := validator.New(validator.WithRequiredStructEnabled()) + if err := validate.Struct(&obType); err != nil { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: "can not create obligation type with these field values", + Error: fmt.Sprintf("field '%s' failed validation: %s\n", err.(validator.ValidationErrors)[0].Field(), err.(validator.ValidationErrors)[0].Tag()), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return + } + + if err := db.DB.Transaction(func(tx *gorm.DB) error { + result := tx.Where(&models.ObligationType{Type: obType.Type}).FirstOrCreate(&obType) + if result.Error != nil { + er := models.LicenseError{ + Status: http.StatusInternalServerError, + Message: "something went wrong while creating new obligation type", + Error: result.Error.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusInternalServerError, er) + return result.Error + } + if result.RowsAffected == 0 { + if *obType.Active { + er := models.LicenseError{ + Status: http.StatusConflict, + Message: "obligation type already exists", + Error: "obligation type already exists", + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusConflict, er) + return errors.New("obligation type already exists") + } + if err := toggleObligationTypeActiveStatus(c, tx, &obType); err != nil { + er := models.LicenseError{ + Status: http.StatusConflict, + Message: "obligation type already exists, something went wrong while reactvating it", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusConflict, er) + return err + } + } + return nil + }); err != nil { + return + } + + res := models.ObligationTypeResponse{ + Status: http.StatusCreated, + Data: []models.ObligationType{obType}, + Meta: &models.PaginationMeta{ + ResourceCount: 1, + }, + } + + c.JSON(http.StatusCreated, res) +} + +// DeleteObligationType marks an existing obligation type record as inactive +// +// @Summary Deactivate obligation type +// @Description Deactivate an obligation type +// @Id DeleteObligationType +// @Tags Obligations +// @Accept json +// @Produce json +// @Param type path string true "Obligation Type" +// @Success 200 +// @Failure 400 {object} models.LicenseError "cannot delete obligation type 'RISK' as it's still referenced by some obligations" +// @Failure 404 {object} models.LicenseError "obligation type 'RISK' not found" +// @Failure 500 {object} models.LicenseError "something went wrong while deleting obligation type" +// @Security ApiKeyAuth +// @Router /obligations/types/{type} [delete] +func DeleteObligationType(c *gin.Context) { + var obType models.ObligationType + obTypeParam := c.Param("type") + if err := db.DB.Where(models.ObligationType{Type: obTypeParam}).First(&obType).Error; err != nil { + er := models.LicenseError{ + Status: http.StatusNotFound, + Message: fmt.Sprintf("obligation type '%s' not found", obTypeParam), + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusNotFound, er) + return + } + + if !*obType.Active { + c.Status(http.StatusOK) + return + } + + var count int64 + if err := db.DB.Model(&models.Obligation{}).Where(&models.Obligation{ObligationTypeId: obType.Id}).Count(&count).Error; err != nil { + er := models.LicenseError{ + Status: http.StatusInternalServerError, + Message: "something went wrong while deleting obligation type", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusInternalServerError, er) + return + } + + if count > 0 { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: fmt.Sprintf("cannot delete obligation type '%s' as it's still referenced by some obligations", obType.Type), + Error: fmt.Sprintf("cannot delete obligation type '%s' as it's still referenced by some obligations", obType.Type), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return + } + + if err := db.DB.Transaction(func(tx *gorm.DB) error { + return toggleObligationTypeActiveStatus(c, tx, &obType) + }); err != nil { + er := models.LicenseError{ + Status: http.StatusInternalServerError, + Message: "something went wrong while deleting obligation type", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusInternalServerError, er) + } + c.Status(http.StatusOK) +} + +func toggleObligationTypeActiveStatus(c *gin.Context, tx *gorm.DB, obType *models.ObligationType) error { + *obType.Active = !*obType.Active + if err := tx.Clauses(clause.Returning{}).Updates(&obType).Error; err != nil { + return errors.New("unable to change 'active' status of obligation type") + } + + username := c.GetString("username") + var user models.User + if err := tx.Where(models.User{Username: username}).First(&user).Error; err != nil { + return errors.New("unable to change 'active' status of obligation type") + } + + oldVal := strconv.FormatBool(!*obType.Active) + newVal := strconv.FormatBool(*obType.Active) + change := models.ChangeLog{ + Field: "Active", + OldValue: &oldVal, + UpdatedValue: &newVal, + } + + audit := models.Audit{ + UserId: user.Id, + TypeId: obType.Id, + Timestamp: time.Now(), + Type: "ObligationType", + ChangeLogs: []models.ChangeLog{change}, + } + + if err := tx.Create(&audit).Error; err != nil { + return errors.New("unable to change 'active' status of obligation type") + } + + return nil +} diff --git a/pkg/api/obligations.go b/pkg/api/obligations.go index 2e68abf..f55017d 100644 --- a/pkg/api/obligations.go +++ b/pkg/api/obligations.go @@ -63,7 +63,7 @@ func GetAllObligation(c *gin.Context) { return } query := db.DB.Model(&models.Obligation{}) - query.Where("active = ?", parsedActive) + query.Where(&models.Obligation{Active: &parsedActive}) _ = utils.PreparePaginateResponse(c, query, &models.ObligationResponse{}) @@ -174,13 +174,13 @@ func CreateObligation(c *gin.Context) { if result.Error != nil { er := models.LicenseError{ - Status: http.StatusInternalServerError, + Status: http.StatusBadRequest, Message: "Failed to create obligation", Error: result.Error.Error(), Path: c.Request.URL.Path, Timestamp: time.Now().Format(time.RFC3339), } - c.JSON(http.StatusInternalServerError, er) + c.JSON(http.StatusBadRequest, er) return } @@ -277,13 +277,13 @@ func UpdateObligation(c *gin.Context) { return nil }); err != nil { er := models.LicenseError{ - Status: http.StatusInternalServerError, + Status: http.StatusBadRequest, Message: "Failed to update license", Error: err.Error(), Path: c.Request.URL.Path, Timestamp: time.Now().Format(time.RFC3339), } - c.JSON(http.StatusInternalServerError, er) + c.JSON(http.StatusBadRequest, er) return } @@ -463,13 +463,13 @@ func ImportObligations(c *gin.Context) { decoder := json.NewDecoder(file) if err := decoder.Decode(&obligations); err != nil { er := models.LicenseError{ - Status: http.StatusInternalServerError, + Status: http.StatusBadRequest, Message: "invalid json", Error: err.Error(), Path: c.Request.URL.Path, Timestamp: time.Now().Format(time.RFC3339), } - c.JSON(http.StatusInternalServerError, er) + c.JSON(http.StatusBadRequest, er) return } @@ -491,7 +491,7 @@ func ImportObligations(c *gin.Context) { FirstOrCreate(&oldObligation) if result.Error != nil { res.Data = append(res.Data, models.LicenseError{ - Status: http.StatusInternalServerError, + Status: http.StatusBadRequest, Message: fmt.Sprintf("Failed to create/update obligation: %s", result.Error.Error()), Error: *ob.Topic, Path: c.Request.URL.Path, @@ -504,7 +504,7 @@ func ImportObligations(c *gin.Context) { ctx := context.WithValue(context.Background(), models.ContextKey("oldObligation"), &oldObligation) if err := tx.WithContext(ctx).Omit("Licenses", "Topic").Clauses(clause.Returning{}).Updates(&newObligation).Error; err != nil { res.Data = append(res.Data, models.LicenseError{ - Status: http.StatusInternalServerError, + Status: http.StatusBadRequest, Message: fmt.Sprintf("Failed to update obligation: %s", err.Error()), Error: *ob.Topic, Path: c.Request.URL.Path, @@ -728,7 +728,7 @@ func GetAllObligationPreviews(c *gin.Context) { return } - if err = db.DB.Joins("Type").Where("active = ?", parsedActive).Find(&obligations).Error; err != nil { + if err = db.DB.Joins("Type").Where(&models.Obligation{Active: &parsedActive}).Find(&obligations).Error; err != nil { er := models.LicenseError{ Status: http.StatusInternalServerError, Message: "Unable to fetch obligations", diff --git a/pkg/models/types.go b/pkg/models/types.go index 0b03331..e11e6ad 100644 --- a/pkg/models/types.go +++ b/pkg/models/types.go @@ -279,9 +279,18 @@ type AuditResponse struct { Meta *PaginationMeta `json:"paginationmeta"` } +// ObligationType represents one of the possible of obligation type values type ObligationType struct { - Id int64 `gorm:"primary_key"` - Type string `gorm:"unique;not null"` + Id int64 `gorm:"primary_key" json:"-"` + Type string `gorm:"unique;not null" validate:"required,uppercase" example:"PERMISSION" json:"type"` + Active *bool `gorm:"not null;default:true" json:"-"` +} + +// ObligationTypeResponse represents the response format for obligation type data. +type ObligationTypeResponse struct { + Status int `json:"status" example:"200"` + Data []ObligationType `json:"data"` + Meta *PaginationMeta `json:"paginationmeta"` } type ObligationClassification struct { @@ -322,9 +331,11 @@ func (o *Obligation) BeforeCreate(tx *gorm.DB) (err error) { } allTypes := "" for i := 0; i < len(obTypes); i++ { - allTypes += fmt.Sprintf(" %s", obTypes[i].Type) - if o.Type.Type == obTypes[i].Type { - o.Type = &obTypes[i] + if *obTypes[i].Active { + allTypes += fmt.Sprintf(" %s", obTypes[i].Type) + if o.Type.Type == obTypes[i].Type { + o.Type = &obTypes[i] + } } } if o.Type.Id == 0 { @@ -389,9 +400,11 @@ func (o *Obligation) BeforeUpdate(tx *gorm.DB) (err error) { } allTypes := "" for i := 0; i < len(obTypes); i++ { - allTypes += fmt.Sprintf(" %s", obTypes[i].Type) - if o.Type.Type == obTypes[i].Type { - o.Type = &obTypes[i] + if *obTypes[i].Active { + allTypes += fmt.Sprintf(" %s", obTypes[i].Type) + if o.Type.Type == obTypes[i].Type { + o.Type = &obTypes[i] + } } } if o.Type.Id == 0 { diff --git a/pkg/utils/util.go b/pkg/utils/util.go index 4144d92..6d24c87 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -446,6 +446,19 @@ func GetAuditEntity(c *gin.Context, audit *models.Audit) error { c.JSON(http.StatusNotFound, er) return err } + } else if audit.Type == "obligationType" || audit.Type == "ObligationType" { + audit.Entity = &models.ObligationType{} + if err := db.DB.Where(&models.ObligationType{Id: audit.TypeId}).First(&audit.Entity).Error; err != nil { + er := models.LicenseError{ + Status: http.StatusNotFound, + Message: "obligation type corresponding with this audit does not exist", + Error: err.Error(), + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusNotFound, er) + return err + } } return nil }