From 51a401f0665dcc483c3df0565f8d7a776f0cd54c Mon Sep 17 00:00:00 2001 From: Iman Mirazimi Date: Fri, 31 May 2024 18:19:04 +0330 Subject: [PATCH] feat(niki): add `delete kind_box_req by benefactor` --- .../benefactor/kind_box_req/delete.go | 46 +++++++++++ .../benefactor/kind_box_req/route.go | 1 + docs/docs.go | 44 ++++++++++ docs/swagger.json | 44 ++++++++++ docs/swagger.yaml | 29 +++++++ internal/initial/validator.go | 1 + pkg/err_msg/message.go | 45 ++++++----- repository/mysql/kind_box_req/accept.go | 20 +++++ repository/mysql/kind_box_req/add.go | 26 ++++++ .../{kind_box_req_test.go => add_test.go} | 0 repository/mysql/kind_box_req/delete.go | 18 +++++ repository/mysql/kind_box_req/get.go | 38 +++++++++ repository/mysql/kind_box_req/get_all.go | 4 +- repository/mysql/kind_box_req/kind_box_req.go | 72 ----------------- repository/mysql/kind_box_req/reject.go | 20 +++++ repository/mysql/kind_box_req/scan.go | 2 + .../1705400111_create_kind_box_reqs_table.sql | 1 + service/benefactor/kind_box_req/delete.go | 16 ++++ service/benefactor/kind_box_req/get.go | 2 +- service/benefactor/kind_box_req/service.go | 3 +- validator/benefactor/kind_box_req/delete.go | 10 +-- .../benefactor/kind_box_req/validator.go | 80 +++++++++---------- 22 files changed, 377 insertions(+), 145 deletions(-) create mode 100644 delivery/http_server/benefactor/kind_box_req/delete.go create mode 100644 repository/mysql/kind_box_req/accept.go create mode 100644 repository/mysql/kind_box_req/add.go rename repository/mysql/kind_box_req/{kind_box_req_test.go => add_test.go} (100%) create mode 100644 repository/mysql/kind_box_req/delete.go create mode 100644 repository/mysql/kind_box_req/get.go create mode 100644 repository/mysql/kind_box_req/reject.go create mode 100644 service/benefactor/kind_box_req/delete.go diff --git a/delivery/http_server/benefactor/kind_box_req/delete.go b/delivery/http_server/benefactor/kind_box_req/delete.go new file mode 100644 index 0000000..647266a --- /dev/null +++ b/delivery/http_server/benefactor/kind_box_req/delete.go @@ -0,0 +1,46 @@ +package benefactorkindboxreqhandler + +import ( + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" + "git.gocasts.ir/ebhomengo/niki/pkg/claim" + httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg" + "github.com/labstack/echo/v4" + "net/http" +) + +// delete godoc +// @Summary delete kindboxreq by benefactor +// @Description This endpoint is used to delete benefactor's kindboxreq at pending status +// @Tags KindBoxReq +// @Accept json +// @Produce json +// @Param id path int true "Kind box request ID" +// @Success 200 {object} param.KindBoxReqDeleteResponse +// @Failure 400 {string} "Bad request" +// @Security AuthBearerBenefactor +// @Router /benefactor/kindboxreqs/{id} [delete] +func (h Handler) Delete(c echo.Context) error { + req := param.KindBoxReqDeleteRequest{} + if bErr := echo.PathParamsBinder(c).Uint("id", &req.KindBoxReqID).BindError(); bErr != nil { + + return echo.NewHTTPError(http.StatusBadRequest) + } + claims := claim.GetClaimsFromEchoContext(c) + req.BenefactorID = claims.UserID + if fieldErrors, err := h.benefactorKindBoxReqVld.ValidateDeleteRequest(req); err != nil { + msg, code := httpmsg.Error(err) + + return c.JSON(code, echo.Map{ + "message": msg, + "errors": fieldErrors, + }) + } + resp, dErr := h.benefactorKindBoxReqSvc.Delete(c.Request().Context(), req) + if dErr != nil { + msg, code := httpmsg.Error(dErr) + + return echo.NewHTTPError(code, msg) + } + + return c.JSON(http.StatusOK, resp) +} diff --git a/delivery/http_server/benefactor/kind_box_req/route.go b/delivery/http_server/benefactor/kind_box_req/route.go index e8aa613..4ed79ff 100644 --- a/delivery/http_server/benefactor/kind_box_req/route.go +++ b/delivery/http_server/benefactor/kind_box_req/route.go @@ -16,4 +16,5 @@ func (h Handler) SetRoutes(e *echo.Echo) { r.POST("/", h.Add) r.GET("/:id", h.Get) + r.DELETE("/:id", h.Delete) } diff --git a/docs/docs.go b/docs/docs.go index 7311683..e071499 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -601,6 +601,47 @@ const docTemplate = `{ } } } + }, + "delete": { + "security": [ + { + "AuthBearerBenefactor": [] + } + ], + "description": "This endpoint is used to delete benefactor's kindboxreq at pending status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "KindBoxReq" + ], + "summary": "delete kindboxreq by benefactor", + "parameters": [ + { + "type": "integer", + "description": "Kind box request ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/benefactorkindboxreqparam.KindBoxReqDeleteResponse" + } + }, + "400": { + "description": "Bad request", + "schema": { + "type": "string" + } + } + } } }, "/benefactor/login-register": { @@ -1171,6 +1212,9 @@ const docTemplate = `{ } } }, + "benefactorkindboxreqparam.KindBoxReqDeleteResponse": { + "type": "object" + }, "benefactorkindboxreqparam.KindBoxReqGetResponse": { "type": "object", "properties": { diff --git a/docs/swagger.json b/docs/swagger.json index ececda1..4191b49 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -590,6 +590,47 @@ } } } + }, + "delete": { + "security": [ + { + "AuthBearerBenefactor": [] + } + ], + "description": "This endpoint is used to delete benefactor's kindboxreq at pending status", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "KindBoxReq" + ], + "summary": "delete kindboxreq by benefactor", + "parameters": [ + { + "type": "integer", + "description": "Kind box request ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/benefactorkindboxreqparam.KindBoxReqDeleteResponse" + } + }, + "400": { + "description": "Bad request", + "schema": { + "type": "string" + } + } + } } }, "/benefactor/login-register": { @@ -1160,6 +1201,9 @@ } } }, + "benefactorkindboxreqparam.KindBoxReqDeleteResponse": { + "type": "object" + }, "benefactorkindboxreqparam.KindBoxReqGetResponse": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index c836e84..56bda60 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -316,6 +316,8 @@ definitions: kind_box_req: $ref: '#/definitions/entity.KindBoxReq' type: object + benefactorkindboxreqparam.KindBoxReqDeleteResponse: + type: object benefactorkindboxreqparam.KindBoxReqGetResponse: properties: kind_box_req: @@ -829,6 +831,33 @@ paths: tags: - KindBoxReq /benefactor/kindboxreqs/{id}: + delete: + consumes: + - application/json + description: This endpoint is used to delete benefactor's kindboxreq at pending + status + parameters: + - description: Kind box request ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/benefactorkindboxreqparam.KindBoxReqDeleteResponse' + "400": + description: Bad request + schema: + type: string + security: + - AuthBearerBenefactor: [] + summary: delete kindboxreq by benefactor + tags: + - KindBoxReq get: consumes: - application/json diff --git a/internal/initial/validator.go b/internal/initial/validator.go index 487f2d7..b43525f 100644 --- a/internal/initial/validator.go +++ b/internal/initial/validator.go @@ -35,6 +35,7 @@ func InitBenefactorKindBoxReqValidator(cfg config.Config, redisAdapter redis.Ada return benefactorkindboxreqvalidator.New( InitBenefactorService(cfg, redisAdapter, db), InitBenefactorAddressService(db), + InitBenefactorKindBoxReqDB(db), ) } diff --git a/pkg/err_msg/message.go b/pkg/err_msg/message.go index 8e36b46..5e01722 100644 --- a/pkg/err_msg/message.go +++ b/pkg/err_msg/message.go @@ -1,25 +1,28 @@ package errmsg const ( - ErrorMsgAdminNotAllowed = "admin is not allowed" - ErrorMsgNotFound = "record not found" - ErrorMsgSomethingWentWrong = "something went wrong" - ErrorMsgInvalidInput = "invalid input" - ErrorMsgInvalidStatus = "invalid status" - ErrorMsgPhoneNumberIsNotUnique = "phone number is not unique" - ErrorMsgEmailIsNotUnique = "email is not unique" - ErrorMsgPhoneNumberIsNotValid = "phone number is not valid" - ErrorMsgUserNotAllowed = "user not allowed" - ErrorMsgUserNotFound = "benefactor not found" - ErrorMsgOtpCodeExist = "please wait a little bit" - ErrorMsgOtpCodeIsNotValid = "verification code is not valid" - ErrorMsgCantScanQueryResult = "can't scan query result" - ErrorMsgPhoneNumberOrPassIsIncorrect = "phone number or password is incorrect" - ErrBadRequest = "Bad request" - ErrorMsgAcceptKindBoxReqStatus = "only pending requests will have the ability to be confirmed" - ErrorMsgRejectKindBoxReqStatus = "only pending requests will have the ability to be rejected" - ErrorMsgAssignSenderAgentKindBoxReqStatus = "only accepted kind_box_reqs will have the ability to be assign sender agent" - ErrorMsgDeliverKindBoxReqStatus = "only assigned requests will have the ability to be delivered" - ErrorMsgAdminIsNotAgent = "admin is not agent" - ErrorMsgCountAcceptedOverflow = "count accepted is greather than count requested" + ErrorMsgAdminNotAllowed = "admin is not allowed" + ErrorMsgNotFound = "record not found" + ErrorMsgSomethingWentWrong = "something went wrong" + ErrorMsgInvalidInput = "invalid input" + ErrorMsgInvalidStatus = "invalid status" + ErrorMsgPhoneNumberIsNotUnique = "phone number is not unique" + ErrorMsgEmailIsNotUnique = "email is not unique" + ErrorMsgPhoneNumberIsNotValid = "phone number is not valid" + ErrorMsgUserNotAllowed = "user not allowed" + ErrorMsgUserNotFound = "benefactor not found" + ErrorMsgOtpCodeExist = "please wait a little bit" + ErrorMsgOtpCodeIsNotValid = "verification code is not valid" + ErrorMsgCantScanQueryResult = "can't scan query result" + ErrorMsgPhoneNumberOrPassIsIncorrect = "phone number or password is incorrect" + ErrBadRequest = "Bad request" + ErrorMsgAcceptKindBoxReqStatus = "only pending requests will have the ability to be confirmed" + ErrorMsgRejectKindBoxReqStatus = "only pending requests will have the ability to be rejected" + ErrorMsgAssignSenderAgentKindBoxReqStatus = "only accepted kind_box_reqs will have the ability to be assign sender agent" + ErrorMsgDeliverKindBoxReqStatus = "only assigned requests will have the ability to be delivered" + ErrorMsgAdminIsNotAgent = "admin is not agent" + ErrorMsgCountAcceptedOverflow = "count accepted is greather than count requested" + ErrorMsgReferTimeNotFound = "refer time not found" + ErrorMsgReferTimeIsNotActive = "refer time is not active" + ErrorMsgKindBoxReqDoesntBelongToBenefactor = "kind box req doesnt belong to benefactor" ) diff --git a/repository/mysql/kind_box_req/accept.go b/repository/mysql/kind_box_req/accept.go new file mode 100644 index 0000000..7328802 --- /dev/null +++ b/repository/mysql/kind_box_req/accept.go @@ -0,0 +1,20 @@ +package mysqlkindboxreq + +import ( + "context" + "git.gocasts.ir/ebhomengo/niki/entity" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" +) + +func (d DB) AcceptKindBoxReq(ctx context.Context, kindBoxReqID, countAccepted uint) error { + op := richerror.Op("mysqlkindboxreq.AcceptKindBoxReq") + _, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set count_accepted = ? , status = ? where id = ?`, + countAccepted, entity.KindBoxReqAcceptedStatus.String(), kindBoxReqID) + if err != nil { + return richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) + } + + return nil +} diff --git a/repository/mysql/kind_box_req/add.go b/repository/mysql/kind_box_req/add.go new file mode 100644 index 0000000..83063c5 --- /dev/null +++ b/repository/mysql/kind_box_req/add.go @@ -0,0 +1,26 @@ +package mysqlkindboxreq + +import ( + "context" + "git.gocasts.ir/ebhomengo/niki/entity" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" +) + +func (d DB) AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error) { + const op = "mysqlkindboxreq.AddKindBoxReq" + + res, err := d.conn.Conn().ExecContext(ctx, `insert into kind_box_reqs(benefactor_id,kind_box_type,deliver_address_id,count_requested,deliver_refer_date,status) values (?,?,?,?,?,?)`, + kindBoxReq.BenefactorID, kindBoxReq.KindBoxType.String(), kindBoxReq.DeliverAddressID, kindBoxReq.CountRequested, kindBoxReq.DeliverReferDate, kindBoxReq.Status.String()) + if err != nil { + return entity.KindBoxReq{}, richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected) + } + + //nolint + // err is always nil + id, _ := res.LastInsertId() + kindBoxReq.ID = uint(id) + + return kindBoxReq, nil +} diff --git a/repository/mysql/kind_box_req/kind_box_req_test.go b/repository/mysql/kind_box_req/add_test.go similarity index 100% rename from repository/mysql/kind_box_req/kind_box_req_test.go rename to repository/mysql/kind_box_req/add_test.go diff --git a/repository/mysql/kind_box_req/delete.go b/repository/mysql/kind_box_req/delete.go new file mode 100644 index 0000000..6e36534 --- /dev/null +++ b/repository/mysql/kind_box_req/delete.go @@ -0,0 +1,18 @@ +package mysqlkindboxreq + +import ( + "context" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" + "time" +) + +func (d DB) DeleteKindBoxReqByID(ctx context.Context, kindBoxReqID uint) error { + const op = richerror.Op("mysqlkindboxreq.DeleteKindBoxReqByID") + _, dErr := d.conn.Conn().ExecContext(ctx, "update kind_box_reqs set deleted_at = ? where id = ? ", time.Now(), kindBoxReqID) + if dErr != nil { + return richerror.New(op).WithErr(dErr). + WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) + } + return nil +} diff --git a/repository/mysql/kind_box_req/get.go b/repository/mysql/kind_box_req/get.go new file mode 100644 index 0000000..f4dce29 --- /dev/null +++ b/repository/mysql/kind_box_req/get.go @@ -0,0 +1,38 @@ +package mysqlkindboxreq + +import ( + "context" + "database/sql" + "git.gocasts.ir/ebhomengo/niki/entity" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" +) + +func (d DB) GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error) { + op := richerror.Op("mysqlkindboxreq.GetByID") + row := d.conn.Conn().QueryRowContext(ctx, `select * from kind_box_reqs where id = ? and deleted_at is null`, id) + k, err := scanKindBoxReq(row) + if err != nil { + return entity.KindBoxReq{}, richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) + } + + return k, nil +} + +func (d DB) GetKindBoxReqByID(ctx context.Context, kindBoxReqID uint) (entity.KindBoxReq, error) { + op := richerror.Op("mysqlkindboxreq.GetKindBoxReqByID") + row := d.conn.Conn().QueryRowContext(ctx, + "select * from kind_box_reqs where id = ? and deleted_at is null", kindBoxReqID) + k, err := scanKindBoxReq(row) + if err != nil { + if err == sql.ErrNoRows { + return entity.KindBoxReq{}, richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound) + } + return entity.KindBoxReq{}, richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) + } + + return k, nil +} diff --git a/repository/mysql/kind_box_req/get_all.go b/repository/mysql/kind_box_req/get_all.go index 7c99714..8d452f6 100644 --- a/repository/mysql/kind_box_req/get_all.go +++ b/repository/mysql/kind_box_req/get_all.go @@ -14,7 +14,7 @@ func (d DB) GetAllKindBoxReq(ctx context.Context, pagination paginationparam.Pag // TODO: create getCount function var count uint - rows, err := d.conn.Conn().QueryContext(ctx, "SELECT COUNT(*) FROM kind_box_reqs") + rows, err := d.conn.Conn().QueryContext(ctx, "SELECT COUNT(*) FROM kind_box_reqs where deleted_at is null") if err != nil { return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithErr(err).WithKind(richerror.KindUnexpected) @@ -35,7 +35,7 @@ func (d DB) GetAllKindBoxReq(ctx context.Context, pagination paginationparam.Pag } // TODO - add sort and filter - rows, err = d.conn.Conn().QueryContext(ctx, "select * from kind_box_reqs limit ? offset ?", pagination.GetPageSize(), pagination.GetOffset()) + rows, err = d.conn.Conn().QueryContext(ctx, "select * from kind_box_reqs where deleted_at is null limit ? offset ?", pagination.GetPageSize(), pagination.GetOffset()) if err != nil { return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithErr(err).WithKind(richerror.KindUnexpected) diff --git a/repository/mysql/kind_box_req/kind_box_req.go b/repository/mysql/kind_box_req/kind_box_req.go index acab110..ce32b2a 100644 --- a/repository/mysql/kind_box_req/kind_box_req.go +++ b/repository/mysql/kind_box_req/kind_box_req.go @@ -9,48 +9,6 @@ import ( richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" ) -func (d DB) AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error) { - const op = "mysqlkindboxreq.AddKindBoxReq" - - res, err := d.conn.Conn().ExecContext(ctx, `insert into kind_box_reqs(benefactor_id,kind_box_type,deliver_address_id,count_requested,deliver_refer_date,status) values (?,?,?,?,?,?)`, - kindBoxReq.BenefactorID, kindBoxReq.KindBoxType.String(), kindBoxReq.DeliverAddressID, kindBoxReq.CountRequested, kindBoxReq.DeliverReferDate, kindBoxReq.Status.String()) - if err != nil { - return entity.KindBoxReq{}, richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected) - } - - //nolint - // err is always nil - id, _ := res.LastInsertId() - kindBoxReq.ID = uint(id) - - return kindBoxReq, nil -} - -func (d DB) AcceptKindBoxReq(ctx context.Context, kindBoxReqID, countAccepted uint) error { - op := richerror.Op("mysqlkindboxreq.AcceptKindBoxReq") - _, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set count_accepted = ? , status = ? where id = ?`, - countAccepted, entity.KindBoxReqAcceptedStatus.String(), kindBoxReqID) - if err != nil { - return richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) - } - - return nil -} - -func (d DB) GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error) { - op := richerror.Op("mysqlkindboxreq.GetByID") - row := d.conn.Conn().QueryRowContext(ctx, `select * from kind_box_reqs where id = ?`, id) - k, err := scanKindBoxReq(row) - if err != nil { - return entity.KindBoxReq{}, richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) - } - - return k, nil -} - func (d DB) KindBoxRequestExist(id uint) (bool, error) { op := richerror.Op("mysqlkindboxreq.KindBoxRequestExist") row := d.conn.Conn().QueryRow(`select * from kind_box_reqs where id = ?`, id) @@ -67,18 +25,6 @@ func (d DB) KindBoxRequestExist(id uint) (bool, error) { return true, nil } -func (d DB) RejectKindBoxReq(ctx context.Context, kindBoxReqID uint, description string) error { - op := richerror.Op("mysqlkindboxreq.RejectKindBoxReq") - _, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set description = ? , status = ? where id = ?`, - description, entity.KindBoxReqRejectedStatus.String(), kindBoxReqID) - if err != nil { - return richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) - } - - return nil -} - func (d DB) RollbackKindBoxRequestStatus(ctx context.Context, id uint) error { op := richerror.Op("mysqlkindboxreq.RollbackKindBoxRequestStatus") _, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set status = ? where id = ?`, entity.KindBoxReqPendingStatus.String(), id) @@ -89,21 +35,3 @@ func (d DB) RollbackKindBoxRequestStatus(ctx context.Context, id uint) error { return nil } - -func (d DB) GetKindBoxReqByID(ctx context.Context, kindBoxReqID, benefactorID uint) (entity.KindBoxReq, error) { - op := richerror.Op("mysqlkindboxreq.GetKindBoxReqByID") - row := d.conn.Conn().QueryRowContext(ctx, - "select kind_box_reqs.* from kind_box_reqs where kind_box_reqs.id = ? and kind_box_reqs.benefactor_id = ?", kindBoxReqID, benefactorID, - ) - k, err := scanKindBoxReq(row) - if err != nil { - if err == sql.ErrNoRows { - return entity.KindBoxReq{}, richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound) - } - return entity.KindBoxReq{}, richerror.New(op).WithErr(err). - WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected) - } - - return k, nil -} diff --git a/repository/mysql/kind_box_req/reject.go b/repository/mysql/kind_box_req/reject.go new file mode 100644 index 0000000..2fc3a30 --- /dev/null +++ b/repository/mysql/kind_box_req/reject.go @@ -0,0 +1,20 @@ +package mysqlkindboxreq + +import ( + "context" + "git.gocasts.ir/ebhomengo/niki/entity" + errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" +) + +func (d DB) RejectKindBoxReq(ctx context.Context, kindBoxReqID uint, description string) error { + op := richerror.Op("mysqlkindboxreq.RejectKindBoxReq") + _, err := d.conn.Conn().ExecContext(ctx, `update kind_box_reqs set description = ? , status = ? where id = ?`, + description, entity.KindBoxReqRejectedStatus.String(), kindBoxReqID) + if err != nil { + return richerror.New(op).WithErr(err). + WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected) + } + + return nil +} diff --git a/repository/mysql/kind_box_req/scan.go b/repository/mysql/kind_box_req/scan.go index 1cb0343..530a79c 100644 --- a/repository/mysql/kind_box_req/scan.go +++ b/repository/mysql/kind_box_req/scan.go @@ -19,6 +19,7 @@ func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) { deliveredAt sql.NullTime createdAt time.Time updatedAt time.Time + deletedAt sql.NullTime ) err := scanner.Scan( @@ -35,6 +36,7 @@ func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) { &deliveredAt, &createdAt, &updatedAt, + &deletedAt, ) if err != nil { return entity.KindBoxReq{}, err diff --git a/repository/mysql/migration/1705400111_create_kind_box_reqs_table.sql b/repository/mysql/migration/1705400111_create_kind_box_reqs_table.sql index de4ca8a..c1e6970 100644 --- a/repository/mysql/migration/1705400111_create_kind_box_reqs_table.sql +++ b/repository/mysql/migration/1705400111_create_kind_box_reqs_table.sql @@ -14,6 +14,7 @@ CREATE TABLE `kind_box_reqs` ( `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `deleted_at` TIMESTAMP, FOREIGN KEY (`benefactor_id`) REFERENCES `benefactors` (`id`), FOREIGN KEY (`deliver_address_id`) REFERENCES `addresses` (`id`), FOREIGN KEY (`sender_agent_id`) REFERENCES `admins` (`id`) diff --git a/service/benefactor/kind_box_req/delete.go b/service/benefactor/kind_box_req/delete.go new file mode 100644 index 0000000..ff3c546 --- /dev/null +++ b/service/benefactor/kind_box_req/delete.go @@ -0,0 +1,16 @@ +package benefactorkindboxreqservice + +import ( + "context" + param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box_req" + richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error" +) + +func (s Service) Delete(ctx context.Context, req param.KindBoxReqDeleteRequest) (param.KindBoxReqDeleteResponse, error) { + const op = richerror.Op("benefactorkindboxreqservice.Delete") + dErr := s.repo.DeleteKindBoxReqByID(ctx, req.KindBoxReqID) + if dErr != nil { + return param.KindBoxReqDeleteResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected) + } + return param.KindBoxReqDeleteResponse{}, nil +} diff --git a/service/benefactor/kind_box_req/get.go b/service/benefactor/kind_box_req/get.go index c4a33ac..028c96d 100644 --- a/service/benefactor/kind_box_req/get.go +++ b/service/benefactor/kind_box_req/get.go @@ -10,7 +10,7 @@ import ( func (s Service) Get(ctx context.Context, req param.KindBoxReqGetRequest) (param.KindBoxReqGetResponse, error) { const op = "userkindboxreqservice.Get" - kindBoxReq, err := s.repo.GetKindBoxReqByID(ctx, req.KindBoxReqID, req.BenefactorID) + kindBoxReq, err := s.repo.GetKindBoxReqByID(ctx, req.KindBoxReqID) if err != nil { return param.KindBoxReqGetResponse{}, richerror.New(op).WithErr(err) } diff --git a/service/benefactor/kind_box_req/service.go b/service/benefactor/kind_box_req/service.go index 6d3a2a2..5573272 100644 --- a/service/benefactor/kind_box_req/service.go +++ b/service/benefactor/kind_box_req/service.go @@ -8,7 +8,8 @@ import ( type Repository interface { AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error) - GetKindBoxReqByID(ctx context.Context, kindBoxReqID uint, benefactorID uint) (entity.KindBoxReq, error) + GetKindBoxReqByID(ctx context.Context, kindBoxReqID uint) (entity.KindBoxReq, error) + DeleteKindBoxReqByID(ctx context.Context, kindBoxReqID uint) error } type Service struct { diff --git a/validator/benefactor/kind_box_req/delete.go b/validator/benefactor/kind_box_req/delete.go index 42c973a..a86867f 100644 --- a/validator/benefactor/kind_box_req/delete.go +++ b/validator/benefactor/kind_box_req/delete.go @@ -16,12 +16,10 @@ func (v Validator) ValidateDeleteRequest(req param.KindBoxReqDeleteRequest) (map validation.Field(&req.BenefactorID, validation.Required, validation.By(v.doesBenefactorExist)), - - // validation.Field(&req.KindBoxReqID, - // validation.Required, - // validation.By(v.doesKindBoxRequestExist), - // validation.By(v.hasPendingStatus), - // validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))), + validation.Field(&req.KindBoxReqID, + validation.Required, + validation.By(v.doesKindBoxRequestHavePendingStatus), + validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))), ); err != nil { fieldErrors := make(map[string]string) diff --git a/validator/benefactor/kind_box_req/validator.go b/validator/benefactor/kind_box_req/validator.go index 4a99066..8a1548e 100644 --- a/validator/benefactor/kind_box_req/validator.go +++ b/validator/benefactor/kind_box_req/validator.go @@ -24,9 +24,14 @@ type AddressSvc interface { AddressExistByID(ctx context.Context, request addressparam.GetAddressByIDRequest) (addressparam.GetAddressByIDResponse, error) } +type Repository interface { + GetKindBoxReqByID(ctx context.Context, kindBoxReqID uint) (entity.KindBoxReq, error) +} + type Validator struct { benefactorSvc BenefactorSvc addressSvc AddressSvc + repo Repository } type ValidatorError struct { @@ -44,8 +49,8 @@ func (v ValidatorError) Error() string { return err } -func New(benefactorSvc BenefactorSvc, addressSvc AddressSvc) Validator { - return Validator{benefactorSvc: benefactorSvc, addressSvc: addressSvc} +func New(benefactorSvc BenefactorSvc, addressSvc AddressSvc, repo Repository) Validator { + return Validator{benefactorSvc: benefactorSvc, addressSvc: addressSvc, repo: repo} } func (v Validator) doesBenefactorExist(value interface{}) error { @@ -110,43 +115,34 @@ func (v Validator) isDateValid(value interface{}) error { return nil } -// func (v Validator) doesKindBoxRequestExist(value interface{}) error { -// kindBoxReqID, ok := value.(uint) -// if !ok { -// return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong) -// } -// _, err := v.repo.KindBoxReqExist(kindBoxReqID) -// if err != nil { -// return fmt.Errorf(errmsg.ErrorMsgNotFound) -// } -// -// return nil -//} -// -// func (v Validator) doesKindBoxBelongToBenefactor(benefactorID uint) validation.RuleFunc { -// return func(value interface{}) error { -// kbID, ok := value.(uint) -// if !ok { -// return fmt.Errorf(errmsg.ErrorMsgNotFound) -// } -// _, err := v.repo.KindBoxBelongToBenefactor(benefactorID, kbID) -// if err != nil { -// return fmt.Errorf(errmsg.ErrorMsgNotFound) -// } -// -// return nil -// } -//} -// -// func (v Validator) hasPendingStatus(value interface{}) error { -// kindboxID, ok := value.(uint) -// if !ok { -// return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong) -// } -// _, err := v.repo.PendingStatus(kindboxID) -// if err != nil { -// return fmt.Errorf(errmsg.ErrorMsgNotFound) -// } -// -// return nil -//} +func (v Validator) doesKindBoxBelongToBenefactor(benefactorID uint) validation.RuleFunc { + return func(value interface{}) error { + kindBoxReqID, ok := value.(uint) + if !ok { + return fmt.Errorf(errmsg.ErrorMsgNotFound) + } + kindBoxReq, err := v.repo.GetKindBoxReqByID(context.Background(), kindBoxReqID) + if err != nil { + return fmt.Errorf(errmsg.ErrorMsgNotFound) + } + if kindBoxReq.BenefactorID != benefactorID { + return fmt.Errorf(errmsg.ErrorMsgKindBoxReqDoesntBelongToBenefactor) + } + return nil + } +} + +func (v Validator) doesKindBoxRequestHavePendingStatus(value interface{}) error { + kindBoxReqID, ok := value.(uint) + if !ok { + return fmt.Errorf(errmsg.ErrorMsgNotFound) + } + kindBoxReq, err := v.repo.GetKindBoxReqByID(context.Background(), kindBoxReqID) + if err != nil { + return fmt.Errorf(errmsg.ErrorMsgNotFound) + } + if kindBoxReq.Status != entity.KindBoxReqPendingStatus { + return fmt.Errorf(errmsg.ErrorMsgInvalidStatus) + } + return nil +}