Merge pull request 'feat(service) : Accept/Reject kind box request' (#25) from stage/abolfazl/62-accept-reject-kind-box-req into develop

Reviewed-on: ebhomengo/niki#25
This commit is contained in:
Alireza Mokhtari Garakani 2024-01-28 06:28:18 +00:00
commit 0aba9e6cbb
62 changed files with 622 additions and 1120 deletions

View File

@ -1,32 +1 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) Add(c echo.Context) error {
var req param.KindBoxAddRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
if fieldErrors, err := h.adminKindBoxVld.ValidateAddRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxSvc.Add(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -1,32 +1 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) Get(c echo.Context) error {
var req param.KindBoxGetRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
if fieldErrors, err := h.adminKindBoxVld.ValidateGetRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxSvc.Get(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -1,25 +1 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) GetAll(c echo.Context) error {
var req param.KindBoxGetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
resp, sErr := h.adminKindBoxSvc.GetAll(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -4,11 +4,5 @@ import (
echo "github.com/labstack/echo/v4"
)
func (h Handler) SetRoutes(e *echo.Echo) {
r := e.Group("/admin/kindboxes")
r.POST("/", h.Add).Name = "admin-addkindbox"
r.GET("/:id", h.Get).Name = "admin-getkindboxbyid"
r.GET("/", h.GetAll).Name = "admin-getallkindbox"
r.PATCH("/:id", h.Update).Name = "admin-updatekindbox"
func (h Handler) SetRoutes(_ *echo.Echo) {
}

View File

@ -1,32 +1 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) Update(c echo.Context) error {
var req param.KindBoxUpdateRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
if fieldErrors, err := h.adminKindBoxVld.ValidateUpdateRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxSvc.Update(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -0,0 +1,40 @@
package adminkindboxreqhandler
import (
"net/http"
"strconv"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
)
func (h Handler) Accept(c echo.Context) error {
var req param.KindBoxReqAcceptRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
num, cErr := strconv.ParseUint(c.Param("id"), 10, 64)
if cErr != nil {
return c.JSON(http.StatusBadRequest, errmsg.ErrorMsgInvalidInput)
}
req.ID = uint(num)
if fieldErrors, err := h.adminKindBoxReqVld.ValidateAcceptRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxReqSvc.Accept(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -1,32 +1 @@
package adminkindboxreqhandler
// import (
// "net/http"
//
// param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
// httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
// echo "github.com/labstack/echo/v4"
//)
//
// func (h Handler) Add(c echo.Context) error {
// var req param.KindBoxReqAddRequest
// if bErr := c.Bind(&req); bErr != nil {
// return echo.NewHTTPError(http.StatusBadRequest)
// }
// if fieldErrors, err := h.adminKindBoxReqVld.ValidateAddRequest(req); err != nil {
// msg, code := httpmsg.Error(err)
//
// return c.JSON(code, echo.Map{
// "message": msg,
// "errors": fieldErrors,
// })
// }
// resp, sErr := h.adminKindBoxReqSvc.Add(c.Request().Context(), req)
// if sErr != nil {
// msg, code := httpmsg.Error(sErr)
//
// return echo.NewHTTPError(code, msg)
// }
//
// return c.JSON(http.StatusCreated, resp)
//}

View File

@ -1,32 +1 @@
package adminkindboxreqhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) Get(c echo.Context) error {
var req param.KindBoxReqGetRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
if fieldErrors, err := h.adminKindBoxReqVld.ValidateGetRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxReqSvc.Get(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -1,25 +1 @@
package adminkindboxreqhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
echo "github.com/labstack/echo/v4"
)
func (h Handler) GetAll(c echo.Context) error {
var req param.KindBoxReqGetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
resp, sErr := h.adminKindBoxReqSvc.GetAll(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -0,0 +1,40 @@
package adminkindboxreqhandler
import (
"net/http"
"strconv"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
)
func (h Handler) Reject(c echo.Context) error {
var req param.KindBoxReqRejectRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
num, cErr := strconv.ParseUint(c.Param("id"), 10, 64)
if cErr != nil {
return c.JSON(http.StatusBadRequest, errmsg.ErrorMsgInvalidInput)
}
req.ID = uint(num)
if fieldErrors, err := h.adminKindBoxReqVld.ValidateRejectRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
resp, sErr := h.adminKindBoxReqSvc.Reject(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusCreated, resp)
}

View File

@ -7,10 +7,7 @@ import (
func (h Handler) SetRoutes(e *echo.Echo) {
r := e.Group("/admin/kindboxreqs")
//nolint:gocritic
//r.POST("/", h.Add).Name = "admin-addkindboxreq"
r.GET("/:id", h.Get).Name = "admin-getkindboxreqbyid"
r.GET("/", h.GetAll).Name = "admin-getallkindboxreq"
//nolint:gocritic
//r.PATCH("/:id", h.Update).Name = "admin-updatekindboxreq"
// todo - add acl
r.PATCH("/accept-kind-box-req/:id", h.Accept)
r.PATCH("/reject-kind-box-req/:id", h.Reject)
}

View File

@ -1,32 +1 @@
package adminkindboxreqhandler
// import (
// "net/http"
//
// param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
// httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
// echo "github.com/labstack/echo/v4"
//)
//
// func (h Handler) Update(c echo.Context) error {
// var req param.KindBoxReqUpdateRequest
// if bErr := c.Bind(&req); bErr != nil {
// return echo.NewHTTPError(http.StatusBadRequest)
// }
// if fieldErrors, err := h.adminKindBoxReqVld.ValidateUpdateRequest(req); err != nil {
// msg, code := httpmsg.Error(err)
//
// return c.JSON(code, echo.Map{
// "message": msg,
// "errors": fieldErrors,
// })
// }
// resp, sErr := h.adminKindBoxReqSvc.Update(c.Request().Context(), req)
// if sErr != nil {
// msg, code := httpmsg.Error(sErr)
//
// return echo.NewHTTPError(code, msg)
// }
//
// return c.JSON(http.StatusCreated, resp)
//}

View File

@ -1,24 +1 @@
package benefactorkindboxreqhandler
// func (h Handler) Get(c echo.Context) error {
// var req param.KindBoxReqGetRequest
// if bErr := c.Bind(&req); bErr != nil {
// return echo.NewHTTPError(http.StatusBadRequest)
// }
// if fieldErrors, err := h.benefactorKindBoxReqVld.ValidateGetRequest(req); err != nil {
// msg, code := httpmsg.Error(err)
//
// return c.JSON(code, echo.Map{
// "message": msg,
// "errors": fieldErrors,
// })
// }
// resp, sErr := h.benefactorKindBoxReqSvc.Get(c.Request().Context(), req)
// if sErr != nil {
// msg, code := httpmsg.Error(sErr)
//
// return echo.NewHTTPError(code, msg)
// }
//
// return c.JSON(http.StatusCreated, resp)
//}

View File

@ -1,17 +1 @@
package benefactorkindboxreqhandler
// func (h Handler) GetAll(c echo.Context) error {
// var req param.KindBoxReqGetAllRequest
// if bErr := c.Bind(&req); bErr != nil {
// return echo.NewHTTPError(http.StatusBadRequest)
// }
//
// resp, sErr := h.benefactorKindBoxReqSvc.GetAll(c.Request().Context(), req)
// if sErr != nil {
// msg, code := httpmsg.Error(sErr)
//
// return echo.NewHTTPError(code, msg)
// }
//
// return c.JSON(http.StatusCreated, resp)
//}

View File

@ -11,8 +11,4 @@ func (h Handler) SetRoutes(e *echo.Echo) {
r.POST("/", h.Add, middleware.Auth(h.authSvc, h.authConfig),
middleware.BenefactorAuthorization(entity.UserBenefactorRole))
//nolint:gocritic
// r.GET("/:id", h.Get)
// r.GET("/", h.GetAll)
// r.PATCH("/:id", h.Update)
}

View File

@ -1,24 +1 @@
package benefactorkindboxreqhandler
// func (h Handler) Update(c echo.Context) error {
// var req param.KindBoxReqUpdateRequest
// if bErr := c.Bind(&req); bErr != nil {
// return echo.NewHTTPError(http.StatusBadRequest)
// }
// if fieldErrors, err := h.benefactorKindBoxReqVld.ValidateUpdateRequest(req); err != nil {
// msg, code := httpmsg.Error(err)
//
// return c.JSON(code, echo.Map{
// "message": msg,
// "errors": fieldErrors,
// })
// }
// resp, sErr := h.benefactorKindBoxReqSvc.Update(c.Request().Context(), req)
// if sErr != nil {
// msg, code := httpmsg.Error(sErr)
//
// return echo.NewHTTPError(code, msg)
// }
//
// return c.JSON(http.StatusCreated, resp)
//}

View File

@ -9,6 +9,7 @@ import (
"github.com/labstack/echo/v4"
)
//nolint
func BenefactorAuthorization(role entity.UserRole) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {

View File

@ -5,15 +5,18 @@ import (
config "git.gocasts.ir/ebhomengo/niki/config"
adminhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/admin"
adminkindboxreqhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/kind_box_req"
benefactoraddresshandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/benefactor/address"
benefactorhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/benefactor/benefactor"
benefactorkindboxreqhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/benefactor/kind_box_req"
adminservice "git.gocasts.ir/ebhomengo/niki/service/admin/admin"
adminkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box_req"
authservice "git.gocasts.ir/ebhomengo/niki/service/auth"
benefactoraddressservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/address"
benefactorservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/benefactor"
benefactorkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box_req"
adminvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/admin"
adminkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box_req"
benefactoraddressvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/address"
benefactorvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/benefactor"
benefactorkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box_req"
@ -28,6 +31,7 @@ type Server struct {
benefactorKindBoxReqHandler benefactorkindboxreqhandler.Handler
benefactorAddressHandler benefactoraddresshandler.Handler
adminHandler adminhandler.Handler
adminKindBoxReqHandler adminkindboxreqhandler.Handler
}
func New(
@ -42,6 +46,8 @@ func New(
adminSvc adminservice.Service,
adminVld adminvalidator.Validator,
adminAuthSvc authservice.Service,
adminKinBoxReqSvc adminkindboxreqservice.Service,
adminKinBoxReqVld adminkindboxreqvalidator.Validator,
) Server {
return Server{
Router: echo.New(),
@ -50,6 +56,7 @@ func New(
benefactorKindBoxReqHandler: benefactorkindboxreqhandler.New(cfg.Auth, benefactorAuthSvc, benefactorKindBoxReqSvc, benefactorKindBoxReqVld),
benefactorAddressHandler: benefactoraddresshandler.New(cfg.Auth, benefactorAuthSvc, benefactorAddressSvc, benefactorAddressVld),
adminHandler: adminhandler.New(cfg.AdminAuth, adminAuthSvc, adminSvc, adminVld),
adminKindBoxReqHandler: adminkindboxreqhandler.New(cfg.Auth, adminAuthSvc, adminKinBoxReqSvc, adminKinBoxReqVld),
}
}
@ -64,6 +71,7 @@ func (s Server) Serve() {
s.benefactorKindBoxReqHandler.SetRoutes(s.Router)
s.benefactorAddressHandler.SetRoutes(s.Router)
s.adminHandler.SetRoutes(s.Router)
s.adminKindBoxReqHandler.SetRoutes(s.Router)
// Start server
address := fmt.Sprintf(":%d", s.config.HTTPServer.Port)

View File

@ -4,12 +4,13 @@ import "time"
type KindBox struct {
ID uint
KindBoxReqID uint // TODO like database model
BenefactorID uint // TODO need in business entity
KindBoxReqID uint
BenefactorID uint
Type KindBoxType
TotalAmount uint
ReceiverID uint
SenderID uint
SerialNumber string
Status KindBoxStatus
SenderID uint
ReceiverID uint
StatusChangedAt time.Time
}

View File

@ -12,4 +12,5 @@ type KindBoxReq struct {
Description string
ReferDate time.Time
AddressID uint
CreatedAt time.Time
}

1
go.mod
View File

@ -31,6 +31,7 @@ require (
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/oklog/ulid/v2 v2.1.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.17.0 // indirect

3
go.sum
View File

@ -228,8 +228,11 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/npillmayer/nestext v0.1.3/go.mod h1:h2lrijH8jpicr25dFY+oAJLyzlya6jhnuG+zWp9L0Uk=
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU=
github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml v1.7.0 h1:7utD74fnzVc/cpcyy8sjrlFr5vYpypUixARcHIMIGuI=
github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE=
github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=

35
main.go
View File

@ -11,14 +11,18 @@ import (
mysqladdress "git.gocasts.ir/ebhomengo/niki/repository/mysql/address"
mysqladmin "git.gocasts.ir/ebhomengo/niki/repository/mysql/admin"
mysqlbenefactor "git.gocasts.ir/ebhomengo/niki/repository/mysql/benefactor"
mysqlkindbox "git.gocasts.ir/ebhomengo/niki/repository/mysql/kind_box"
mysqlkindboxreq "git.gocasts.ir/ebhomengo/niki/repository/mysql/kind_box_req"
redisotp "git.gocasts.ir/ebhomengo/niki/repository/redis/redis_otp"
adminservice "git.gocasts.ir/ebhomengo/niki/service/admin/admin"
adminkindboxservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box"
adminkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box_req"
authservice "git.gocasts.ir/ebhomengo/niki/service/auth"
benefactoraddressservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/address"
benefactorservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/benefactor"
benefactorkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box_req"
adminvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/admin"
adminkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box_req"
benefactoraddressvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/address"
benefactorvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/benefactor"
benefactorkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box_req"
@ -31,10 +35,21 @@ func main() {
mgr := migrator.New(cfg.Mysql)
mgr.Up()
benefactorAuthSvc, benefactorSvc, benefactorVld, benefactorKindBoxReqSvc, benefactorKindBoxReqVld, benefactorAddressSvc, benefactorAddressVld,
adminSvc, adminVld, adminAuthSvc := setupServices(cfg)
server := httpserver.New(cfg, benefactorSvc, benefactorVld, benefactorAuthSvc, benefactorKindBoxReqSvc, benefactorKindBoxReqVld,
benefactorAddressSvc, benefactorAddressVld, adminSvc, adminVld, adminAuthSvc)
authSvc,
benefactorSvc,
benefactorVld,
benefactorKindBoxReqSvc,
benefactorKindBoxReqVld,
benefactorAddressSvc,
benefactorAddressVld,
adminSvc,
adminVld,
adminAuthSvc,
adminKindBoxReqSvc,
adminKindBoxReqVld := setupServices(cfg)
server := httpserver.New(cfg, benefactorSvc, benefactorVld, authSvc, benefactorKindBoxReqSvc, benefactorKindBoxReqVld,
benefactorAddressSvc, benefactorAddressVld, adminSvc, adminVld, adminAuthSvc, adminKindBoxReqSvc, adminKindBoxReqVld)
server.Serve()
}
@ -44,7 +59,9 @@ func setupServices(cfg config.Config) (
benefactorKindBoxReqSvc benefactorkindboxreqservice.Service, benefactorKindBoxReqVld benefactorkindboxreqvalidator.Validator,
benefactorAddressSvc benefactoraddressservice.Service,
benefactorAddressVld benefactoraddressvalidator.Validator,
adminSvc adminservice.Service, adminVld adminvalidator.Validator, adminAuthSvc authservice.Service,
adminSvc adminservice.Service, adminVld adminvalidator.Validator,
adminAuthSvc authservice.Service,
adminKindBoxReqSvc adminkindboxreqservice.Service, adminKindBoxReqVld adminkindboxreqvalidator.Validator,
) {
benefactorAuthSvc = authservice.New(cfg.Auth)
@ -55,8 +72,10 @@ func setupServices(cfg config.Config) (
benefactorMysql := mysqlbenefactor.New(MysqlRepo)
kavenegarSmsProvider := smsprovider.New(cfg.KavenegarSmsProvider)
otpSmsProvider := kavenegarotp.New(kavenegarSmsProvider)
authGenerator := authservice.New(cfg.Auth)
benefactorSvc = benefactorservice.New(cfg.BenefactorSvc, RedisOtp, otpSmsProvider, authGenerator, benefactorMysql)
benefactorSvc = benefactorservice.New(cfg.BenefactorSvc, RedisOtp, otpSmsProvider, benefactorAuthSvc, benefactorMysql)
benefactorAddressMysql := mysqladdress.New(MysqlRepo)
benefactorAddressSvc = benefactoraddressservice.New(benefactorAddressMysql)
benefactorAddressVld = benefactoraddressvalidator.New(benefactorSvc, benefactorAddressMysql)
@ -65,6 +84,10 @@ func setupServices(cfg config.Config) (
benefactorKindBoxReqMysql := mysqlkindboxreq.New(MysqlRepo)
benefactorKindBoxReqSvc = benefactorkindboxreqservice.New(benefactorKindBoxReqMysql)
benefactorKindBoxReqVld = benefactorkindboxreqvalidator.New(benefactorKindBoxReqMysql, benefactorSvc, benefactorAddressSvc)
mysqlkindboxRepo := mysqlkindbox.New(MysqlRepo)
adminkindboxsvc := adminkindboxservice.New(mysqlkindboxRepo)
adminKindBoxReqSvc = adminkindboxreqservice.New(benefactorKindBoxReqMysql, adminkindboxsvc)
adminKindBoxReqVld = adminkindboxreqvalidator.New(benefactorKindBoxReqMysql)
adminAuthSvc = authservice.New(cfg.AdminAuth)
adminMysql := mysqladmin.New(MysqlRepo)

View File

@ -2,13 +2,11 @@ package adminkindboxparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
type KindBoxAddRequest struct {
type KindBoxAddAfterAcceptingReqRequest struct {
BenefactorID uint
KindBoxReqID uint
SenderID uint
SerialNumber string
Type entity.KindBoxType
Count uint
}
type KindBoxAddResponse struct {
KindBox entity.KindBox
}
type KindBoxAddAfterAcceptingReqResponse struct{}

View File

@ -0,0 +1,21 @@
package adminkindboxreqparam
import (
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
)
type KindBoxReqAcceptRequest struct {
ID uint `json:"id"`
CountAccepted uint `json:"count_accepted"`
}
type KindBoxReqAcceptResponse struct {
KindBoxReqID uint `json:"kind_box_req_id"`
KindBoxReqStatus entity.KindBoxReqStatus `json:"kind_box_req_status"`
CountRequested uint `json:"count_requested"`
CountAccepted uint `json:"count_accepted"`
ReferDate time.Time `json:"refer_date"`
AddressID uint `json:"address_id"`
}

View File

@ -0,0 +1,23 @@
package adminkindboxreqparam
import (
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
)
type KindBoxReqRejectRequest struct {
ID uint `json:"id"`
Description string `json:"description"`
}
type KindBoxReqRejectResponse struct {
ID uint `json:"id"`
KindBoxType entity.KindBoxType `json:"kind_box_type"`
CountRequested uint `json:"count_requested"`
BenefactorID uint `json:"benefactor_id"`
Status entity.KindBoxReqStatus `json:"status"`
Description string `json:"description"`
ReferDate time.Time `json:"refer_date"`
AddressID uint `json:"address_id"`
}

View File

@ -14,4 +14,6 @@ const (
ErrorMsgOtpCodeIsNotValid = "verification code is not valid"
ErrorMsgCantScanQueryResult = "can't scan query result"
ErrorMsgPhoneNumberOrPassIsIncorrect = "phone number or password is incorrect"
ErrorMsgAcceptKindBoxReqStatus = "only pending requests will have the ability to be confirmed"
ErrorMsgRejectKindBoxReqStatus = "only pending requests will have the ability to be rejected"
)

View File

@ -1 +1,69 @@
package mysqlkindbox
import (
"context"
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/logger"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (d DB) AddBatchKindBox(ctx context.Context, kindBoxes []entity.KindBox) error {
const op = "mysqlkindbox.AddBatchKindBoxConcurrentlyRollback"
errCh := make(chan error, len(kindBoxes))
resultCh := make(chan entity.KindBox, len(kindBoxes))
tx, tErr := d.conn.Conn().Begin()
if tErr != nil {
return richerror.New(op).WithErr(tErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
for _, kindBox := range kindBoxes {
go func(kb entity.KindBox) {
_, err := tx.ExecContext(ctx,
"insert into kind_boxes (kind_box_req_id, benefactor_id, type, serial_number, status) values (?, ?, ?, ?, ?);",
kb.KindBoxReqID, kb.BenefactorID, kb.Type.String(), kb.SerialNumber, kb.Status.String(),
)
if err != nil {
errCh <- richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
return
}
resultCh <- kb
errCh <- nil
}(kindBox)
}
for i := 0; i < len(kindBoxes); i++ {
select {
case err := <-errCh:
if err != nil {
if err := tx.Rollback(); err != nil {
logger.L().Error("Rollback error: ", err)
}
return err
}
case <-resultCh:
case <-ctx.Done():
if err := tx.Rollback(); err != nil {
logger.L().Error("Rollback error: ", err)
}
return richerror.New(op).WithErr(ctx.Err()).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
}
if err := tx.Commit(); err != nil {
logger.L().Error("Commit error: ", err)
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return nil
}

View File

@ -2,6 +2,8 @@ package mysqlkindboxreq
import (
"context"
"database/sql"
"errors"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
@ -25,3 +27,102 @@ func (d DB) AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (en
return kindBoxReq, nil
}
func (d DB) AcceptKindBoxReq(ctx context.Context, kindBoxReqID, countAccepted uint) (finalErr error) {
op := richerror.Op("mysqlkindboxreq.AcceptKindBoxReq")
statement, err := d.conn.Conn().
Prepare(`update kind_box_reqs set count_accepted = ? , status = ? where id = ?`)
defer func() {
cErr := statement.Close()
if cErr != nil {
finalErr = cErr
}
}()
if err != nil {
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
_, eErr := statement.ExecContext(ctx, countAccepted, entity.KindBoxReqAcceptedStatus.String(), kindBoxReqID)
if eErr != nil {
return richerror.New(op).WithErr(eErr).
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)
_, sErr := scanKindBoxReq(row)
if sErr != nil {
if errors.Is(sErr, sql.ErrNoRows) {
return false, nil
}
return false, richerror.New(op).WithErr(sErr).WithMessage(errmsg.ErrorMsgCantScanQueryResult).
WithKind(richerror.KindUnexpected).WithMeta(map[string]any{"id": id})
}
return true, nil
}
func (d DB) RejectKindBoxReq(ctx context.Context, kindBoxReqID uint, description string) (finalErr error) {
op := richerror.Op("mysqlkindboxreq.RejectKindBoxReq")
statement, err := d.conn.Conn().
Prepare(`update kind_box_reqs set description = ? , status = ? where id = ?`)
defer func() {
cErr := statement.Close()
if cErr != nil {
finalErr = cErr
}
}()
if err != nil {
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
_, eErr := statement.ExecContext(ctx, description, entity.KindBoxReqRejectedStatus.String(), kindBoxReqID)
if eErr != nil {
return richerror.New(op).WithErr(eErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return nil
}
func (d DB) RollbackKindBoxRequestStatus(ctx context.Context, id uint) (finalErr error) {
op := richerror.Op("mysqlkindboxreq.RollbackKindBoxRequestStatus")
statement, err := d.conn.Conn().
Prepare(`update kind_box_reqs set status = ? where id = ?`)
defer func() {
cErr := statement.Close()
if cErr != nil {
finalErr = cErr
}
}()
if err != nil {
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
_, eErr := statement.ExecContext(ctx, entity.KindBoxReqPendingStatus.String(), id)
if eErr != nil {
return richerror.New(op).WithErr(eErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return nil
}

View File

@ -0,0 +1,20 @@
package mysqlkindboxreq
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)
func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) {
var kindBoxReq entity.KindBoxReq
var kindBoxStatus string
var kindBoxType string
err := scanner.Scan(&kindBoxReq.ID, &kindBoxReq.BenefactorID, &kindBoxType, &kindBoxReq.AddressID, &kindBoxReq.CountRequested, &kindBoxReq.CountAccepted,
&kindBoxReq.Description,
&kindBoxReq.ReferDate, &kindBoxStatus, &kindBoxReq.CreatedAt)
kindBoxReq.Status = entity.MapToKindBoxReqStatus(kindBoxStatus)
kindBoxReq.KindBoxType = entity.MapToKindBoxType(kindBoxType)
return kindBoxReq, err
}

View File

@ -0,0 +1,24 @@
-- +migrate Up
CREATE TABLE `kind_boxes`
(
`id` INT PRIMARY KEY AUTO_INCREMENT,
`kind_box_req_id` INT NOT NULL,
`benefactor_id` INT NOT NULL,
`type` ENUM ('on-table','cylindrical','stand-up') NOT NULL,
`total_amount` INT UNSIGNED NULL NULL,
`serial_number` varchar(255),
`status` varchar(255),
`sender_id` INT NULL,
`receiver_id` INT NULL,
`status_changed_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`kind_box_req_id`) REFERENCES `kind_box_reqs` (`id`),
FOREIGN KEY (`benefactor_id`) REFERENCES `benefactors` (`id`),
FOREIGN KEY (`sender_id`) REFERENCES `admins` (`id`),
FOREIGN KEY (`receiver_id`) REFERENCES `admins` (`id`),
index `index_serial_number` (`serial_number`)
);
-- +migrate Down
DROP TABLE `kind_boxes`;

View File

@ -6,21 +6,26 @@ import (
entity "git.gocasts.ir/ebhomengo/niki/entity"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"github.com/oklog/ulid/v2"
)
func (s Service) Add(ctx context.Context, req param.KindBoxAddRequest) (param.KindBoxAddResponse, error) {
const op = "adminkindboxservice.Add"
func (s Service) AddKindBoxAfterAcceptingRequest(ctx context.Context, req param.KindBoxAddAfterAcceptingReqRequest) (param.KindBoxAddAfterAcceptingReqResponse, error) {
const op = "adminkindboxservice.AddKindBoxAfterAcceptingRequest"
kindBox, err := s.repo.AddKindBox(ctx, entity.KindBox{
BenefactorID: req.BenefactorID,
var kindBoxes []entity.KindBox
for i := 0; i < int(req.Count); i++ {
kindBoxes = append(kindBoxes, entity.KindBox{
KindBoxReqID: req.KindBoxReqID,
SenderID: req.SenderID,
SerialNumber: req.SerialNumber,
BenefactorID: req.BenefactorID,
Type: req.Type,
Status: entity.KindBoxPendingSendStatus,
SerialNumber: ulid.Make().String(),
})
}
err := s.repo.AddBatchKindBox(ctx, kindBoxes)
if err != nil {
return param.KindBoxAddResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
return param.KindBoxAddAfterAcceptingReqResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.KindBoxAddResponse{KindBox: kindBox}, nil
return param.KindBoxAddAfterAcceptingReqResponse{}, nil
}

View File

@ -1,20 +1 @@
package adminkindboxservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) Delete(ctx context.Context, req param.KindBoxDeleteRequest) (param.KindBoxDeleteResponse, error) {
// TODO: Does business domain need to delete an kindbox ?
const op = "adminkindboxservice.Delete"
dErr := s.repo.DeleteKindBox(ctx, req.KindBoxID)
if dErr != nil {
return param.KindBoxDeleteResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected)
}
return param.KindBoxDeleteResponse{}, nil
}

View File

@ -1,19 +1 @@
package adminkindboxservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) Get(ctx context.Context, req param.KindBoxGetRequest) (param.KindBoxGetResponse, error) {
const op = "adminkindboxservice.Get"
kindBox, err := s.repo.GetKindBox(ctx, req.KindBoxID)
if err != nil {
return param.KindBoxGetResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.KindBoxGetResponse{KindBox: kindBox}, nil
}

View File

@ -1,18 +1 @@
package adminkindboxservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) GetAll(ctx context.Context, _ param.KindBoxGetAllRequest) (param.KindBoxGetAllResponse, error) {
const op = "adminkindboxservice.GetAll"
allKindBox, err := s.repo.GetAllKindBox(ctx)
if err != nil {
return param.KindBoxGetAllResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.KindBoxGetAllResponse{AllKindBox: allKindBox}, nil
}

View File

@ -7,22 +7,13 @@ import (
)
type Repository interface {
AddKindBox(ctx context.Context, kindBox entity.KindBox) (entity.KindBox, error)
UpdateKindBox(ctx context.Context, kindBoxID uint, kindBoxInput entity.KindBox) (entity.KindBox, error)
DeleteKindBox(ctx context.Context, kindBoxID uint) error
GetAllKindBox(ctx context.Context) ([]entity.KindBox, error)
GetKindBox(ctx context.Context, kindBox uint) (entity.KindBox, error)
AddBatchKindBox(ctx context.Context, kindBoxes []entity.KindBox) error
}
type Service struct {
repo Repository
}
// TODO: check validation.
// type BenefactorService interface {
// IsBenefactorExist(ctx context.Context, benefactorID uint) (bool, error)
// }
func New(repository Repository) Service {
return Service{
repo: repository,

View File

@ -1,29 +1 @@
package adminkindboxservice
import (
"context"
entity "git.gocasts.ir/ebhomengo/niki/entity"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) Update(ctx context.Context, req param.KindBoxUpdateRequest) (param.KindBoxUpdateResponse, error) {
// TODO: can benefactor update its Request ?
// TODO: Is Update Mothod Service Responsible to check which kindboxreqID belongs to benefactorID ?
// TODO: updating data(s) may have side-effect on other entities by masood-keshvary accepted -> rejected
const op = "adminkindboxservice.Update"
kindBox, uErr := s.repo.UpdateKindBox(ctx, req.KindBoxID, entity.KindBox{
TotalAmount: req.TotalAmount,
ReceiverID: req.ReceiverID,
SenderID: req.SenderID,
SerialNumber: req.SerialNumber,
Status: req.Status,
})
if uErr != nil {
return param.KindBoxUpdateResponse{}, richerror.New(op).WithErr(uErr).WithKind(richerror.KindUnexpected)
}
return param.KindBoxUpdateResponse{KindBox: kindBox}, nil
}

View File

@ -0,0 +1,54 @@
package adminkindboxreqservice
import (
"context"
"git.gocasts.ir/ebhomengo/niki/logger"
adminkindboxparam "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
// @see
// When confirming a request, should the senderID field, which represents the person sending the kind-box to the beneficiary,
// be filled at the same time? Or is it acceptable to confirm the request first and fill in the senderID field later?
//
func (s Service) Accept(ctx context.Context, req param.KindBoxReqAcceptRequest) (param.KindBoxReqAcceptResponse, error) {
const op = "adminkindboxreqservice.Accept"
err := s.repo.AcceptKindBoxReq(ctx, req.ID, req.CountAccepted)
if err != nil {
return param.KindBoxReqAcceptResponse{}, richerror.New(op).WithErr(err)
}
kindBoxReq, gErr := s.repo.GetByID(ctx, req.ID)
if gErr != nil {
return param.KindBoxReqAcceptResponse{}, richerror.New(op).WithErr(gErr)
}
_, kErr := s.kindBoxClient.AddKindBoxAfterAcceptingRequest(ctx, adminkindboxparam.KindBoxAddAfterAcceptingReqRequest{
BenefactorID: kindBoxReq.BenefactorID,
KindBoxReqID: kindBoxReq.ID,
Type: kindBoxReq.KindBoxType,
Count: kindBoxReq.CountAccepted,
})
if kErr != nil {
// rollback kind box request status
rErr := s.repo.RollbackKindBoxRequestStatus(ctx, req.ID)
if rErr != nil {
// log error
logger.L().Error(rErr.Error())
}
return param.KindBoxReqAcceptResponse{}, richerror.New(op).WithErr(kErr)
}
return param.KindBoxReqAcceptResponse{
KindBoxReqID: kindBoxReq.ID,
KindBoxReqStatus: kindBoxReq.Status,
CountRequested: kindBoxReq.CountRequested,
CountAccepted: kindBoxReq.CountAccepted,
ReferDate: kindBoxReq.ReferDate,
AddressID: kindBoxReq.AddressID,
}, nil
}

View File

@ -1,17 +1 @@
package adminkindboxreqservice
// func (s Service) Add(ctx context.Context, req param.KindBoxReqAddRequest) (param.KindBoxReqAddResponse, error) {
// const op = "adminkindboxreqservice.Add"
//
// kindBoxReq, err := s.repo.AddKindBoxReq(ctx, entity.KindBoxReq{
// BenefactorID: req.BenefactorID,
// KindBoxType: req.TypeID,
// CountRequested: req.CountRequested,
// Status: entity.KindBoxReqPendingStatus,
// })
// if err != nil {
// return param.KindBoxReqAddResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqAddResponse{KindBoxReq: kindBoxReq}, nil
//}

View File

@ -1,20 +1 @@
package adminkindboxreqservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/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) {
// TODO: Does business domain need to delete an kindboxreq ?
const op = "adminkindboxreqservice.Delete"
dErr := s.repo.DeleteKindBoxReq(ctx, req.KindBoxReqID)
if dErr != nil {
return param.KindBoxReqDeleteResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected)
}
return param.KindBoxReqDeleteResponse{}, nil
}

View File

@ -1,20 +1 @@
package adminkindboxreqservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) Get(ctx context.Context, req param.KindBoxReqGetRequest) (param.KindBoxReqGetResponse, error) {
const op = "adminkindboxreqservice.Get"
// TODO : ref to service.Update()
kindBoxReq, err := s.repo.GetKindBoxReq(ctx, req.KindBoxReqID)
if err != nil {
return param.KindBoxReqGetResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.KindBoxReqGetResponse{KindBoxReq: kindBoxReq}, nil
}

View File

@ -1,20 +1 @@
package adminkindboxreqservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
// TODO: Pagination, Filters, Sort.
func (s Service) GetAll(ctx context.Context, _ param.KindBoxReqGetAllRequest) (param.KindBoxReqGetAllResponse, error) {
const op = "adminkindboxreqservice.GetAll"
allKindBoxReq, err := s.repo.GetAllKindBoxReq(ctx)
if err != nil {
return param.KindBoxReqGetAllResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.KindBoxReqGetAllResponse{AllKindBoxReq: allKindBoxReq}, nil
}

View File

@ -0,0 +1,32 @@
package adminkindboxreqservice
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) Reject(ctx context.Context, req param.KindBoxReqRejectRequest) (param.KindBoxReqRejectResponse, error) {
const op = "adminkindboxreqservice.Reject"
err := s.repo.RejectKindBoxReq(ctx, req.ID, req.Description)
if err != nil {
return param.KindBoxReqRejectResponse{}, richerror.New(op).WithErr(err)
}
kindBoxReq, gErr := s.repo.GetByID(ctx, req.ID)
if gErr != nil {
return param.KindBoxReqRejectResponse{}, richerror.New(op).WithErr(err)
}
return param.KindBoxReqRejectResponse{
ID: kindBoxReq.ID,
KindBoxType: kindBoxReq.KindBoxType,
CountRequested: kindBoxReq.CountRequested,
BenefactorID: kindBoxReq.BenefactorID,
Status: kindBoxReq.Status,
Description: kindBoxReq.Description,
ReferDate: kindBoxReq.ReferDate,
AddressID: kindBoxReq.AddressID,
}, nil
}

View File

@ -3,16 +3,19 @@ package adminkindboxreqservice
import (
"context"
entity "git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/entity"
adminkindboxparam "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
)
type Repository interface {
AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error)
UpdateKindBoxReq(ctx context.Context, kindBoxReqID uint, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error)
// TODO: can benefactor cancel its request ?
DeleteKindBoxReq(ctx context.Context, kindBoxReqID uint) error
GetAllKindBoxReq(ctx context.Context) ([]entity.KindBoxReq, error)
GetKindBoxReq(ctx context.Context, kindBoxReqID uint) (entity.KindBoxReq, error)
AcceptKindBoxReq(ctx context.Context, kindBoxReqID uint, countAccepted uint) error
GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error)
RejectKindBoxReq(ctx context.Context, kindBoxReqID uint, description string) error
RollbackKindBoxRequestStatus(ctx context.Context, id uint) error
}
type KindBoxClient interface {
AddKindBoxAfterAcceptingRequest(ctx context.Context, param adminkindboxparam.KindBoxAddAfterAcceptingReqRequest) (adminkindboxparam.KindBoxAddAfterAcceptingReqResponse, error)
}
// TODO: check validation.
@ -23,10 +26,12 @@ type Repository interface {
type Service struct {
repo Repository
// benefactorService BenefactorService
kindBoxClient KindBoxClient
}
func New(repository Repository) Service {
func New(repository Repository, kindBoxClient KindBoxClient) Service {
return Service{
repo: repository,
kindBoxClient: kindBoxClient,
}
}

View File

@ -1,29 +1 @@
package adminkindboxreqservice
//
// import (
// "context"
//
// entity "git.gocasts.ir/ebhomengo/niki/entity"
// param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
// richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
//)
//
// func (s Service) Update(ctx context.Context, req param.KindBoxReqUpdateRequest) (param.KindBoxReqUpdateResponse, error) {
// // TODO: can benefactor update its request ?
// // TODO: Is Update Mothod Service Responsible to check which kindboxreqID belongs to benefactorID ?
// // TODO: updating data(s) may have side-effect on other entities by masood-keshvary accepted -> rejected
//
// const op = "adminkindboxreqservice.Update"
//
// kindBoxReq, uErr := s.repo.UpdateKindBoxReq(ctx, req.KindBoxReqID, entity.KindBoxReq{
// BenefactorID: req.BenefactorID,
// TypeID: req.TypeID,
// CountRequested: req.CountRequested,
// })
// if uErr != nil {
// return param.KindBoxReqUpdateResponse{}, richerror.New(op).WithErr(uErr).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqUpdateResponse{KindBoxReq: kindBoxReq}, nil
//}

View File

@ -1,13 +1 @@
package benefactorkindboxreqservice
// func (s Service) Delete(ctx context.Context, req param.KindBoxReqDeleteRequest) (param.KindBoxReqDeleteResponse, error) {
// // TODO: Does business domain need to delete an kindboxreq ?
// const op = "userkindboxreqservice.Delete"
//
// dErr := s.repo.DeleteKindBoxReq(ctx, req.KindBoxReqID)
// if dErr != nil {
// return param.KindBoxReqDeleteResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqDeleteResponse{}, nil
//}

View File

@ -1,12 +1 @@
package benefactorkindboxreqservice
// func (s Service) Get(ctx context.Context, req param.KindBoxReqGetRequest) (param.KindBoxReqGetResponse, error) {
// const op = "userkindboxreqservice.Get"
//
// kindBoxReq, err := s.repo.GetKindBoxReq(ctx, req.KindBoxReqID)
// if err != nil {
// return param.KindBoxReqGetResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqGetResponse{KindBoxReq: kindBoxReq}, nil
//}

View File

@ -1,13 +1 @@
package benefactorkindboxreqservice
//// TODO: Pagination, Filters, Sort.
// func (s Service) GetAll(ctx context.Context, req param.KindBoxReqGetAllRequest) (param.KindBoxReqGetAllResponse, error) {
// const op = "userkindboxreqservice.GetAll"
//
// allKindBoxReq, err := s.repo.GetAllKindBoxReq(ctx, req.BenefactorID)
// if err != nil {
// return param.KindBoxReqGetAllResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqGetAllResponse{AllKindBoxReq: allKindBoxReq}, nil
//}

View File

@ -8,11 +8,6 @@ import (
type Repository interface {
AddKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error)
// UpdateKindBoxReq(ctx context.Context, kindBoxReqID uint, kindBoxReq entity.KindBoxReq) (entity.KindBoxReq, error)
// TODO: can benefactor cancel its request ?
// DeleteKindBoxReq(ctx context.Context, kindBoxReqID uint) error
// GetAllKindBoxReq(ctx context.Context, benefactorID uint) ([]entity.KindBoxReq, error)
// GetKindBoxReq(ctx context.Context, kindBoxReqID uint) (entity.KindBoxReq, error)
}
type Service struct {

View File

@ -1,18 +1 @@
package benefactorkindboxreqservice
// func (s Service) Update(ctx context.Context, req param.KindBoxReqUpdateRequest) (param.KindBoxReqUpdateResponse, error) {
// // TODO: can benefactor update its request ?
// // TODO: Is Update Mothod Service Responsible to check which kindboxreqID belongs to benefactorID ?
// const op = "userkindboxreqservice.Update"
//
// kindBoxReq, uErr := s.repo.UpdateKindBoxReq(ctx, req.KindBoxReqID, entity.KindBoxReq{
// BenefactorID: req.BenefactorID,
// KindBoxType: req.TypeID,
// CountRequested: req.CountRequested,
// })
// if uErr != nil {
// return param.KindBoxReqUpdateResponse{}, richerror.New(op).WithErr(uErr).WithKind(richerror.KindUnexpected)
// }
//
// return param.KindBoxReqUpdateResponse{KindBoxReq: kindBoxReq}, nil
//}

View File

@ -1,49 +1 @@
package adminkindboxvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"github.com/go-ozzo/ozzo-validation/is"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateAddRequest(req param.KindBoxAddRequest) (map[string]string, error) {
const op = "adminkindboxvalidator.KindBoxAddRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.SerialNumber, validation.Required, is.Alphanumeric),
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.SenderID,
validation.Required,
validation.By(v.doesEmployeeExist)),
validation.Field(&req.KindBoxReqID,
validation.Required,
validation.By(v.doesKindBoxRequestExist)),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,45 +1 @@
package adminkindboxvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateDeleteRequest(req param.KindBoxDeleteRequest) (map[string]string, error) {
const op = "adminkindboxvalidator.ValidateDeleteRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.KindBoxID,
validation.Required,
validation.By(v.hasPendingStatus),
validation.By(v.doesKindBoxExist),
validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,44 +1 @@
package adminkindboxvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateGetRequest(req param.KindBoxGetRequest) (map[string]string, error) {
const op = "adminkindboxvalidator.ValidateGetRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.KindBoxID,
validation.Required,
validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID)),
validation.By(v.doesKindBoxExist)),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,59 +1 @@
package adminkindboxvalidator
import (
"errors"
"git.gocasts.ir/ebhomengo/niki/entity"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"github.com/go-ozzo/ozzo-validation/is"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateUpdateRequest(req param.KindBoxUpdateRequest) (map[string]string, error) {
const op = "adminkindboxvalidator.ValidateUpdateRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.KindBoxID,
validation.Required,
validation.By(v.doesKindBoxExist),
validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))),
validation.Field(&req.SerialNumber, is.Alphanumeric),
validation.Field(&req.TotalAmount, validation.Min(0)),
validation.Field(&req.SenderID,
validation.By(v.doesEmployeeExist)),
validation.Field(&req.ReceiverID,
validation.By(v.doesEmployeeExist)),
validation.Field(&req.Status,
validation.In(entity.AllKindBoxStatus())),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,12 +1,5 @@
package adminkindboxvalidator
import (
"fmt"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
type Repository interface {
KindBoxRequestExist(id uint) (bool, error)
EmployeeExist(id uint) (bool, error)
@ -24,97 +17,3 @@ type Validator struct {
func New(repo Repository) Validator {
return Validator{repo: repo}
}
func (v Validator) doesKindBoxRequestExist(value interface{}) error {
receiverID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.KindBoxRequestExist(receiverID)
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
}
return nil
}
func (v Validator) doesEmployeeExist(value interface{}) error {
senderID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.EmployeeExist(senderID)
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
}
return nil
}
func (v Validator) doesBenefactorExist(value interface{}) error {
benefactorID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.BenefactorExist(benefactorID)
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
}
return nil
}
func (v Validator) doesKindBoxExist(value interface{}) error {
kindboxID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
}
_, err := v.repo.KindBoxExist(kindboxID)
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
}
}
// TODO: this temperary to ignore linter error. (unused function)
// func (v Validator) hasCorrectStatus(value interface{}) error {
// status, ok := value.(string)
// if !ok {
// return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
// }
// _, err := v.repo.CheckStatus(status)
// 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
}

View File

@ -0,0 +1,42 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateAcceptRequest(req param.KindBoxReqAcceptRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateAcceptRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.ID, validation.Required, validation.By(v.doesKindBoxRequestExist), validation.By(v.CheckKindBoxReqStatusForAccepting)),
validation.Field(&req.CountAccepted,
validation.Required,
validation.Min(uint(MinKindBoxReq)), validation.Max(uint(MaxKindBoxReq)),
),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,46 +1 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateAddRequest(req param.KindBoxReqAddRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateAddRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.CountRequested, validation.Required, validation.Min(MinKindBoxReq), validation.Max(MaxKindBoxReq)),
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.TypeID,
validation.Required,
validation.By(v.doesTypeExist)),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,45 +1 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateDeleteRequest(req param.KindBoxReqDeleteRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateDeleteRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.KindBoxReqID,
validation.Required,
validation.By(v.hasPendingStatus),
validation.By(v.doesKindBoxRequestExist),
validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,44 +1 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateGetRequest(req param.KindBoxReqGetRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateGetRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.BenefactorID,
validation.Required,
validation.By(v.doesBenefactorExist)),
validation.Field(&req.KindBoxReqID,
validation.Required,
validation.By(v.doesKindBoxRequestExist),
validation.By(v.doesKindBoxBelongToBenefactor(req.BenefactorID))),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -0,0 +1,41 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateRejectRequest(req param.KindBoxReqRejectRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateRejectRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.ID, validation.Required, validation.By(v.doesKindBoxRequestExist), validation.By(v.CheckKindBoxReqStatusForRejecting)),
validation.Field(&req.Description,
validation.Required,
),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,50 +1 @@
package adminkindboxreqvalidator
import (
"errors"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
func (v Validator) ValidateUpdateRequest(req param.KindBoxReqUpdateRequest) (map[string]string, error) {
const op = "adminkindboxreqvalidator.ValidateUpdateRequest"
if err := validation.ValidateStruct(&req,
validation.Field(&req.CountRequested, validation.Min(MinKindBoxReq), validation.Max(MaxKindBoxReq)),
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.TypeID,
validation.By(v.doesTypeExist)),
); err != nil {
fieldErrors := make(map[string]string)
var errV validation.Errors
if errors.As(err, &errV) {
for key, value := range errV {
if value != nil {
fieldErrors[key] = value.Error()
}
}
}
return fieldErrors, richerror.New(op).
WithMessage(errmsg.ErrorMsgInvalidInput).
WithKind(richerror.KindInvalid).
WithMeta(map[string]interface{}{"req": req}).
WithErr(err)
}
return map[string]string{}, nil
}

View File

@ -1,10 +1,12 @@
package adminkindboxreqvalidator
import (
"context"
"errors"
"fmt"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
const (
@ -13,11 +15,8 @@ const (
)
type Repository interface {
BenefactorExist(id int) (bool, error)
KindBoxRequestExist(id int) (bool, error)
TypeExist(id int) (bool, error)
KindBoxBelongToBenefactor(benefactorID uint, kindboxID uint) (bool, error)
PendingStatus(id uint) (bool, error)
KindBoxRequestExist(id uint) (bool, error)
GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error)
}
type Validator struct {
@ -28,68 +27,50 @@ func New(repo Repository) Validator {
return Validator{repo: repo}
}
func (v Validator) doesBenefactorExist(value interface{}) error {
benefactorID, ok := value.(int)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.BenefactorExist(benefactorID)
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) doesKindBoxRequestExist(value interface{}) error {
kindboxreqID, ok := value.(int)
kindboxreqID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.KindBoxRequestExist(kindboxreqID)
if isExist, err := v.repo.KindBoxRequestExist(kindboxreqID); !isExist || err != nil {
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
return err
}
if !isExist {
return errors.New("kind box request is not exist")
}
}
return nil
}
func (v Validator) doesTypeExist(value interface{}) error {
typeID, ok := value.(int)
func (v Validator) CheckKindBoxReqStatusForAccepting(value interface{}) error {
kindboxreqID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.TypeExist(typeID)
kindBox, err := v.repo.GetByID(context.Background(), kindboxreqID)
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
return err
}
if kindBox.Status != entity.KindBoxReqPendingStatus {
return fmt.Errorf(errmsg.ErrorMsgAcceptKindBoxReqStatus)
}
return nil
}
func (v Validator) hasPendingStatus(value interface{}) error {
kindboxID, ok := value.(uint)
func (v Validator) CheckKindBoxReqStatusForRejecting(value interface{}) error {
kindboxreqID, ok := value.(uint)
if !ok {
return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
}
_, err := v.repo.PendingStatus(kindboxID)
kindBox, err := v.repo.GetByID(context.Background(), kindboxreqID)
if err != nil {
return fmt.Errorf(errmsg.ErrorMsgNotFound)
return err
}
if kindBox.Status != entity.KindBoxReqPendingStatus {
return fmt.Errorf(errmsg.ErrorMsgRejectKindBoxReqStatus)
}
return nil