From 88fcbfe1a5067f121ff341dceb9ca1d6a04e2dff Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 2 Nov 2025 20:59:25 +0300 Subject: [PATCH 01/11] routes + repo fix --- internal/api/user/controller.go | 8 ++++---- internal/api/user/repository.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/api/user/controller.go b/internal/api/user/controller.go index 212865a..48128f6 100644 --- a/internal/api/user/controller.go +++ b/internal/api/user/controller.go @@ -26,10 +26,10 @@ func newController(service *service, utils interfaces.Utils) *controller { func (h *Handler) RegisterRoutes(r *gin.RouterGroup, authMW gin.HandlerFunc, refreshMW gin.HandlerFunc) { userGroup := r.Group("/user") - userGroup.POST("/", h.controller.register) - userGroup.GET("/", authMW, h.controller.get) - userGroup.PUT("/", authMW, h.controller.update) - userGroup.DELETE("/", authMW, h.controller.delete) + userGroup.POST("", h.controller.register) + userGroup.GET("", authMW, h.controller.get) + userGroup.PUT("", authMW, h.controller.update) + userGroup.DELETE("", authMW, h.controller.delete) //auth h.controller.authPath = fmt.Sprintf("%s/user/auth", h.apiPrefix) diff --git a/internal/api/user/repository.go b/internal/api/user/repository.go index 87d2b2d..4b0b754 100644 --- a/internal/api/user/repository.go +++ b/internal/api/user/repository.go @@ -40,7 +40,7 @@ func (r *repo) getByUuid(userUuid string) (user User, err error) { } func (r *repo) update(user map[string]any) error { - return r.db.Where("uuid = ?", user["uuid"]).Updates(&user).Error + return r.db.Model(&User{}).Where("uuid = ?", user["uuid"]).Updates(&user).Error } func (r *repo) delete(userUuid string) error { From 93ce93770d3c37d59e238028eef64560cd69a723 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 2 Nov 2025 21:10:49 +0300 Subject: [PATCH 02/11] zero prices check added --- internal/api/merch/controller.go | 81 +++++++++++++++++++++++++++++++- internal/api/merch/dto.go | 13 +++++ internal/api/merch/model.go | 4 +- internal/api/merch/repository.go | 43 +++++++++++++++++ internal/api/merch/service.go | 8 ++++ 5 files changed, 146 insertions(+), 3 deletions(-) diff --git a/internal/api/merch/controller.go b/internal/api/merch/controller.go index 41a6983..63b28f2 100644 --- a/internal/api/merch/controller.go +++ b/internal/api/merch/controller.go @@ -27,7 +27,6 @@ func newController(service *service, utils interfaces.Utils, expires time.Durati func (h *Handler) RegisterRoutes(r *gin.RouterGroup, authMW gin.HandlerFunc, refreshMW gin.HandlerFunc) { merchGroup := r.Group("/merch", authMW) - merchGroup.POST("/", h.controller.addMerch) merchGroup.GET("/:uuid", h.controller.getSingleMerch) merchGroup.GET("/", h.controller.getAllMerch) @@ -51,6 +50,10 @@ func (h *Handler) RegisterRoutes(r *gin.RouterGroup, authMW gin.HandlerFunc, ref labelsGroup.POST("/attach", h.controller.attachLabel) labelsGroup.POST("/detach", h.controller.detachLabel) labelsGroup.GET("/:uuid", h.controller.getMerchLabels) + + zeroPricesGroup := merchGroup.Group("/zeroprices", authMW) + zeroPricesGroup.GET("", h.controller.getZeroPrices) + zeroPricesGroup.DELETE("", h.controller.deleteZeroPrices) } // @Summary Добавить новый мерч @@ -92,6 +95,7 @@ func (co *controller) addMerch(c *gin.Context) { // @Description Получить всю информацию про мерч по его uuid // @Tags Merch // @Security BearerAuth +// @Produce json // @Param uuid path string true "merch_uuid" // @Success 200 {object} MerchDTO // @Failure 400 {object} responses.ErrorResponse400 @@ -125,6 +129,7 @@ func (co *controller) getSingleMerch(c *gin.Context) { // @Description Получить все записи мерча // @Tags Merch // @Security BearerAuth +// @Produce json // @Success 200 {array} ListResponse // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 @@ -151,6 +156,7 @@ func (co *controller) getAllMerch(c *gin.Context) { // @Description Обновить информацию про мерч по его uuid в json-е // @Tags Merch // @Security BearerAuth +// Accept json // @Param body body UpdateMerchDTO true "merch_uuid" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -214,6 +220,7 @@ func (co *controller) deleteMerch(c *gin.Context) { // @Description Получить цены мерча за период // @Tags Merch // @Security BearerAuth +// @Produce json // @Param days query string false "period in days" // @Success 200 {array} PricesResponse // @Failure 400 {object} responses.ErrorResponse400 @@ -243,6 +250,7 @@ func (co *controller) getChartsPrices(c *gin.Context) { // @Description Получить перепады цен мерча за период по его merch_uuid // @Tags Merch // @Security BearerAuth +// @Produce json // @Param uuid path string true "merch_uuid" // @Param days query string false "period in days" // @Success 200 {object} PricesResponse @@ -338,6 +346,7 @@ func (co *controller) uploadMerchImage(c *gin.Context) { // @Description Получить картинки по merch_uuid и query параметрам // @Tags Merch images // @Security BearerAuth +// @Produce json // @Param uuid path string true "merch_uuid" // @Param type query string true "image type" // @Success 200 {object} ImageLink @@ -429,6 +438,7 @@ func (co *controller) deleteMerchImage(c *gin.Context) { // @Description Создать новую метку для товара // @Tags Merch labels // @Security BearerAuth +// Accept json // @Param payload body LabelDTO true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -464,6 +474,7 @@ func (co *controller) createLabel(c *gin.Context) { // @Description Получить все метки товаров // @Tags Merch labels // @Security BearerAuth +// @Produce json // @Success 200 {array} LabelsList // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 @@ -492,6 +503,7 @@ func (co *controller) getLabels(c *gin.Context) { // @Description Изменить метку // @Tags Merch labels // @Security BearerAuth +// Accept json // @Param uuid path string true "label uuid" // @Param payload body LabelDTO true "payload" // @Success 200 @@ -568,6 +580,7 @@ func (co *controller) deleteLabel(c *gin.Context) { // @Description Прикрепить метку к товару // @Tags Merch labels // @Security BearerAuth +// Accept json // @Param payload body LabelLink true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -602,6 +615,7 @@ func (co *controller) attachLabel(c *gin.Context) { // @Description Удалить привязку метки к товару // @Tags Merch labels // @Security BearerAuth +// Accept json // @Param payload body LabelLink true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -636,6 +650,7 @@ func (co *controller) detachLabel(c *gin.Context) { // @Description Получить метки товара по его uuid // @Tags Merch labels // @Security BearerAuth +// @Produce json // @Param uuid path string true "label uuid" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -666,3 +681,67 @@ func (co *controller) getMerchLabels(c *gin.Context) { } c.JSON(http.StatusOK, response) } + +// @Summary Получить нулевые цены +// @Description Получить нулевые цены +// @Tags Merch zero prices +// @Security BearerAuth +// @Produce json +// @Success 200 {array} ZeroPrice +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/zeroprices [get] +func (co *controller) getZeroPrices(c *gin.Context) { + const logMsg = "Merch | Get zero prices" + + userUuid, err := co.utils.GetUserUuidFromContext(c) + if err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + response, err := co.service.getZeroPrices(userUuid) + if err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + c.JSON(http.StatusOK, response) +} + +// @Summary Пометить нулевые цены как удаленные +// @Description Пометить нулевые цены как удаленные +// @Tags Merch zero prices +// @Security BearerAuth +// Accept json +// @Param payload body DeleteZeroPrices true "payload" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/zeroprices [delete] +func (co *controller) deleteZeroPrices(c *gin.Context) { + const logMsg = "Merch | Delete zero prices" + + userUuid, err := co.utils.GetUserUuidFromContext(c) + if err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + var payload DeleteZeroPrices + if err = c.ShouldBindJSON(&payload); err != nil { + c.JSON(http.StatusBadRequest, responses.ErrorResponse400{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + if err = co.service.deleteZeroPrices(userUuid, payload); err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + c.Status(http.StatusOK) +} diff --git a/internal/api/merch/dto.go b/internal/api/merch/dto.go index 2f267b1..b10aa6b 100644 --- a/internal/api/merch/dto.go +++ b/internal/api/merch/dto.go @@ -1,5 +1,7 @@ package merch +import "time" + type merchBundle struct { Merch *Merch Surugaya *Surugaya @@ -78,3 +80,14 @@ type LabelLink struct { MerchUuid string `json:"merch_uuid"` LabelUuid string `json:"label_uuid"` } + +type ZeroPrice struct { + CreatedAt time.Time `json:"created_at"` + MerchUuid string `json:"merch_uuid"` + Name string `json:"name"` + Origin string `json:"origin"` +} + +type DeleteZeroPrices struct { + MerchUuids []string `json:"merch_uuids"` +} diff --git a/internal/api/merch/model.go b/internal/api/merch/model.go index 935a194..2dd6e0e 100644 --- a/internal/api/merch/model.go +++ b/internal/api/merch/model.go @@ -44,8 +44,8 @@ func (Mandarake) TableName() string { type Price struct { Id uint `json:"id" gorm:"primary_key"` CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` - UpdatedAt sql.NullTime `json:"updated_at" gorm:"column:updated_at"` - DeletedAt sql.NullTime `json:"deleted_at" gorm:"column:deleted_at"` + UpdatedAt sql.NullTime `json:"updated_at,omitempty" gorm:"column:updated_at"` + DeletedAt sql.NullTime `json:"deleted_at,omitempty" gorm:"column:deleted_at"` MerchUuid string `json:"merch_uuid" gorm:"column:merch_uuid"` Price int `json:"price" gorm:"column:price"` Origin Origin `json:"origin" gorm:"column:origin;type:integer"` diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index b5ecf39..1af8df0 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -38,6 +38,9 @@ type repository interface { type prices interface { getPricesWithDays(userUuid string, period time.Time) ([]Price, error) getDistinctPrices(userUuid, merchUuid string, period time.Time) (prices []Price, err error) + + getZeroPrices(userUuid string) ([]ZeroPrice, error) + deleteZeroPrices(userUuid string, list []string) error } type labels interface { @@ -311,3 +314,43 @@ func (r *Repo) getAttachedLabelsByUuid(userUuid, merchUuid string) ([]CardLabel, return labelsList, nil } + +func (r *Repo) getZeroPrices(userUuid string) ([]ZeroPrice, error) { + var priceList []ZeroPrice + if err := r.db.Raw(` + WITH price_with_neighbors AS ( + SELECT + p.created_at, p.merch_uuid, p.price, p.origin, m.name, + LAG(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS prev_price, + LEAD(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS next_price + FROM prices AS p + JOIN merch as m ON m.merch_uuid = p.merch_uuid + WHERE p.deleted_at IS NULL + AND m.user_uuid = ?) + + SELECT + created_at, merch_uuid, origin, name + FROM price_with_neighbors + WHERE + price = 0 + AND prev_price IS NOT NULL + AND prev_price > 0 + AND next_price IS NOT NULL + AND next_price > 0; + `, userUuid).Scan(&priceList).Error; err != nil { + return nil, err + } + return priceList, nil +} + +func (r *Repo) deleteZeroPrices(userUuid string, list []string) error { + subQuery := r.db.Table("merch"). + Select("merch_uuid"). + Where("user_uuid = ?", userUuid) + + return r.db.Model(&Price{}). + Where("merch_uuid IN ?", list). + Where("merch_uuid IN (?)", subQuery). + Update("deleted_at", time.Now().UTC()). + Error +} diff --git a/internal/api/merch/service.go b/internal/api/merch/service.go index 4689453..259563d 100644 --- a/internal/api/merch/service.go +++ b/internal/api/merch/service.go @@ -612,3 +612,11 @@ func (s *service) getMerchLabels(userUuid, merchUuid string) ([]string, error) { return response, nil } + +func (s *service) getZeroPrices(userUuid string) ([]ZeroPrice, error) { + return s.repo.getZeroPrices(userUuid) +} + +func (s *service) deleteZeroPrices(userUuid string, list DeleteZeroPrices) error { + return s.repo.deleteZeroPrices(userUuid, list.MerchUuids) +} From a0e21db5a09e7e13d026611c1f068ca27fbe9ed1 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 2 Nov 2025 21:10:59 +0300 Subject: [PATCH 03/11] swagger docs update --- docs/docs.go | 179 ++++++++++++++++++++++++++++++++++++++++++++++ docs/swagger.json | 179 ++++++++++++++++++++++++++++++++++++++++++++++ docs/swagger.yaml | 114 +++++++++++++++++++++++++++++ 3 files changed, 472 insertions(+) diff --git a/docs/docs.go b/docs/docs.go index 0111bc4..b668308 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -68,6 +68,9 @@ const docTemplate = `{ } ], "description": "Получить все записи мерча", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -145,6 +148,9 @@ const docTemplate = `{ } ], "description": "Получить картинки по merch_uuid и query параметрам", + "produces": [ + "application/json" + ], "tags": [ "Merch images" ], @@ -287,6 +293,9 @@ const docTemplate = `{ } ], "description": "Получить все метки товаров", + "produces": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -441,6 +450,47 @@ const docTemplate = `{ } }, "/merch/labels/{uuid}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Получить метки товара по его uuid", + "produces": [ + "application/json" + ], + "tags": [ + "Merch labels" + ], + "summary": "Получить метки товара по его uuid", + "parameters": [ + { + "type": "string", + "description": "label uuid", + "name": "uuid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + }, "put": { "security": [ { @@ -527,6 +577,86 @@ const docTemplate = `{ } } }, + "/merch/zeroprices": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Получить нулевые цены", + "produces": [ + "application/json" + ], + "tags": [ + "Merch zero prices" + ], + "summary": "Получить нулевые цены", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/merch.ZeroPrice" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Пометить нулевые цены как удаленные", + "tags": [ + "Merch zero prices" + ], + "summary": "Пометить нулевые цены как удаленные", + "parameters": [ + { + "description": "payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/merch.DeleteZeroPrices" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + } + }, "/merch/{uuid}": { "get": { "security": [ @@ -535,6 +665,9 @@ const docTemplate = `{ } ], "description": "Получить всю информацию про мерч по его uuid", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -619,6 +752,9 @@ const docTemplate = `{ } ], "description": "Получить цены мерча за период", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -664,6 +800,9 @@ const docTemplate = `{ } ], "description": "Получить перепады цен мерча за период по его merch_uuid", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -1018,6 +1157,17 @@ const docTemplate = `{ } } }, + "merch.DeleteZeroPrices": { + "type": "object", + "properties": { + "merch_uuids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, "merch.ImageLink": { "type": "object", "properties": { @@ -1074,6 +1224,12 @@ const docTemplate = `{ "merch.ListResponse": { "type": "object", "properties": { + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, "merch_uuid": { "type": "string" }, @@ -1093,6 +1249,12 @@ const docTemplate = `{ "merch.MerchDTO": { "type": "object", "properties": { + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, "merch_uuid": { "type": "string" }, @@ -1174,6 +1336,23 @@ const docTemplate = `{ } } }, + "merch.ZeroPrice": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "merch_uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "origin": { + "type": "string" + } + } + }, "responses.ErrorResponse400": { "type": "object", "properties": { diff --git a/docs/swagger.json b/docs/swagger.json index 7b17bd7..0df1704 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -60,6 +60,9 @@ } ], "description": "Получить все записи мерча", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -137,6 +140,9 @@ } ], "description": "Получить картинки по merch_uuid и query параметрам", + "produces": [ + "application/json" + ], "tags": [ "Merch images" ], @@ -279,6 +285,9 @@ } ], "description": "Получить все метки товаров", + "produces": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -433,6 +442,47 @@ } }, "/merch/labels/{uuid}": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Получить метки товара по его uuid", + "produces": [ + "application/json" + ], + "tags": [ + "Merch labels" + ], + "summary": "Получить метки товара по его uuid", + "parameters": [ + { + "type": "string", + "description": "label uuid", + "name": "uuid", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + }, "put": { "security": [ { @@ -519,6 +569,86 @@ } } }, + "/merch/zeroprices": { + "get": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Получить нулевые цены", + "produces": [ + "application/json" + ], + "tags": [ + "Merch zero prices" + ], + "summary": "Получить нулевые цены", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/merch.ZeroPrice" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + }, + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Пометить нулевые цены как удаленные", + "tags": [ + "Merch zero prices" + ], + "summary": "Пометить нулевые цены как удаленные", + "parameters": [ + { + "description": "payload", + "name": "payload", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/merch.DeleteZeroPrices" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + } + }, "/merch/{uuid}": { "get": { "security": [ @@ -527,6 +657,9 @@ } ], "description": "Получить всю информацию про мерч по его uuid", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -611,6 +744,9 @@ } ], "description": "Получить цены мерча за период", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -656,6 +792,9 @@ } ], "description": "Получить перепады цен мерча за период по его merch_uuid", + "produces": [ + "application/json" + ], "tags": [ "Merch" ], @@ -1010,6 +1149,17 @@ } } }, + "merch.DeleteZeroPrices": { + "type": "object", + "properties": { + "merch_uuids": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, "merch.ImageLink": { "type": "object", "properties": { @@ -1066,6 +1216,12 @@ "merch.ListResponse": { "type": "object", "properties": { + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, "merch_uuid": { "type": "string" }, @@ -1085,6 +1241,12 @@ "merch.MerchDTO": { "type": "object", "properties": { + "labels": { + "type": "array", + "items": { + "type": "string" + } + }, "merch_uuid": { "type": "string" }, @@ -1166,6 +1328,23 @@ } } }, + "merch.ZeroPrice": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "merch_uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "origin": { + "type": "string" + } + } + }, "responses.ErrorResponse400": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 3dadf18..fd4e41b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -7,6 +7,13 @@ definitions: thumbnail: type: string type: object + merch.DeleteZeroPrices: + properties: + merch_uuids: + items: + type: string + type: array + type: object merch.ImageLink: properties: etag: @@ -43,6 +50,10 @@ definitions: type: object merch.ListResponse: properties: + labels: + items: + type: string + type: array merch_uuid: type: string name: @@ -55,6 +66,10 @@ definitions: type: object merch.MerchDTO: properties: + labels: + items: + type: string + type: array merch_uuid: type: string name: @@ -107,6 +122,17 @@ definitions: origin: type: string type: object + merch.ZeroPrice: + properties: + created_at: + type: string + merch_uuid: + type: string + name: + type: string + origin: + type: string + type: object responses.ErrorResponse400: properties: error: @@ -205,6 +231,8 @@ paths: /merch/: get: description: Получить все записи мерча + produces: + - application/json responses: "200": description: OK @@ -285,6 +313,8 @@ paths: name: uuid required: true type: string + produces: + - application/json responses: "200": description: OK @@ -341,6 +371,8 @@ paths: name: type required: true type: string + produces: + - application/json responses: "200": description: OK @@ -398,6 +430,8 @@ paths: /merch/labels: get: description: Получить все метки товаров + produces: + - application/json responses: "200": description: OK @@ -468,6 +502,32 @@ paths: summary: Пометить метку как удаленную tags: - Merch labels + get: + description: Получить метки товара по его uuid + parameters: + - description: label uuid + in: path + name: uuid + required: true + type: string + produces: + - application/json + responses: + "200": + description: OK + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.ErrorResponse400' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.ErrorResponse500' + security: + - BearerAuth: [] + summary: Получить метки товара по его uuid + tags: + - Merch labels put: description: Изменить метку parameters: @@ -550,6 +610,56 @@ paths: summary: Удалить привязку метки к товару tags: - Merch labels + /merch/zeroprices: + delete: + description: Пометить нулевые цены как удаленные + parameters: + - description: payload + in: body + name: payload + required: true + schema: + $ref: '#/definitions/merch.DeleteZeroPrices' + responses: + "200": + description: OK + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.ErrorResponse400' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.ErrorResponse500' + security: + - BearerAuth: [] + summary: Пометить нулевые цены как удаленные + tags: + - Merch zero prices + get: + description: Получить нулевые цены + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/merch.ZeroPrice' + type: array + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.ErrorResponse400' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.ErrorResponse500' + security: + - BearerAuth: [] + summary: Получить нулевые цены + tags: + - Merch zero prices /prices: get: description: Получить цены мерча за период @@ -558,6 +668,8 @@ paths: in: query name: days type: string + produces: + - application/json responses: "200": description: OK @@ -591,6 +703,8 @@ paths: in: query name: days type: string + produces: + - application/json responses: "200": description: OK From 2728051fdeed24f957dae3e96a1bc0192be022b6 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 2 Nov 2025 23:27:23 +0300 Subject: [PATCH 04/11] fixes --- internal/api/merch/controller.go | 2 +- internal/api/merch/dto.go | 4 ++- internal/api/merch/repository.go | 44 ++++++++++++++++++++++---------- internal/api/merch/service.go | 25 ++++++++++++++++-- 4 files changed, 58 insertions(+), 17 deletions(-) diff --git a/internal/api/merch/controller.go b/internal/api/merch/controller.go index 63b28f2..33c194f 100644 --- a/internal/api/merch/controller.go +++ b/internal/api/merch/controller.go @@ -731,7 +731,7 @@ func (co *controller) deleteZeroPrices(c *gin.Context) { return } - var payload DeleteZeroPrices + var payload []DeleteZeroPrices if err = c.ShouldBindJSON(&payload); err != nil { c.JSON(http.StatusBadRequest, responses.ErrorResponse400{Error: err.Error()}) log.WithError(err).Error(logMsg) diff --git a/internal/api/merch/dto.go b/internal/api/merch/dto.go index b10aa6b..7ee7281 100644 --- a/internal/api/merch/dto.go +++ b/internal/api/merch/dto.go @@ -82,6 +82,7 @@ type LabelLink struct { } type ZeroPrice struct { + Id int `json:"id"` CreatedAt time.Time `json:"created_at"` MerchUuid string `json:"merch_uuid"` Name string `json:"name"` @@ -89,5 +90,6 @@ type ZeroPrice struct { } type DeleteZeroPrices struct { - MerchUuids []string `json:"merch_uuids"` + Id uint `json:"id"` + MerchUuid string `json:"merch_uuid"` } diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index 1af8df0..711b731 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -3,6 +3,7 @@ package merch import ( "database/sql" "errors" + "fmt" "gorm.io/gorm" "gorm.io/gorm/clause" "time" @@ -22,6 +23,7 @@ type repository interface { addMerch(bundle merchBundle) error merchRecordExists(userUuid, merchUuid string) (bool, error) + userOwnsMerchUuids(userUuid string, merchUuids []string) (bool, error) getSingleMerch(userUuid, merchUuid string) (merchBundle, error) getAllMerch(userUuid string) ([]ListResponse, error) @@ -40,7 +42,7 @@ type prices interface { getDistinctPrices(userUuid, merchUuid string, period time.Time) (prices []Price, err error) getZeroPrices(userUuid string) ([]ZeroPrice, error) - deleteZeroPrices(userUuid string, list []string) error + deleteZeroPrices(list []DeleteZeroPrices) error } type labels interface { @@ -84,6 +86,22 @@ func (r *Repo) merchRecordExists(userUuid, merchUuid string) (bool, error) { return exists, err } +func (r *Repo) userOwnsMerchUuids(userUuid string, merchUuids []string) (bool, error) { + var count int64 + + err := r.db.Model(&Merch{}). + Where("user_uuid = ?", userUuid). + Where("merch_uuid IN ?", merchUuids). + Where("deleted_at IS NULL"). + Count(&count).Error + fmt.Println("!!!!!!", count) + if err != nil { + return false, err + } + fmt.Println("!!!!!!", len(merchUuids)) + return count == int64(len(merchUuids)), nil +} + func (r *Repo) getSingleMerch(userUuid, merchUuid string) (merchBundle, error) { var merch Merch if err := r.db. @@ -320,16 +338,17 @@ func (r *Repo) getZeroPrices(userUuid string) ([]ZeroPrice, error) { if err := r.db.Raw(` WITH price_with_neighbors AS ( SELECT - p.created_at, p.merch_uuid, p.price, p.origin, m.name, + p.id, p.created_at, p.merch_uuid, p.price, p.origin, m.name, LAG(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS prev_price, LEAD(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS next_price FROM prices AS p JOIN merch as m ON m.merch_uuid = p.merch_uuid WHERE p.deleted_at IS NULL + AND m.deleted_at IS NULL AND m.user_uuid = ?) SELECT - created_at, merch_uuid, origin, name + id, created_at, merch_uuid, origin, name FROM price_with_neighbors WHERE price = 0 @@ -343,14 +362,13 @@ func (r *Repo) getZeroPrices(userUuid string) ([]ZeroPrice, error) { return priceList, nil } -func (r *Repo) deleteZeroPrices(userUuid string, list []string) error { - subQuery := r.db.Table("merch"). - Select("merch_uuid"). - Where("user_uuid = ?", userUuid) - - return r.db.Model(&Price{}). - Where("merch_uuid IN ?", list). - Where("merch_uuid IN (?)", subQuery). - Update("deleted_at", time.Now().UTC()). - Error +func (r *Repo) deleteZeroPrices(list []DeleteZeroPrices) error { + for _, item := range list { + if err := r.db.Model(&Price{}). + Where("id = ? AND merch_uuid = ?", item.Id, item.MerchUuid). + Update("deleted_at", time.Now().UTC()).Error; err != nil { + return err + } + } + return nil } diff --git a/internal/api/merch/service.go b/internal/api/merch/service.go index 259563d..4d06a37 100644 --- a/internal/api/merch/service.go +++ b/internal/api/merch/service.go @@ -16,6 +16,7 @@ import ( is "merch-parser-api/proto/imageStorage" "mime/multipart" "path/filepath" + "slices" "strings" "time" ) @@ -617,6 +618,26 @@ func (s *service) getZeroPrices(userUuid string) ([]ZeroPrice, error) { return s.repo.getZeroPrices(userUuid) } -func (s *service) deleteZeroPrices(userUuid string, list DeleteZeroPrices) error { - return s.repo.deleteZeroPrices(userUuid, list.MerchUuids) +func (s *service) deleteZeroPrices(userUuid string, list []DeleteZeroPrices) error { + if len(list) == 0 { + return nil + } + + ids := make([]string, 0, len(list)) + for _, item := range list { + ids = append(ids, item.MerchUuid) + fmt.Println(item.MerchUuid, ids) + } + slices.Compact(ids) + + owns, err := s.repo.userOwnsMerchUuids(userUuid, ids) + if err != nil { + return err + } + + if !owns { + return errors.New("wrong ids") + } + + return s.repo.deleteZeroPrices(list) } From 7fa79d770a20293799485e76c55fb66f4ca73f6f Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 2 Nov 2025 23:39:25 +0300 Subject: [PATCH 05/11] swagger docs update --- docs/docs.go | 31 ++++++++++-- docs/swagger.json | 31 ++++++++++-- docs/swagger.yaml | 22 +++++++-- internal/api/merch/controller.go | 84 +++++++++++++++++--------------- 4 files changed, 114 insertions(+), 54 deletions(-) diff --git a/docs/docs.go b/docs/docs.go index b668308..b97688b 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -106,6 +106,9 @@ const docTemplate = `{ } ], "description": "Обновить информацию про мерч по его uuid в json-е", + "consumes": [ + "application/json" + ], "tags": [ "Merch" ], @@ -331,6 +334,9 @@ const docTemplate = `{ } ], "description": "Создать новую метку для товара", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -373,6 +379,9 @@ const docTemplate = `{ } ], "description": "Прикрепить метку к товару", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -415,6 +424,9 @@ const docTemplate = `{ } ], "description": "Удалить привязку метки к товару", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -498,6 +510,9 @@ const docTemplate = `{ } ], "description": "Изменить метку", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -623,6 +638,9 @@ const docTemplate = `{ } ], "description": "Пометить нулевые цены как удаленные", + "consumes": [ + "application/json" + ], "tags": [ "Merch zero prices" ], @@ -1160,11 +1178,11 @@ const docTemplate = `{ "merch.DeleteZeroPrices": { "type": "object", "properties": { - "merch_uuids": { - "type": "array", - "items": { - "type": "string" - } + "id": { + "type": "integer" + }, + "merch_uuid": { + "type": "string" } } }, @@ -1342,6 +1360,9 @@ const docTemplate = `{ "created_at": { "type": "string" }, + "id": { + "type": "integer" + }, "merch_uuid": { "type": "string" }, diff --git a/docs/swagger.json b/docs/swagger.json index 0df1704..f746266 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -98,6 +98,9 @@ } ], "description": "Обновить информацию про мерч по его uuid в json-е", + "consumes": [ + "application/json" + ], "tags": [ "Merch" ], @@ -323,6 +326,9 @@ } ], "description": "Создать новую метку для товара", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -365,6 +371,9 @@ } ], "description": "Прикрепить метку к товару", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -407,6 +416,9 @@ } ], "description": "Удалить привязку метки к товару", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -490,6 +502,9 @@ } ], "description": "Изменить метку", + "consumes": [ + "application/json" + ], "tags": [ "Merch labels" ], @@ -615,6 +630,9 @@ } ], "description": "Пометить нулевые цены как удаленные", + "consumes": [ + "application/json" + ], "tags": [ "Merch zero prices" ], @@ -1152,11 +1170,11 @@ "merch.DeleteZeroPrices": { "type": "object", "properties": { - "merch_uuids": { - "type": "array", - "items": { - "type": "string" - } + "id": { + "type": "integer" + }, + "merch_uuid": { + "type": "string" } } }, @@ -1334,6 +1352,9 @@ "created_at": { "type": "string" }, + "id": { + "type": "integer" + }, "merch_uuid": { "type": "string" }, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index fd4e41b..883b177 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -9,10 +9,10 @@ definitions: type: object merch.DeleteZeroPrices: properties: - merch_uuids: - items: - type: string - type: array + id: + type: integer + merch_uuid: + type: string type: object merch.ImageLink: properties: @@ -126,6 +126,8 @@ definitions: properties: created_at: type: string + id: + type: integer merch_uuid: type: string name: @@ -254,6 +256,8 @@ paths: tags: - Merch put: + consumes: + - application/json description: Обновить информацию про мерч по его uuid в json-е parameters: - description: merch_uuid @@ -453,6 +457,8 @@ paths: tags: - Merch labels post: + consumes: + - application/json description: Создать новую метку для товара parameters: - description: payload @@ -529,6 +535,8 @@ paths: tags: - Merch labels put: + consumes: + - application/json description: Изменить метку parameters: - description: label uuid @@ -560,6 +568,8 @@ paths: - Merch labels /merch/labels/attach: post: + consumes: + - application/json description: Прикрепить метку к товару parameters: - description: payload @@ -586,6 +596,8 @@ paths: - Merch labels /merch/labels/detach: post: + consumes: + - application/json description: Удалить привязку метки к товару parameters: - description: payload @@ -612,6 +624,8 @@ paths: - Merch labels /merch/zeroprices: delete: + consumes: + - application/json description: Пометить нулевые цены как удаленные parameters: - description: payload diff --git a/internal/api/merch/controller.go b/internal/api/merch/controller.go index 33c194f..7ea9636 100644 --- a/internal/api/merch/controller.go +++ b/internal/api/merch/controller.go @@ -95,7 +95,7 @@ func (co *controller) addMerch(c *gin.Context) { // @Description Получить всю информацию про мерч по его uuid // @Tags Merch // @Security BearerAuth -// @Produce json +// @Produce json // @Param uuid path string true "merch_uuid" // @Success 200 {object} MerchDTO // @Failure 400 {object} responses.ErrorResponse400 @@ -129,7 +129,7 @@ func (co *controller) getSingleMerch(c *gin.Context) { // @Description Получить все записи мерча // @Tags Merch // @Security BearerAuth -// @Produce json +// @Produce json // @Success 200 {array} ListResponse // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 @@ -156,7 +156,7 @@ func (co *controller) getAllMerch(c *gin.Context) { // @Description Обновить информацию про мерч по его uuid в json-е // @Tags Merch // @Security BearerAuth -// Accept json +// @Accept json // @Param body body UpdateMerchDTO true "merch_uuid" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -182,6 +182,7 @@ func (co *controller) updateMerch(c *gin.Context) { log.WithError(err).Error("Merch | Failed to get single merch") return } + c.Status(http.StatusOK) } // @Summary Пометить мерч как удаленный @@ -192,7 +193,8 @@ func (co *controller) updateMerch(c *gin.Context) { // @Success 200 {object} MerchDTO // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 -// @Router /merch/{uuid} [delete] +// +// @Router /merch/{uuid} [delete] func (co *controller) deleteMerch(c *gin.Context) { merchUuid := c.Param("uuid") if merchUuid == "" { @@ -220,12 +222,16 @@ func (co *controller) deleteMerch(c *gin.Context) { // @Description Получить цены мерча за период // @Tags Merch // @Security BearerAuth -// @Produce json +// @Produce json // @Param days query string false "period in days" // @Success 200 {array} PricesResponse // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 // @Router /prices [get] +// +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /prices [get] func (co *controller) getChartsPrices(c *gin.Context) { daysQuery := strings.ToLower(c.DefaultQuery("days", "")) @@ -250,7 +256,7 @@ func (co *controller) getChartsPrices(c *gin.Context) { // @Description Получить перепады цен мерча за период по его merch_uuid // @Tags Merch // @Security BearerAuth -// @Produce json +// @Produce json // @Param uuid path string true "merch_uuid" // @Param days query string false "period in days" // @Success 200 {object} PricesResponse @@ -338,7 +344,6 @@ func (co *controller) uploadMerchImage(c *gin.Context) { return } - //c.Status(http.StatusOK) c.JSON(http.StatusOK, response) } @@ -346,7 +351,7 @@ func (co *controller) uploadMerchImage(c *gin.Context) { // @Description Получить картинки по merch_uuid и query параметрам // @Tags Merch images // @Security BearerAuth -// @Produce json +// @Produce json // @Param uuid path string true "merch_uuid" // @Param type query string true "image type" // @Success 200 {object} ImageLink @@ -393,7 +398,6 @@ func (co *controller) getMerchImage(c *gin.Context) { //} // //c.JSON(http.StatusOK, link) - c.JSON(http.StatusNotImplemented, gin.H{"msg": "Method deprecated. Request images from image storage."}) } // @Summary Удалить (безвозвратно) картинки по merch_uuid @@ -438,7 +442,7 @@ func (co *controller) deleteMerchImage(c *gin.Context) { // @Description Создать новую метку для товара // @Tags Merch labels // @Security BearerAuth -// Accept json +// @Accept json // @Param payload body LabelDTO true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -474,7 +478,7 @@ func (co *controller) createLabel(c *gin.Context) { // @Description Получить все метки товаров // @Tags Merch labels // @Security BearerAuth -// @Produce json +// @Produce json // @Success 200 {array} LabelsList // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 @@ -503,7 +507,7 @@ func (co *controller) getLabels(c *gin.Context) { // @Description Изменить метку // @Tags Merch labels // @Security BearerAuth -// Accept json +// @Accept json // @Param uuid path string true "label uuid" // @Param payload body LabelDTO true "payload" // @Success 200 @@ -576,16 +580,16 @@ func (co *controller) deleteLabel(c *gin.Context) { c.Status(http.StatusOK) } -// @Summary Прикрепить метку к товару -// @Description Прикрепить метку к товару -// @Tags Merch labels -// @Security BearerAuth -// Accept json -// @Param payload body LabelLink true "payload" -// @Success 200 -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 -// @Router /merch/labels/attach [post] +// @Summary Прикрепить метку к товару +// @Description Прикрепить метку к товару +// @Tags Merch labels +// @Security BearerAuth +// @Accept json +// @Param payload body LabelLink true "payload" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/labels/attach [post] func (co *controller) attachLabel(c *gin.Context) { const logMsg = "Merch | Attach label" @@ -611,16 +615,16 @@ func (co *controller) attachLabel(c *gin.Context) { c.Status(http.StatusOK) } -// @Summary Удалить привязку метки к товару -// @Description Удалить привязку метки к товару -// @Tags Merch labels -// @Security BearerAuth -// Accept json -// @Param payload body LabelLink true "payload" -// @Success 200 -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 -// @Router /merch/labels/detach [post] +// @Summary Удалить привязку метки к товару +// @Description Удалить привязку метки к товару +// @Tags Merch labels +// @Security BearerAuth +// @Accept json +// @Param payload body LabelLink true "payload" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/labels/detach [post] func (co *controller) detachLabel(c *gin.Context) { const logMsg = "Merch | Detach label" @@ -650,7 +654,7 @@ func (co *controller) detachLabel(c *gin.Context) { // @Description Получить метки товара по его uuid // @Tags Merch labels // @Security BearerAuth -// @Produce json +// @Produce json // @Param uuid path string true "label uuid" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -686,10 +690,10 @@ func (co *controller) getMerchLabels(c *gin.Context) { // @Description Получить нулевые цены // @Tags Merch zero prices // @Security BearerAuth -// @Produce json -// @Success 200 {array} ZeroPrice -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 +// @Produce json +// @Success 200 {array} ZeroPrice +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 // @Router /merch/zeroprices [get] func (co *controller) getZeroPrices(c *gin.Context) { const logMsg = "Merch | Get zero prices" @@ -715,11 +719,11 @@ func (co *controller) getZeroPrices(c *gin.Context) { // @Description Пометить нулевые цены как удаленные // @Tags Merch zero prices // @Security BearerAuth -// Accept json +// @Accept json // @Param payload body DeleteZeroPrices true "payload" // @Success 200 -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 // @Router /merch/zeroprices [delete] func (co *controller) deleteZeroPrices(c *gin.Context) { const logMsg = "Merch | Delete zero prices" From aeb5cb819b0d0bfcd192e9c13d3951946017b7dc Mon Sep 17 00:00:00 2001 From: nquidox Date: Tue, 4 Nov 2025 16:49:04 +0300 Subject: [PATCH 06/11] =?UTF-8?q?=D1=81hanged=20ownership=20validation=20f?= =?UTF-8?q?or=20user's=20merch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/api/merch/repository.go | 21 ++++++++++---------- internal/api/merch/service.go | 33 ++++++++++++++++++++++++++------ 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index 711b731..e84f551 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -3,7 +3,6 @@ package merch import ( "database/sql" "errors" - "fmt" "gorm.io/gorm" "gorm.io/gorm/clause" "time" @@ -23,7 +22,7 @@ type repository interface { addMerch(bundle merchBundle) error merchRecordExists(userUuid, merchUuid string) (bool, error) - userOwnsMerchUuids(userUuid string, merchUuids []string) (bool, error) + userOwnsMerchUuids(userUuid string, merchUuids []string) ([]Merch, error) getSingleMerch(userUuid, merchUuid string) (merchBundle, error) getAllMerch(userUuid string) ([]ListResponse, error) @@ -86,20 +85,20 @@ func (r *Repo) merchRecordExists(userUuid, merchUuid string) (bool, error) { return exists, err } -func (r *Repo) userOwnsMerchUuids(userUuid string, merchUuids []string) (bool, error) { - var count int64 - +func (r *Repo) userOwnsMerchUuids(userUuid string, merchUuids []string) ([]Merch, error) { + var ownsUuids []Merch err := r.db.Model(&Merch{}). + Select("merch_uuid"). Where("user_uuid = ?", userUuid). - Where("merch_uuid IN ?", merchUuids). + Where("merch_uuid IN (?)", merchUuids). Where("deleted_at IS NULL"). - Count(&count).Error - fmt.Println("!!!!!!", count) + Find(&ownsUuids).Error + if err != nil { - return false, err + return nil, err } - fmt.Println("!!!!!!", len(merchUuids)) - return count == int64(len(merchUuids)), nil + + return ownsUuids, nil } func (r *Repo) getSingleMerch(userUuid, merchUuid string) (merchBundle, error) { diff --git a/internal/api/merch/service.go b/internal/api/merch/service.go index 4d06a37..d409b71 100644 --- a/internal/api/merch/service.go +++ b/internal/api/merch/service.go @@ -16,7 +16,6 @@ import ( is "merch-parser-api/proto/imageStorage" "mime/multipart" "path/filepath" - "slices" "strings" "time" ) @@ -619,6 +618,7 @@ func (s *service) getZeroPrices(userUuid string) ([]ZeroPrice, error) { } func (s *service) deleteZeroPrices(userUuid string, list []DeleteZeroPrices) error { + const delMsg = "Merch - service | Delete zero prices" if len(list) == 0 { return nil } @@ -626,18 +626,39 @@ func (s *service) deleteZeroPrices(userUuid string, list []DeleteZeroPrices) err ids := make([]string, 0, len(list)) for _, item := range list { ids = append(ids, item.MerchUuid) - fmt.Println(item.MerchUuid, ids) } - slices.Compact(ids) - owns, err := s.repo.userOwnsMerchUuids(userUuid, ids) + uniqueMap := make(map[string]struct{}, len(list)) + uniqueIds := make([]string, 0, len(list)) + for _, id := range ids { + if _, ok := uniqueMap[id]; !ok { + uniqueMap[id] = struct{}{} + uniqueIds = append(uniqueIds, id) + } + } + + log.WithField("uuid count", len(uniqueIds)).Debug(delMsg) + + owns, err := s.repo.userOwnsMerchUuids(userUuid, uniqueIds) if err != nil { return err } - if !owns { + if len(owns) < 1 { return errors.New("wrong ids") } - return s.repo.deleteZeroPrices(list) + ownsMap := make(map[string]struct{}, len(owns)) + for _, own := range owns { + ownsMap[own.MerchUuid] = struct{}{} + } + + toDelete := make([]DeleteZeroPrices, 0, len(owns)) + for _, item := range list { + if _, ok := ownsMap[item.MerchUuid]; ok { + toDelete = append(toDelete, item) + } + } + + return s.repo.deleteZeroPrices(toDelete) } From a338fd03b28378add0d8162217753c5dace9eb56 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sat, 6 Dec 2025 17:32:45 +0300 Subject: [PATCH 07/11] added: time util --- internal/interfaces/utils.go | 6 +++++- pkg/utils/time.go | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 pkg/utils/time.go diff --git a/internal/interfaces/utils.go b/internal/interfaces/utils.go index dd6b773..31cd891 100644 --- a/internal/interfaces/utils.go +++ b/internal/interfaces/utils.go @@ -1,6 +1,9 @@ package interfaces -import "github.com/gin-gonic/gin" +import ( + "github.com/gin-gonic/gin" + "time" +) type Utils interface { IsEmail(email string) bool @@ -8,4 +11,5 @@ type Utils interface { GetRefreshUuidFromContext(c *gin.Context) (string, error) HashPassword(password string) (string, error) ComparePasswords(hashedPassword string, plainPassword string) error + ParseTime(t string) (time.Time, error) } diff --git a/pkg/utils/time.go b/pkg/utils/time.go new file mode 100644 index 0000000..01bfaf6 --- /dev/null +++ b/pkg/utils/time.go @@ -0,0 +1,11 @@ +package utils + +import "time" + +func (u *Utils) ParseTime(t string) (time.Time, error) { + timeStr, err := time.Parse(time.RFC3339, t) + if err != nil { + return time.Time{}, err + } + return timeStr, nil +} From d997d8bfa4c0a57b68f12a36e66a1b5b3527b7b1 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sat, 6 Dec 2025 17:33:18 +0300 Subject: [PATCH 08/11] added: delete zero prices in period --- internal/api/merch/controller.go | 101 ++++++++++++++++++++++--------- internal/api/merch/repository.go | 17 ++++++ internal/api/merch/service.go | 4 ++ 3 files changed, 94 insertions(+), 28 deletions(-) diff --git a/internal/api/merch/controller.go b/internal/api/merch/controller.go index 7ea9636..a9f922a 100644 --- a/internal/api/merch/controller.go +++ b/internal/api/merch/controller.go @@ -54,6 +54,9 @@ func (h *Handler) RegisterRoutes(r *gin.RouterGroup, authMW gin.HandlerFunc, ref zeroPricesGroup := merchGroup.Group("/zeroprices", authMW) zeroPricesGroup.GET("", h.controller.getZeroPrices) zeroPricesGroup.DELETE("", h.controller.deleteZeroPrices) + + zeroPricesGroup.DELETE("/period", h.controller.deleteZeroPricesPeriod) + } // @Summary Добавить новый мерч @@ -156,7 +159,7 @@ func (co *controller) getAllMerch(c *gin.Context) { // @Description Обновить информацию про мерч по его uuid в json-е // @Tags Merch // @Security BearerAuth -// @Accept json +// @Accept json // @Param body body UpdateMerchDTO true "merch_uuid" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -194,7 +197,7 @@ func (co *controller) updateMerch(c *gin.Context) { // @Failure 400 {object} responses.ErrorResponse400 // @Failure 500 {object} responses.ErrorResponse500 // -// @Router /merch/{uuid} [delete] +// @Router /merch/{uuid} [delete] func (co *controller) deleteMerch(c *gin.Context) { merchUuid := c.Param("uuid") if merchUuid == "" { @@ -229,9 +232,9 @@ func (co *controller) deleteMerch(c *gin.Context) { // @Failure 500 {object} responses.ErrorResponse500 // @Router /prices [get] // -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 -// @Router /prices [get] +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /prices [get] func (co *controller) getChartsPrices(c *gin.Context) { daysQuery := strings.ToLower(c.DefaultQuery("days", "")) @@ -442,7 +445,7 @@ func (co *controller) deleteMerchImage(c *gin.Context) { // @Description Создать новую метку для товара // @Tags Merch labels // @Security BearerAuth -// @Accept json +// @Accept json // @Param payload body LabelDTO true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -507,7 +510,7 @@ func (co *controller) getLabels(c *gin.Context) { // @Description Изменить метку // @Tags Merch labels // @Security BearerAuth -// @Accept json +// @Accept json // @Param uuid path string true "label uuid" // @Param payload body LabelDTO true "payload" // @Success 200 @@ -580,16 +583,16 @@ func (co *controller) deleteLabel(c *gin.Context) { c.Status(http.StatusOK) } -// @Summary Прикрепить метку к товару -// @Description Прикрепить метку к товару -// @Tags Merch labels -// @Security BearerAuth -// @Accept json -// @Param payload body LabelLink true "payload" -// @Success 200 -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 -// @Router /merch/labels/attach [post] +// @Summary Прикрепить метку к товару +// @Description Прикрепить метку к товару +// @Tags Merch labels +// @Security BearerAuth +// @Accept json +// @Param payload body LabelLink true "payload" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/labels/attach [post] func (co *controller) attachLabel(c *gin.Context) { const logMsg = "Merch | Attach label" @@ -615,16 +618,16 @@ func (co *controller) attachLabel(c *gin.Context) { c.Status(http.StatusOK) } -// @Summary Удалить привязку метки к товару -// @Description Удалить привязку метки к товару -// @Tags Merch labels -// @Security BearerAuth -// @Accept json -// @Param payload body LabelLink true "payload" -// @Success 200 -// @Failure 400 {object} responses.ErrorResponse400 -// @Failure 500 {object} responses.ErrorResponse500 -// @Router /merch/labels/detach [post] +// @Summary Удалить привязку метки к товару +// @Description Удалить привязку метки к товару +// @Tags Merch labels +// @Security BearerAuth +// @Accept json +// @Param payload body LabelLink true "payload" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/labels/detach [post] func (co *controller) detachLabel(c *gin.Context) { const logMsg = "Merch | Detach label" @@ -719,7 +722,7 @@ func (co *controller) getZeroPrices(c *gin.Context) { // @Description Пометить нулевые цены как удаленные // @Tags Merch zero prices // @Security BearerAuth -// @Accept json +// @Accept json // @Param payload body DeleteZeroPrices true "payload" // @Success 200 // @Failure 400 {object} responses.ErrorResponse400 @@ -749,3 +752,45 @@ func (co *controller) deleteZeroPrices(c *gin.Context) { } c.Status(http.StatusOK) } + +// @Summary Пометить нулевые цены как удаленные за указанный период +// @Description Пометить нулевые цены как удаленные за указанный период +// @Tags Merch zero prices +// @Security BearerAuth +// @Param start query string true "start" +// @Param end query string true "end" +// @Success 200 +// @Failure 400 {object} responses.ErrorResponse400 +// @Failure 500 {object} responses.ErrorResponse500 +// @Router /merch/zeroprices/period [delete] +func (co *controller) deleteZeroPricesPeriod(c *gin.Context) { + const logMsg = "Merch | Delete zero prices period" + + userUuid, err := co.utils.GetUserUuidFromContext(c) + if err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + start, err := co.utils.ParseTime(c.Query("start")) + if err != nil { + c.JSON(http.StatusBadRequest, responses.ErrorResponse400{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + end, err := co.utils.ParseTime(c.Query("end")) + if err != nil { + c.JSON(http.StatusBadRequest, responses.ErrorResponse400{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + + if err = co.service.deleteZeroPricesPeriod(userUuid, start, end); err != nil { + c.JSON(http.StatusInternalServerError, responses.ErrorResponse500{Error: err.Error()}) + log.WithError(err).Error(logMsg) + return + } + c.Status(http.StatusOK) +} diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index e84f551..4a5f3ce 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -42,6 +42,7 @@ type prices interface { getZeroPrices(userUuid string) ([]ZeroPrice, error) deleteZeroPrices(list []DeleteZeroPrices) error + deleteZeroPricesPeriod(userUuid string, start, end time.Time) error } type labels interface { @@ -371,3 +372,19 @@ func (r *Repo) deleteZeroPrices(list []DeleteZeroPrices) error { } return nil } + +func (r *Repo) deleteZeroPricesPeriod(userUuid string, start, end time.Time) error { + if err := r.db.Exec(` + UPDATE prices + SET deleted_at = ? + FROM merch + WHERE prices.merch_uuid = merch.merch_uuid + AND merch.user_uuid = ? + AND prices.price = 0 + AND prices.deleted_at IS NULL + AND prices.created_at BETWEEN ? AND ?; + `, time.Now().UTC(), userUuid, start, end).Error; err != nil { + return err + } + return nil +} diff --git a/internal/api/merch/service.go b/internal/api/merch/service.go index d409b71..ae6c2f5 100644 --- a/internal/api/merch/service.go +++ b/internal/api/merch/service.go @@ -662,3 +662,7 @@ func (s *service) deleteZeroPrices(userUuid string, list []DeleteZeroPrices) err return s.repo.deleteZeroPrices(toDelete) } + +func (s *service) deleteZeroPricesPeriod(userUuid string, start, end time.Time) error { + return s.repo.deleteZeroPricesPeriod(userUuid, start, end) +} From f9eac067be59003f3e0bff1c4012ef732313fe00 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sat, 6 Dec 2025 17:33:29 +0300 Subject: [PATCH 09/11] swagger docs update --- docs/docs.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ docs/swagger.json | 47 +++++++++++++++++++++++++++++++++++++++++++++++ docs/swagger.yaml | 30 ++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+) diff --git a/docs/docs.go b/docs/docs.go index b97688b..a232b91 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -675,6 +675,53 @@ const docTemplate = `{ } } }, + "/merch/zeroprices/period": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Пометить нулевые цены как удаленные за указанный период", + "tags": [ + "Merch zero prices" + ], + "summary": "Пометить нулевые цены как удаленные за указанный период", + "parameters": [ + { + "type": "string", + "description": "start", + "name": "start", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "end", + "name": "end", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + } + }, "/merch/{uuid}": { "get": { "security": [ diff --git a/docs/swagger.json b/docs/swagger.json index f746266..74a0031 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -667,6 +667,53 @@ } } }, + "/merch/zeroprices/period": { + "delete": { + "security": [ + { + "BearerAuth": [] + } + ], + "description": "Пометить нулевые цены как удаленные за указанный период", + "tags": [ + "Merch zero prices" + ], + "summary": "Пометить нулевые цены как удаленные за указанный период", + "parameters": [ + { + "type": "string", + "description": "start", + "name": "start", + "in": "query", + "required": true + }, + { + "type": "string", + "description": "end", + "name": "end", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse400" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/responses.ErrorResponse500" + } + } + } + } + }, "/merch/{uuid}": { "get": { "security": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 883b177..31eaa0d 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -674,6 +674,36 @@ paths: summary: Получить нулевые цены tags: - Merch zero prices + /merch/zeroprices/period: + delete: + description: Пометить нулевые цены как удаленные за указанный период + parameters: + - description: start + in: query + name: start + required: true + type: string + - description: end + in: query + name: end + required: true + type: string + responses: + "200": + description: OK + "400": + description: Bad Request + schema: + $ref: '#/definitions/responses.ErrorResponse400' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/responses.ErrorResponse500' + security: + - BearerAuth: [] + summary: Пометить нулевые цены как удаленные за указанный период + tags: + - Merch zero prices /prices: get: description: Получить цены мерча за период From 4c59ab3f58f5f1cbe2eedf3ec5543d93cb6e385e Mon Sep 17 00:00:00 2001 From: nquidox Date: Sat, 6 Dec 2025 19:14:21 +0300 Subject: [PATCH 10/11] return origin name instead of code --- internal/api/merch/dto.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/api/merch/dto.go b/internal/api/merch/dto.go index 7ee7281..5b9180c 100644 --- a/internal/api/merch/dto.go +++ b/internal/api/merch/dto.go @@ -86,7 +86,7 @@ type ZeroPrice struct { CreatedAt time.Time `json:"created_at"` MerchUuid string `json:"merch_uuid"` Name string `json:"name"` - Origin string `json:"origin"` + Origin Origin `json:"origin"` } type DeleteZeroPrices struct { From 8f2b0470b19e9dd4b4cece4a76c8b8e22f930077 Mon Sep 17 00:00:00 2001 From: nquidox Date: Sun, 7 Dec 2025 13:37:15 +0300 Subject: [PATCH 11/11] false zero price bugfix --- internal/api/merch/repository.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/api/merch/repository.go b/internal/api/merch/repository.go index 4a5f3ce..fe5dd7d 100644 --- a/internal/api/merch/repository.go +++ b/internal/api/merch/repository.go @@ -339,8 +339,8 @@ func (r *Repo) getZeroPrices(userUuid string) ([]ZeroPrice, error) { WITH price_with_neighbors AS ( SELECT p.id, p.created_at, p.merch_uuid, p.price, p.origin, m.name, - LAG(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS prev_price, - LEAD(price) OVER (PARTITION BY p.merch_uuid ORDER BY p.created_at, p.id) AS next_price + LAG(price) OVER (PARTITION BY p.merch_uuid, p.origin ORDER BY p.created_at, p.id) AS prev_price, + LEAD(price) OVER (PARTITION BY p.merch_uuid, p.origin ORDER BY p.created_at, p.id) AS next_price FROM prices AS p JOIN merch as m ON m.merch_uuid = p.merch_uuid WHERE p.deleted_at IS NULL