Compare commits

...

16 Commits

Author SHA1 Message Date
Erfan Mohammadi 89b23d1999 Update .gitea/workflows/demo.yaml
checks / check and test (push) Has been cancelled Details
2024-07-13 16:10:03 +00:00
Erfan Mohammadi 8968eea907 Merge pull request 'Update .gitea/workflows/demo.yaml' (#2) from erfantech-patch-1 into develop
checks / check and test (push) Waiting to run Details
Reviewed-on: #2
2024-07-13 15:59:13 +00:00
Erfan Mohammadi 9ec80deb62 Update .gitea/workflows/demo.yaml
checks / check and test (push) Waiting to run Details
checks / check and test (pull_request) Has been cancelled Details
2024-07-13 15:57:26 +00:00
Erfan Mohammadi c1090b1516 Add .gitea/workflows/demo.yaml
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run Details
2024-07-13 15:49:11 +00:00
Erfan Mohammadi 15698b18f9 fix(niki): update kindbox request by admin 2024-07-10 09:45:20 +03:30
AMiR ecb3e9aedc "feat(niki): add update kind box request by admin" 2024-07-10 09:45:11 +03:30
hossein 9de27badb9 Merge pull request 'feat(niki): get all kindboxes by admin' (#75) from stage/erfan/admin-getall-kindboxes into develop
Reviewed-on: ebhomengo/niki#75
2024-07-10 05:50:39 +00:00
Erfan Mohammadi bf9f79a524 feat(niki): get all kindboxes by admin 2024-07-09 20:47:04 +03:30
Iman Mirazimi ec769748fe feat(niki): get-getall kindboxreq with page-filter-sort by benefactor 2024-07-03 21:24:24 +03:30
Erfan Mohammadi 47bc77baee feat(niki): admin assign kindbox to a agent 2024-07-03 15:52:53 +03:30
Erfan Mohammadi 8a66e43789 feat(niki): admin get kindbox 2024-07-03 14:32:07 +03:30
alikafy 36d34b2b6b feat(kindbox_req): Add API for adding kindbox req by admin 2024-07-03 10:17:56 +03:30
alikafy 4185ef594b fix: rebase 2024-07-03 10:17:54 +03:30
Erfan Mohammadi 620db23582 feat(niki): benefactor requests emptying a KindBox 2024-07-03 06:27:51 +00:00
Erfan Mohammadi 857d26fd10 feat(niki): agent get all delivery awaiting kindboxreqs 2024-06-19 18:02:28 +03:30
Erfan Mohammadi 5eb962dc43 fix(repository): replace "assigned-sender-agent" with entity.KindBoxReqAssignedSenderAgentStatus.String() 2024-06-12 17:46:08 +00:00
211 changed files with 5577 additions and 854 deletions

View File

@ -0,0 +1,12 @@
name: checks
on:
- push
- pull_request
jobs:
lint:
name: check and test
runs-on: ubuntu-latest
steps:
- name: hello
run: echo "hello world"

View File

@ -16,7 +16,7 @@ import (
// @Param Request body adminserviceparam.LoginWithPhoneNumberRequest true "Admin login request body"
// @Success 200 {object} adminserviceparam.LoginWithPhoneNumberResponse
// @Failure 400 {string} "Bad request"
// @Router /admins/login-by-phone [post]
// @Router /admins/login-by-phone [post].
func (h Handler) LoginByPhoneNumber(c echo.Context) error {
var req adminserviceparam.LoginWithPhoneNumberRequest

View File

@ -17,7 +17,7 @@ import (
// @Success 200 {object} adminserviceparam.RegisterResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admins/register [post]
// @Router /admins/register [post].
func (h Handler) Register(c echo.Context) error {
var req adminserviceparam.RegisterRequest

View File

@ -0,0 +1,47 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
)
// AssignReceiverAgent godoc
// @Summary Admin assign receiver agent to kindbox
// @Tags KindBox
// @Accept json
// @Produce json
// @Param id path int true "KindBox ID"
// @Param Request body param.AssignReceiverRequest true "Assign Receiver Agent Request Body"
// @Success 204
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxes/assign-receiver-agent/{id} [patch].
func (h Handler) AssignReceiverAgent(c echo.Context) error {
var req param.AssignReceiverRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
if fieldErrors, err := h.adminKindBoxVld.ValidateAssignReceiverAgent(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
sErr := h.adminKindBoxSvc.AssignReceiverAgent(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusNoContent, nil)
}

View File

@ -0,0 +1,43 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
)
// Get godoc
// @Summary Get a specific kind box by admin
// @Description This endpoint retrieves a specific kind box by admin
// @Tags KindBox
// @Accept json
// @Produce json
// @Param id path int true "Kind box ID"
// @Success 200 {object} param.KindBoxGetResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxes/{id} [get].
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.StatusOK, resp)
}

View File

@ -0,0 +1,67 @@
package adminkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param"
"github.com/labstack/echo/v4"
)
// GetAll godoc
// @Summary Get all KindBoxes by admin
// @Description Retrieves a list of all KindBoxes with filtering, sorting, and pagination options
// @Tags KindBox
// @Accept json
// @Produce json
// @Param filter_id query int false "Filter by ID"
// @Param filter_kind_box_req_id query int false "Filter by KindBox request ID"
// @Param filter_benefactor_id query int false "Filter by benefactor ID"
// @Param filter_kind_box_type query string false "Filter by KindBox type" Enums(on-table,cylindrical,stand-up)
// @Param filter_amount query int false "Filter by amount"
// @Param filter_serial_number query string false "Filter by serial number"
// @Param filter_status query string false "Filter by status" Enums(delivered,ready-to-return,assigned-receiver-agent,returned,enumerated)
// @Param filter_delivered_at query string false "Filter by delivered at" Format(date-time)
// @Param filter_return_refer_time_id query int false "Filter by return refer time ID"
// @Param filter_return_refer_date query string false "Filter by return refer date" Format(date)
// @Param filter_return_address_id query int false "Filter by return address ID"
// @Param filter_receiver_agent_id query int false "Filter by receiver agent ID"
// @Param filter_returned_at query string false "Filter by returned at" Format(date-time)
// @Param filter_sender_agent_id query int false "Filter by sender agent ID"
// @Param filter_deliver_refer_date query string false "Filter by deliver refer date" Format(date)
// @Param filter_deliver_address_id query int false "Filter by deliver address ID"
// @Param page_number query int false "Page number"
// @Param page_size query int false "Page size"
// @Param sort_field query string false "Sort by field" Enums(id,kind_box_req_id,benefactor_id,kind_box_type,amount,serial_number,status,delivered_at,return_refer_time_id,return_refer_date,return_address_id,receiver_agent_id,returned_at,sender_agent_id,deliver_refer_date,deliver_address_id)
// @Param sort_direction query string false "Sort order" Enums(asc,desc)
// @Success 200 {object} param.KindBoxGetAllResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxes [get].
func (h Handler) GetAll(c echo.Context) error {
var req param.KindBoxGetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
req.Filter = queryparam.GetFilterParams(c)
if fieldErrors, err := h.adminKindBoxVld.ValidateGetAll(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
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.StatusOK, resp)
}

View File

@ -1,8 +1,17 @@
package adminkindboxhandler
import (
echo "github.com/labstack/echo/v4"
"git.gocasts.ir/ebhomengo/niki/delivery/http_server/middleware"
"git.gocasts.ir/ebhomengo/niki/entity"
"github.com/labstack/echo/v4"
)
func (h Handler) SetRoutes(_ *echo.Echo) {
func (h Handler) SetRoutes(e *echo.Echo) {
r := e.Group("/admin/kindboxes")
r.Use(middleware.Auth(h.authSvc, h.authConfig))
r.GET("/:id", h.Get, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxGetPermission))
r.PATCH("/assign-receiver-agent/:id", h.AssignReceiverAgent, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxAssignReceiverAgentPermission))
r.GET("", h.GetAll, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxGetAllPermission))
}

View File

@ -20,7 +20,7 @@ import (
// @Success 200 {object} param.KindBoxReqAcceptResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/accept-kind-box-req/{id} [patch]
// @Router /admin/kindboxreqs/accept-kind-box-req/{id} [patch].
func (h Handler) Accept(c echo.Context) error {
var req param.KindBoxReqAcceptRequest
if bErr := c.Bind(&req); bErr != nil {

View File

@ -0,0 +1,44 @@
package adminkindboxreqhandler
import (
"net/http"
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"
echo "github.com/labstack/echo/v4"
)
// AddKindBoxReq godoc
// @Summary Add a new kind box request for a benefactor by admin
// @Tags KindBoxReq
// @Accept json
// @Produce json
// @Param Request body param.KindBoxReqAddRequest true "New kind box request details"
// @Success 200 {object} param.KindBoxReqAddResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs [post].
func (h Handler) AddKindBoxReq(c echo.Context) error {
req := param.KindBoxReqAddRequest{}
if err := c.Bind(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, errmsg.ErrBadRequest)
}
result := h.adminKindBoxReqVld.ValidateAddRequest(req)
if result != nil {
msg, code := httpmsg.Error(result.Err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": result.Fields,
})
}
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

@ -20,7 +20,7 @@ import (
// @Success 200 {object} param.AssignSenderResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/assign-sender-agent/{id} [patch]
// @Router /admin/kindboxreqs/assign-sender-agent/{id} [patch].
func (h Handler) AssignSenderAgent(c echo.Context) error {
var req param.AssignSenderRequest

View File

@ -19,7 +19,7 @@ import (
// @Success 200 {object} param.DeliverKindBoxReqResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/deliver-kind-box-req/{id} [patch]
// @Router /admin/kindboxreqs/deliver-kind-box-req/{id} [patch].
func (h Handler) Deliver(c echo.Context) error {
var req param.DeliverKindBoxReqRequest

View File

@ -1,13 +1,10 @@
package adminkindboxreqhandler
import (
"net/http"
"strconv"
paginationparam "git.gocasts.ir/ebhomengo/niki/param"
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"
"net/http"
)
// GetAll godoc
@ -20,23 +17,13 @@ import (
// @Success 200 {object} param.KindBoxReqGetAllResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs [get]
// @Router /admin/kindboxreqs [get].
func (h Handler) GetAll(c echo.Context) error {
var req param.KindBoxReqGetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
var paginationReq paginationparam.PaginationRequest
// TODO : pkg convert string to uint
//nolint
pageNumber, _ := strconv.ParseUint(c.QueryParam("page_number"), 0, 64)
//nolint
pageSize, _ := strconv.ParseUint(c.QueryParam("page_size"), 0, 64)
paginationReq.PageSize = uint(pageSize)
paginationReq.PageNumber = uint(pageNumber)
resp, sErr := h.adminKindBoxReqSvc.GetAll(c.Request().Context(), req, paginationReq)
resp, sErr := h.adminKindBoxReqSvc.GetAll(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)

View File

@ -0,0 +1,64 @@
package adminkindboxreqhandler
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/pkg/claim"
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param"
"github.com/labstack/echo/v4"
)
// GetAllAwaitingDelivery godoc
// @Summary Get all awaiting delivery KindBox requests
// @Description Retrieves a list of all awaiting KindBox requests with filtering, sorting, and pagination options
// @Tags KindBoxReq
// @Accept json
// @Produce json
// @Param filter_id query int false "Filter by ID"
// @Param filter_benefactor_id query int false "Filter by benefactor ID"
// @Param filter_kind_box_type query entity.KindBoxType false "Filter by KindBox type" Format(enum)
// @Param filter_count_requested query int false "Filter by count requested"
// @Param filter_count_accepted query int false "Filter by count accepted"
// @Param filter_deliver_refer_time_id query int false "Filter by deliver refer time ID"
// @Param filter_deliver_refer_date query string false "Filter by deliver refer date" Format(date)
// @Param filter_deliver_address_id query int false "Filter by deliver address ID"
// @Param page_number query int false "Page number"
// @Param page_size query int false "Page size"
// @Param sort_field query string false "Sort by field" Enums(id,benefactor_id,kind_box_type,count_requested,count_accepted,deliver_refer_time_id,deliver_refer_date,deliver_address_id)
// @Param sort_direction query string false "Sort order" Enums(asc,desc)
// @Success 200 {object} param.DeliveryAwaitingGetAllResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/awaiting-delivery [get]
func (h Handler) GetAllAwaitingDelivery(c echo.Context) error {
var req param.DeliveryAwaitingGetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
req.Filter = queryparam.GetFilterParams(c)
if fieldErrors, err := h.adminKindBoxReqVld.ValidateGetAllAwaitingDelivery(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
req.Filter["sender_agent_id"] = claim.GetClaimsFromEchoContext(c).UserID
req.Filter["status"] = entity.KindBoxReqAssignedSenderAgentStatus.String()
resp, sErr := h.adminKindBoxReqSvc.GetAllAwaitingDelivery(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusOK, resp)
}

View File

@ -20,7 +20,7 @@ import (
// @Success 200 {object} param.KindBoxReqRejectResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/reject-kind-box-req/{id} [patch]
// @Router /admin/kindboxreqs/reject-kind-box-req/{id} [patch].
func (h Handler) Reject(c echo.Context) error {
var req param.KindBoxReqRejectRequest
if bErr := c.Bind(&req); bErr != nil {

View File

@ -10,10 +10,13 @@ func (h Handler) SetRoutes(e *echo.Echo) {
r := e.Group("/admin/kindboxreqs")
r.Use(middleware.Auth(h.authSvc, h.authConfig))
r.POST("", h.AddKindBoxReq, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqAddPermission))
r.PATCH("/accept-kind-box-req/:id", h.Accept, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqAcceptPermission))
r.PATCH("/reject-kind-box-req/:id", h.Reject, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqRejectPermission))
r.PATCH("/deliver-kind-box-req/:id", h.Deliver, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqDeliverPermission))
r.PATCH("/assign-sender-agent/:id", h.AssignSenderAgent, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqAssignSenderAgentPermission))
r.GET("", h.GetAll, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqGetAllPermission))
r.GET("/awaiting-delivery/:id", h.GetAwaitingDelivery, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqGetAwaitingDeliveryPermission))
r.GET("/awaiting-delivery", h.GetAllAwaitingDelivery, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqGetAwaitingDeliveryPermission))
r.PUT("/:id", h.Update, middleware.AdminAuthorization(h.adminAuthorizeSvc, entity.AdminKindBoxReqUpdatePermission))
}

View File

@ -0,0 +1,44 @@
package adminkindboxreqhandler
import (
param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
"net/http"
)
// Update godoc
// @Summary Update kind box request by admin
// @Tags KindBoxReq
// @Accept json
// @Produce json
// @Param id path int true "KindBoxReq ID"
// @Param Request body param.KindBoxReqUpdateRequest true "Update KindBoxReq Request Body"
// @Success 204
// @Failure 400 {string} "Bad request"
// @Security AuthBearerAdmin
// @Router /admin/kindboxreqs/{id} [put].
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,
})
}
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.StatusNoContent, nil)
}

View File

@ -19,7 +19,7 @@ import (
// @Success 201 {object} param.BenefactorAddAddressResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /address/ [post]
// @Router /address/ [post].
func (h Handler) AddAddress(c echo.Context) error {
req := param.BenefactorAddAddressRequest{}
if bErr := c.Bind(&req); bErr != nil {

View File

@ -18,7 +18,7 @@ import (
// @Success 200 {object} param.GetAddressResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /address/{id} [get]
// @Router /address/{id} [get].
func (h Handler) GetAddress(c echo.Context) error {
var req param.GetAddressRequest
if bErr := echo.PathParamsBinder(c).Uint("id", &req.AddressID).BindError(); bErr != nil {

View File

@ -17,7 +17,7 @@ import (
// @Success 200 {object} param.GetAllAddressesResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /address/ [get]
// @Router /address/ [get].
func (h Handler) GetAddresses(c echo.Context) error {
var req param.GetAllAddressesRequest

View File

@ -15,7 +15,7 @@ import (
// @Produce json
// @Success 200 {object} addressparam.GetAllCitiesResponse
// @Failure 400 {string} "Bad request"
// @Router /address/cities [get]
// @Router /address/cities [get].
func (h Handler) GetAllCities(c echo.Context) error {
var req addressparam.GetAllCitiesRequest

View File

@ -15,7 +15,7 @@ import (
// @Produce json
// @Success 200 {object} addressparam.GetAllProvincesResponse
// @Failure 400 {string} "Bad request"
// @Router /address/provinces [get]
// @Router /address/provinces [get].
func (h Handler) GetAllProvinces(c echo.Context) error {
var req addressparam.GetAllProvincesRequest

View File

@ -17,7 +17,7 @@ import (
// @Param Request body benefactoreparam.LoginOrRegisterRequest true "Login or register request details"
// @Success 200 {object} benefactoreparam.LoginOrRegisterResponse
// @Failure 400 {string} "Bad request"
// @Router /benefactor/login-register [post]
// @Router /benefactor/login-register [post].
func (h Handler) loginOrRegister(c echo.Context) error {
var req benefactoreparam.LoginOrRegisterRequest

View File

@ -17,7 +17,7 @@ import (
// @Param Request body benefactoreparam.SendOtpRequest true "Send OTP request details"
// @Success 200 {object} benefactoreparam.SendOtpResponse
// @Failure 400 {string} "Bad request"
// @Router /benefactor/send-otp [post]
// @Router /benefactor/send-otp [post].
func (h Handler) SendOtp(c echo.Context) error {
var req benefactoreparam.SendOtpRequest

View File

@ -18,7 +18,7 @@ import (
// @Success 200 {object} param.KindBoxGetResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxes/{id} [get]
// @Router /benefactor/kindboxes/{id} [get].
func (h Handler) Get(c echo.Context) error {
var req param.KindBoxGetRequest
if bErr := c.Bind(&req); bErr != nil {

View File

@ -16,7 +16,7 @@ import (
// @Success 200 {object} param.KindBoxGetResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxes/ [get]
// @Router /benefactor/kindboxes [get]
func (h Handler) GetAll(c echo.Context) error {
var req param.KindBoxGetAllRequest
if bErr := c.Bind(&req); bErr != nil {

View File

@ -0,0 +1,48 @@
package benefactorkindboxhandler
import (
"net/http"
param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box"
"git.gocasts.ir/ebhomengo/niki/pkg/claim"
httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
"github.com/labstack/echo/v4"
)
// RegisterEmptyingRequest godoc
// @Summary Register a new emptying request for a kind box by benefactor
// @Tags Benefactor
// @Accept json
// @Produce json
// @Param id path int true "KindBox ID"
// @Param Request body param.KindBoxRegisterEmptyingRequest true "Request body"
// @Success 204 {string} "No content"
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxes/{id}/emptying-requests [patch].
func (h Handler) RegisterEmptyingRequest(c echo.Context) error {
var req param.KindBoxRegisterEmptyingRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
claims := claim.GetClaimsFromEchoContext(c)
req.BenefactorID = claims.UserID
if fieldErrors, err := h.benefactorKindBoxVld.ValidateRegisterEmptyingRequest(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
sErr := h.benefactorKindBoxSvc.RegisterEmptyingRequest(c.Request().Context(), req)
if sErr != nil {
msg, code := httpmsg.Error(sErr)
return echo.NewHTTPError(code, msg)
}
return c.JSON(http.StatusNoContent, nil)
}

View File

@ -1,12 +1,20 @@
package benefactorkindboxhandler
import (
echo "github.com/labstack/echo/v4"
"git.gocasts.ir/ebhomengo/niki/delivery/http_server/middleware"
"git.gocasts.ir/ebhomengo/niki/entity"
"github.com/labstack/echo/v4"
)
func (h Handler) SetRoutes(e *echo.Echo) {
r := e.Group("/benefactor/kindboxes")
r.GET("/:id", h.Get).Name = "benefactor-getkindboxbyid"
r.GET("/", h.GetAll).Name = "benefactor-getallkindbox"
r.Use(
middleware.Auth(h.authSvc, h.authConfig),
middleware.BenefactorAuthorization(entity.UserBenefactorRole),
)
r.GET("/:id", h.Get)
r.GET("", h.GetAll)
r.PATCH("/:id/emptying-requests", h.RegisterEmptyingRequest)
}

View File

@ -18,11 +18,10 @@ import (
// @Success 200 {object} param.KindBoxReqAddResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxreqs/ [post]
// @Router /benefactor/kindboxreqs/ [post].
func (h Handler) Add(c echo.Context) error {
req := param.KindBoxReqAddRequest{}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{
"message": errmsg.ErrBadRequest,
})

View File

@ -74,7 +74,7 @@ func TestAdd(t *testing.T) {
{
name: "invalid or expired jwt",
requestBody: benefactorkindboxreqparam.KindBoxReqAddRequest{
TypeID: 1,
KindBoxType: 1,
AddressID: address.Address.ID,
ReferDate: time.Now(),
CountRequested: 1,
@ -96,7 +96,7 @@ func TestAdd(t *testing.T) {
expectedStatus: http.StatusUnprocessableEntity,
expectedBody: `{
"errors":{
"type_id":"cannot be blank"
"kind_box_type":"cannot be blank"
},
"message":"invalid input"
}`,
@ -104,7 +104,7 @@ func TestAdd(t *testing.T) {
{
name: "Added successfully",
requestBody: benefactorkindboxreqparam.KindBoxReqAddRequest{
TypeID: 2,
KindBoxType: 2,
AddressID: address.Address.ID,
ReferDate: time.Now(),
CountRequested: 2,

View File

@ -1,11 +1,12 @@
package benefactorkindboxreqhandler
import (
"net/http"
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
@ -18,11 +19,10 @@ import (
// @Success 200 {object} param.KindBoxReqDeleteResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxreqs/{id} [delete]
// @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)

View File

@ -18,7 +18,7 @@ import (
// @Success 200 {object} param.KindBoxReqGetResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxreqs/{id} [get]
// @Router /benefactor/kindboxreqs/{id} [get].
func (h Handler) Get(c echo.Context) error {
var req param.KindBoxReqGetRequest
if bErr := echo.PathParamsBinder(c).Uint("id", &req.KindBoxReqID).BindError(); bErr != nil {

View File

@ -0,0 +1,62 @@
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"
queryparam "git.gocasts.ir/ebhomengo/niki/pkg/query_param"
"github.com/labstack/echo/v4"
"net/http"
)
// GetAll godoc
// @Summary Get all KindBox requests
// @Description Retrieves a list of all KindBox requests with filtering, sorting, and pagination options
// @Tags KindBoxReq
// @Accept json
// @Produce json
// @Param filter_id query int false "Filter by ID"
// @Param filter_benefactor_id query int false "Filter by benefactor ID"
// @Param filter_kind_box_type query entity.KindBoxType false "Filter by KindBox type" Format(enum)
// @Param filter_status query string false "Filter by KindBoxReq Status" Enums(pending,accepted,assigned-sender-agent,rejected,delivered)
// @Param filter_count_requested query int false "Filter by count requested"
// @Param filter_count_accepted query int false "Filter by count accepted"
// @Param filter_deliver_refer_time_id query int false "Filter by deliver refer time ID"
// @Param filter_deliver_refer_date query string false "Filter by deliver refer date" Format(date)
// @Param filter_deliver_address_id query int false "Filter by deliver address ID"
// @Param page_number query int false "Page number"
// @Param page_size query int false "Page size"
// @Param sort_field query string false "Sort by field" Enums(id,benefactor_id,kind_box_type,count_requested,count_accepted,deliver_refer_time_id,deliver_refer_date,deliver_address_id)
// @Param sort_direction query string false "Sort order" Enums(asc,desc)
// @Success 200 {object} param.GetAllResponse
// @Failure 400 {string} "Bad request"
// @Security AuthBearerBenefactor
// @Router /benefactor/kindboxreqs/ [get]
func (h Handler) GetAll(c echo.Context) error {
var req param.GetAllRequest
if bErr := c.Bind(&req); bErr != nil {
return echo.NewHTTPError(http.StatusBadRequest)
}
req.Filter = queryparam.GetFilterParams(c)
if fieldErrors, err := h.benefactorKindBoxReqVld.ValidateGetAll(req); err != nil {
msg, code := httpmsg.Error(err)
return c.JSON(code, echo.Map{
"message": msg,
"errors": fieldErrors,
})
}
req.Filter["benefactor_id"] = claim.GetClaimsFromEchoContext(c).UserID
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.StatusOK, resp)
}

View File

@ -17,4 +17,5 @@ func (h Handler) SetRoutes(e *echo.Echo) {
r.POST("/", h.Add)
r.GET("/:id", h.Get)
r.DELETE("/:id", h.Delete)
r.GET("/", h.GetAll)
}

View File

@ -2,24 +2,31 @@ package httpserver
import (
"fmt"
config "git.gocasts.ir/ebhomengo/niki/config"
adminhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/admin"
adminKindBoxHandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/admin/kind_box"
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"
benefactorkindboxhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/benefactor/kind_box"
benefactorkindboxreqhandler "git.gocasts.ir/ebhomengo/niki/delivery/http_server/benefactor/kind_box_req"
"git.gocasts.ir/ebhomengo/niki/docs"
adminservice "git.gocasts.ir/ebhomengo/niki/service/admin/admin"
adminauthorizationservice "git.gocasts.ir/ebhomengo/niki/service/admin/authorization"
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"
benefactorkindboxservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box"
benefactorkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box_req"
adminvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/admin"
adminkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box"
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"
benefactorkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box"
benefactorkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box_req"
echo "github.com/labstack/echo/v4"
middleware "github.com/labstack/echo/v4/middleware"
@ -32,8 +39,10 @@ type Server struct {
benefactorHandler benefactorhandler.Handler
benefactorKindBoxReqHandler benefactorkindboxreqhandler.Handler
benefactorAddressHandler benefactoraddresshandler.Handler
benefactorKindBoxHandler benefactorkindboxhandler.Handler
adminHandler adminhandler.Handler
adminKindBoxReqHandler adminkindboxreqhandler.Handler
adminKindBoxHandler adminKindBoxHandler.Handler
}
func New(
@ -45,12 +54,16 @@ func New(
benefactorKindBoxReqVld benefactorkindboxreqvalidator.Validator,
benefactorAddressSvc benefactoraddressservice.Service,
benefactorAddressVld benefactoraddressvalidator.Validator,
benefactorKindBoxSvc benefactorkindboxservice.Service,
benefactorKindBoxVld benefactorkindboxvalidator.Validator,
adminSvc adminservice.Service,
adminVld adminvalidator.Validator,
adminAuthSvc authservice.Service,
adminKinBoxReqSvc adminkindboxreqservice.Service,
adminKinBoxReqVld adminkindboxreqvalidator.Validator,
adminAuthorizeSvc adminauthorizationservice.Service,
adminKindBoxSvc adminkindboxservice.Service,
adminKindBoxVld adminkindboxvalidator.Validator,
) Server {
return Server{
Router: echo.New(),
@ -58,8 +71,10 @@ func New(
benefactorHandler: benefactorhandler.New(cfg.Auth, benefactorAuthSvc, benefactorSvc, benefactorVld),
benefactorKindBoxReqHandler: benefactorkindboxreqhandler.New(cfg.Auth, benefactorAuthSvc, benefactorKindBoxReqSvc, benefactorKindBoxReqVld),
benefactorAddressHandler: benefactoraddresshandler.New(cfg.Auth, benefactorAuthSvc, benefactorAddressSvc, benefactorAddressVld),
benefactorKindBoxHandler: benefactorkindboxhandler.New(cfg.Auth, benefactorAuthSvc, benefactorKindBoxSvc, benefactorKindBoxVld),
adminHandler: adminhandler.New(cfg.AdminAuth, adminAuthSvc, adminSvc, adminVld, adminAuthorizeSvc),
adminKindBoxReqHandler: adminkindboxreqhandler.New(cfg.Auth, adminAuthSvc, adminKinBoxReqSvc, adminKinBoxReqVld, adminAuthorizeSvc),
adminKindBoxHandler: adminKindBoxHandler.New(cfg.Auth, adminAuthSvc, adminKindBoxSvc, adminKindBoxVld, adminAuthorizeSvc),
}
}
@ -73,8 +88,10 @@ func (s Server) Serve() {
s.benefactorHandler.SetRoutes(s.Router)
s.benefactorKindBoxReqHandler.SetRoutes(s.Router)
s.benefactorAddressHandler.SetRoutes(s.Router)
s.benefactorKindBoxHandler.SetRoutes(s.Router)
s.adminHandler.SetRoutes(s.Router)
s.adminKindBoxReqHandler.SetRoutes(s.Router)
s.adminKindBoxHandler.SetRoutes(s.Router)
// Start server
address := fmt.Sprintf(":%d", s.config.HTTPServer.Port)
fmt.Printf("start echo server on %s\n", address)
@ -84,11 +101,11 @@ func (s Server) Serve() {
}
func RegisterSwagger(s *echo.Echo, config config.Config) {
//TODO: move this to a better place and make it more dynamic and configurable
// TODO: move this to a better place and make it more dynamic and configurable
docs.SwaggerInfo.Title = "NIKI API"
docs.SwaggerInfo.Description = "This is the API documentation for the NIKI project"
docs.SwaggerInfo.Version = "1.0.0"
//docs.SwaggerInfo.BasePath = "/api/v1"
// docs.SwaggerInfo.BasePath = "/api/v1"
docs.SwaggerInfo.Host = fmt.Sprintf("localhost:%d", config.HTTPServer.Port)
s.GET("/swagger/*any", echoSwagger.WrapHandler)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -72,6 +72,55 @@ definitions:
example: "1234567890"
type: string
type: object
adminkindboxparam.AssignReceiverRequest:
properties:
receiver_agent_id:
type: integer
type: object
adminkindboxparam.KindBoxGetAllResponse:
properties:
all_kind_box:
items:
$ref: '#/definitions/entity.KindBox'
type: array
pagination:
$ref: '#/definitions/param.PaginationResponse'
type: object
adminkindboxparam.KindBoxGetResponse:
properties:
amount:
type: integer
benefactorID:
type: integer
deliverAddressID:
type: integer
deliverReferDate:
type: string
deliveredAt:
type: string
id:
type: integer
kindBoxReqID:
type: integer
kindBoxType:
$ref: '#/definitions/entity.KindBoxType'
receiverAgentID:
type: integer
returnAddressID:
type: integer
returnReferDate:
type: string
returnReferTimeID:
type: integer
returnedAt:
type: string
senderAgentID:
type: integer
serialNumber:
type: string
status:
$ref: '#/definitions/entity.KindBoxStatus'
type: object
adminkindboxreqparam.AssignSenderRequest:
properties:
sender_agent_id:
@ -81,6 +130,15 @@ definitions:
type: object
adminkindboxreqparam.DeliverKindBoxReqResponse:
type: object
adminkindboxreqparam.DeliveryAwaitingGetAllResponse:
properties:
all_awaiting_kind_box_req:
items:
$ref: '#/definitions/entity.KindBoxReq'
type: array
pagination:
$ref: '#/definitions/param.PaginationResponse'
type: object
adminkindboxreqparam.DeliveryAwaitingGetResponse:
properties:
benefactorID:
@ -128,9 +186,33 @@ definitions:
kind_box_req_status:
$ref: '#/definitions/entity.KindBoxReqStatus'
type: object
adminkindboxreqparam.KindBoxReqAddRequest:
properties:
benefactor_id:
example: 1
type: integer
count_requested:
example: 2
type: integer
deliver_address_id:
example: 1
type: integer
deliver_refer_date:
example: "2025-01-02 15:04:05"
type: string
kind_box_type:
allOf:
- $ref: '#/definitions/entity.KindBoxType'
example: 1
type: object
adminkindboxreqparam.KindBoxReqAddResponse:
properties:
kindBoxReq:
$ref: '#/definitions/entity.KindBoxReq'
type: object
adminkindboxreqparam.KindBoxReqGetAllResponse:
properties:
all_kind_box_req:
all_awaiting_kind_box_req:
items:
$ref: '#/definitions/entity.KindBoxReq'
type: array
@ -172,6 +254,34 @@ definitions:
- $ref: '#/definitions/entity.KindBoxReqStatus'
example: 1
type: object
adminkindboxreqparam.KindBoxReqUpdateRequest:
properties:
count_accepted:
example: 3
type: integer
count_requested:
example: 5
type: integer
deliver_address_id:
example: 1
type: integer
deliver_refer_date:
example: "2025-01-02T15:04:05Z"
type: string
deliver_refer_time_id:
example: 1
type: integer
description:
example: description
type: string
kind_box_type:
allOf:
- $ref: '#/definitions/entity.KindBoxType'
example: 2
sender_agent_id:
example: 1
type: integer
type: object
adminserviceparam.AdminInfo:
properties:
description:
@ -357,12 +467,16 @@ definitions:
type: integer
kindBoxReqID:
type: integer
kindBoxType:
$ref: '#/definitions/entity.KindBoxType'
receiverAgentID:
type: integer
returnAddressID:
type: integer
returnReferDate:
type: string
returnReferTimeID:
type: integer
returnedAt:
type: string
senderAgentID:
@ -371,8 +485,27 @@ definitions:
type: string
status:
$ref: '#/definitions/entity.KindBoxStatus'
type:
$ref: '#/definitions/entity.KindBoxType'
type: object
benefactorkindboxparam.KindBoxRegisterEmptyingRequest:
properties:
return_address_id:
example: 1
type: integer
return_refer_date:
example: "2025-01-02T15:04:05Z"
type: string
return_refer_time_id:
example: 1
type: integer
type: object
benefactorkindboxreqparam.GetAllResponse:
properties:
all_kind_box_req:
items:
$ref: '#/definitions/entity.KindBoxReq'
type: array
pagination:
$ref: '#/definitions/param.PaginationResponse'
type: object
benefactorkindboxreqparam.KindBoxReqAddRequest:
properties:
@ -391,7 +524,7 @@ definitions:
deliver_refer_time_id:
example: 1
type: integer
type_id:
kind_box_type:
allOf:
- $ref: '#/definitions/entity.KindBoxType'
example: 1
@ -487,6 +620,41 @@ definitions:
x-enum-varnames:
- MaleGender
- FemaleGender
entity.KindBox:
properties:
amount:
type: integer
benefactorID:
type: integer
deliverAddressID:
type: integer
deliverReferDate:
type: string
deliveredAt:
type: string
id:
type: integer
kindBoxReqID:
type: integer
kindBoxType:
$ref: '#/definitions/entity.KindBoxType'
receiverAgentID:
type: integer
returnAddressID:
type: integer
returnReferDate:
type: string
returnReferTimeID:
type: integer
returnedAt:
type: string
senderAgentID:
type: integer
serialNumber:
type: string
status:
$ref: '#/definitions/entity.KindBoxStatus'
type: object
entity.KindBoxReq:
properties:
benefactorID:
@ -733,6 +901,200 @@ paths:
summary: Get all provinces
tags:
- Address
/admin/kindboxes:
get:
consumes:
- application/json
description: Retrieves a list of all KindBoxes with filtering, sorting, and
pagination options
parameters:
- description: Filter by ID
in: query
name: filter_id
type: integer
- description: Filter by KindBox request ID
in: query
name: filter_kind_box_req_id
type: integer
- description: Filter by benefactor ID
in: query
name: filter_benefactor_id
type: integer
- description: Filter by KindBox type
enum:
- on-table
- cylindrical
- stand-up
in: query
name: filter_kind_box_type
type: string
- description: Filter by amount
in: query
name: filter_amount
type: integer
- description: Filter by serial number
in: query
name: filter_serial_number
type: string
- description: Filter by status
enum:
- delivered
- ready-to-return
- assigned-receiver-agent
- returned
- enumerated
in: query
name: filter_status
type: string
- description: Filter by delivered at
format: date-time
in: query
name: filter_delivered_at
type: string
- description: Filter by return refer time ID
in: query
name: filter_return_refer_time_id
type: integer
- description: Filter by return refer date
format: date
in: query
name: filter_return_refer_date
type: string
- description: Filter by return address ID
in: query
name: filter_return_address_id
type: integer
- description: Filter by receiver agent ID
in: query
name: filter_receiver_agent_id
type: integer
- description: Filter by returned at
format: date-time
in: query
name: filter_returned_at
type: string
- description: Filter by sender agent ID
in: query
name: filter_sender_agent_id
type: integer
- description: Filter by deliver refer date
format: date
in: query
name: filter_deliver_refer_date
type: string
- description: Filter by deliver address ID
in: query
name: filter_deliver_address_id
type: integer
- description: Page number
in: query
name: page_number
type: integer
- description: Page size
in: query
name: page_size
type: integer
- description: Sort by field
enum:
- id
- kind_box_req_id
- benefactor_id
- kind_box_type
- amount
- serial_number
- status
- delivered_at
- return_refer_time_id
- return_refer_date
- return_address_id
- receiver_agent_id
- returned_at
- sender_agent_id
- deliver_refer_date
- deliver_address_id
in: query
name: sort_field
type: string
- description: Sort order
enum:
- asc
- desc
in: query
name: sort_direction
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/adminkindboxparam.KindBoxGetAllResponse'
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Get all KindBoxes by admin
tags:
- KindBox
/admin/kindboxes/{id}:
get:
consumes:
- application/json
description: This endpoint retrieves a specific kind box by admin
parameters:
- description: Kind box ID
in: path
name: id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/adminkindboxparam.KindBoxGetResponse'
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Get a specific kind box by admin
tags:
- KindBox
/admin/kindboxes/assign-receiver-agent/{id}:
patch:
consumes:
- application/json
parameters:
- description: KindBox ID
in: path
name: id
required: true
type: integer
- description: Assign Receiver Agent Request Body
in: body
name: Request
required: true
schema:
$ref: '#/definitions/adminkindboxparam.AssignReceiverRequest'
produces:
- application/json
responses:
"204":
description: No Content
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Admin assign receiver agent to kindbox
tags:
- KindBox
/admin/kindboxreqs:
get:
consumes:
@ -762,6 +1124,62 @@ paths:
summary: Admin get all kindboxreq
tags:
- KindBoxReq
post:
consumes:
- application/json
parameters:
- description: New kind box request details
in: body
name: Request
required: true
schema:
$ref: '#/definitions/adminkindboxreqparam.KindBoxReqAddRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/adminkindboxreqparam.KindBoxReqAddResponse'
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Add a new kind box request for a benefactor by admin
tags:
- KindBoxReq
/admin/kindboxreqs/{id}:
put:
consumes:
- application/json
parameters:
- description: KindBoxReq ID
in: path
name: id
required: true
type: integer
- description: Update KindBoxReq Request Body
in: body
name: Request
required: true
schema:
$ref: '#/definitions/adminkindboxreqparam.KindBoxReqUpdateRequest'
produces:
- application/json
responses:
"204":
description: No Content
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Update kind box request by admin
tags:
- KindBoxReq
/admin/kindboxreqs/accept-kind-box-req/{id}:
patch:
consumes:
@ -826,6 +1244,95 @@ paths:
summary: Admin Assign Sender Agent to kindboxreq
tags:
- KindBoxReq
/admin/kindboxreqs/awaiting-delivery:
get:
consumes:
- application/json
description: Retrieves a list of all awaiting KindBox requests with filtering,
sorting, and pagination options
parameters:
- description: Filter by ID
in: query
name: filter_id
type: integer
- description: Filter by benefactor ID
in: query
name: filter_benefactor_id
type: integer
- description: Filter by KindBox type
enum:
- 1
- 2
- 3
format: enum
in: query
name: filter_kind_box_type
type: integer
- description: Filter by count requested
in: query
name: filter_count_requested
type: integer
- description: Filter by count accepted
in: query
name: filter_count_accepted
type: integer
- description: Filter by deliver refer time ID
in: query
name: filter_deliver_refer_time_id
type: integer
- description: Filter by deliver refer date
format: date
in: query
name: filter_deliver_refer_date
type: string
- description: Filter by deliver address ID
in: query
name: filter_deliver_address_id
type: integer
- description: Page number
in: query
name: page_number
type: integer
- description: Page size
in: query
name: page_size
type: integer
- description: Sort by field
enum:
- id
- benefactor_id
- kind_box_type
- count_requested
- count_accepted
- deliver_refer_time_id
- deliver_refer_date
- deliver_address_id
in: query
name: sort_field
type: string
- description: Sort order
enum:
- asc
- desc
in: query
name: sort_direction
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/adminkindboxreqparam.DeliveryAwaitingGetAllResponse'
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerAdmin: []
summary: Get all awaiting delivery KindBox requests
tags:
- KindBoxReq
/admin/kindboxreqs/awaiting-delivery/{id}:
get:
consumes:
@ -982,7 +1489,7 @@ paths:
summary: Register an admin by super-admin
tags:
- Admin
/benefactor/kindboxes/:
/benefactor/kindboxes:
get:
consumes:
- application/json
@ -1030,7 +1537,137 @@ paths:
summary: Get a specific kind box for a benefactor
tags:
- KindBox
/benefactor/kindboxes/{id}/emptying-requests:
patch:
consumes:
- application/json
parameters:
- description: KindBox ID
in: path
name: id
required: true
type: integer
- description: Request body
in: body
name: Request
required: true
schema:
$ref: '#/definitions/benefactorkindboxparam.KindBoxRegisterEmptyingRequest'
produces:
- application/json
responses:
"204":
description: No content
schema:
type: string
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerBenefactor: []
summary: Register a new emptying request for a kind box by benefactor
tags:
- Benefactor
/benefactor/kindboxreqs/:
get:
consumes:
- application/json
description: Retrieves a list of all KindBox requests with filtering, sorting,
and pagination options
parameters:
- description: Filter by ID
in: query
name: filter_id
type: integer
- description: Filter by benefactor ID
in: query
name: filter_benefactor_id
type: integer
- description: Filter by KindBox type
enum:
- 1
- 2
- 3
format: enum
in: query
name: filter_kind_box_type
type: integer
- description: Filter by KindBoxReq Status
enum:
- pending
- accepted
- assigned-sender-agent
- rejected
- delivered
in: query
name: filter_status
type: string
- description: Filter by count requested
in: query
name: filter_count_requested
type: integer
- description: Filter by count accepted
in: query
name: filter_count_accepted
type: integer
- description: Filter by deliver refer time ID
in: query
name: filter_deliver_refer_time_id
type: integer
- description: Filter by deliver refer date
format: date
in: query
name: filter_deliver_refer_date
type: string
- description: Filter by deliver address ID
in: query
name: filter_deliver_address_id
type: integer
- description: Page number
in: query
name: page_number
type: integer
- description: Page size
in: query
name: page_size
type: integer
- description: Sort by field
enum:
- id
- benefactor_id
- kind_box_type
- count_requested
- count_accepted
- deliver_refer_time_id
- deliver_refer_date
- deliver_address_id
in: query
name: sort_field
type: string
- description: Sort order
enum:
- asc
- desc
in: query
name: sort_direction
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/benefactorkindboxreqparam.GetAllResponse'
"400":
description: Bad request
schema:
type: string
security:
- AuthBearerBenefactor: []
summary: Get all KindBox requests
tags:
- KindBoxReq
post:
consumes:
- application/json

View File

@ -3,12 +3,17 @@ package entity
type AdminPermission string
const (
AdminAdminRegisterPermission = AdminPermission("admin-register")
AdminKindBoxReqAcceptPermission = AdminPermission("kindboxreq-accept")
AdminKindBoxReqRejectPermission = AdminPermission("kindboxreq-reject")
AdminKindBoxReqGetAllPermission = AdminPermission("kindboxreq-getall")
AdminKindBoxReqDeliverPermission = AdminPermission("kindboxreq-deliver")
AdminKindBoxReqAssignSenderAgentPermission = AdminPermission("kindboxreq-assign_sender_agent")
AdminAdminGetAllAgentPermission = AdminPermission("admin-getall_agent")
AdminAdminRegisterPermission = AdminPermission("admin-register")
AdminKindBoxReqAcceptPermission = AdminPermission("kindboxreq-accept")
AdminKindBoxReqAddPermission = AdminPermission("kindboxreq-add")
AdminKindBoxReqRejectPermission = AdminPermission("kindboxreq-reject")
AdminKindBoxReqGetAllPermission = AdminPermission("kindboxreq-getall")
AdminKindBoxReqDeliverPermission = AdminPermission("kindboxreq-deliver")
AdminKindBoxReqAssignSenderAgentPermission = AdminPermission("kindboxreq-assign_sender_agent")
AdminAdminGetAllAgentPermission = AdminPermission("admin-getall_agent")
AdminKindBoxReqGetAwaitingDeliveryPermission = AdminPermission("kindboxreq-get_awaiting_delivery")
AdminKindBoxGetPermission = AdminPermission("kindbox-get")
AdminKindBoxAssignReceiverAgentPermission = AdminPermission("kindbox-assign_receiver_agent")
AdminKindBoxGetAllPermission = AdminPermission("kindbox-getall")
AdminKindBoxReqUpdatePermission = AdminPermission("kindboxreq-update")
)

View File

@ -3,19 +3,20 @@ package entity
import "time"
type KindBox struct {
ID uint
KindBoxReqID uint
BenefactorID uint
Type KindBoxType
Amount uint
SerialNumber string
Status KindBoxStatus
DeliverReferDate time.Time
DeliverAddressID uint
SenderAgentID uint
DeliveredAt time.Time
ReturnReferDate time.Time
ReturnAddressID uint
ReceiverAgentID uint
ReturnedAt time.Time
ID uint
KindBoxReqID uint
BenefactorID uint
KindBoxType KindBoxType
Amount uint
SerialNumber string
Status KindBoxStatus
DeliverReferDate time.Time
DeliverAddressID uint
SenderAgentID uint
DeliveredAt time.Time
ReturnReferTimeID uint
ReturnReferDate time.Time
ReturnAddressID uint
ReceiverAgentID uint
ReturnedAt time.Time
}

2
go.mod
View File

@ -16,6 +16,7 @@ require (
github.com/rubenv/sql-migrate v1.6.0
github.com/stretchr/testify v1.9.0
github.com/swaggo/echo-swagger v1.4.1
github.com/swaggo/swag v1.16.3
golang.org/x/crypto v0.23.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)
@ -46,7 +47,6 @@ require (
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/swaggo/files/v2 v2.0.0 // indirect
github.com/swaggo/swag v1.16.3 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/net v0.25.0 // indirect

View File

@ -8,14 +8,17 @@ import (
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
mysqladdress "git.gocasts.ir/ebhomengo/niki/repository/mysql/address"
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"
benefactorforadminservice "git.gocasts.ir/ebhomengo/niki/service/admin/benefactor"
adminkindboxservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box"
adminkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/admin/kind_box_req"
adminrefertimeservice "git.gocasts.ir/ebhomengo/niki/service/admin/refer_time"
benefactoraddressservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/address"
benefactorservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/benefactor"
benefactorkindboxservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box"
benefactorkindboxreqservice "git.gocasts.ir/ebhomengo/niki/service/benefactor/kind_box_req"
)
@ -23,6 +26,7 @@ type Services struct {
BenefactorSvc benefactorservice.Service
BenefactorKindBoxReqSvc benefactorkindboxreqservice.Service
BenefactorAddressSvc benefactoraddressservice.Service
BenefactorKindBoxSvc benefactorkindboxservice.Service
AdminKindBoxSvc adminkindboxservice.Service
AdminSvc adminservice.Service
AdminKindBoxReqSvc adminkindboxreqservice.Service
@ -36,6 +40,9 @@ func initSms(cfg config.Config) *kavenegarotp.Adapter {
func InitAdminService(cfg config.Config, db *mysql.DB) adminservice.Service {
return adminservice.New(InitAdminMysql(db), InitAdminAuthService(cfg))
}
func InitBenefactorForAdminService(db *mysql.DB) benefactorforadminservice.Service {
return benefactorforadminservice.New(InitAdminMysql(db))
}
func InitBenefactorService(cfg config.Config, redisAdapter redis.Adapter, db *mysql.DB) benefactorservice.Service {
return benefactorservice.New(
@ -62,8 +69,13 @@ func InitAdminKindBoxService(db *mysql.DB) adminkindboxservice.Service {
func InitAdminKindBoxReqService(db *mysql.DB) adminkindboxreqservice.Service {
return adminkindboxreqservice.New(InitBenefactorKindBoxReqDB(db), InitAdminKindBoxService(db))
}
func InitAdminReferTimeService(db *mysql.DB) adminrefertimeservice.Service {
return adminrefertimeservice.New(
InitAdminReferTimeDB(db),
)
}
func InitBenefactorKindBoxService(db *mysql.DB) benefactorkindboxservice.Service {
return benefactorkindboxservice.New(mysqlkindbox.New(db))
}

View File

@ -5,9 +5,11 @@ import (
"git.gocasts.ir/ebhomengo/niki/config"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
adminvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/admin"
adminkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/admin/kind_box"
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"
benefactorkindboxvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box"
benefactorkindboxreqvalidator "git.gocasts.ir/ebhomengo/niki/validator/benefactor/kind_box_req"
)
@ -15,12 +17,14 @@ type Validators struct {
BenefactorVld benefactorvalidator.Validator
BenefactorKindBoxReqVld benefactorkindboxreqvalidator.Validator
BenefactorAddressVld benefactoraddressvalidator.Validator
BenefactorKindBoxVld benefactorkindboxvalidator.Validator
AdminKindBoxReqVld adminkindboxreqvalidator.Validator
AdminVld adminvalidator.Validator
AdminKindBoxVld adminkindboxvalidator.Validator
}
func InitAdminKindBoxReqValidator(db *mysql.DB, cfg config.Config) adminkindboxreqvalidator.Validator {
return adminkindboxreqvalidator.New(InitBenefactorKindBoxReqDB(db), InitAdminService(cfg, db))
return adminkindboxreqvalidator.New(InitBenefactorKindBoxReqDB(db), InitAdminService(cfg, db), InitBenefactorForAdminService(db), InitAdminReferTimeService(db), InitBenefactorAddressService(db))
}
func InitAdminValidator(db *mysql.DB) adminvalidator.Validator {
@ -46,3 +50,16 @@ func InitBenefactorAddressValidator(cfg config.Config, redisAdapter redis.Adapte
InitBenefactorAddressDB(db),
)
}
func InitAdminKindBoxValidator(db *mysql.DB, cfg config.Config) adminkindboxvalidator.Validator {
return adminkindboxvalidator.New(InitKindBoxRepo(db), InitAdminService(cfg, db))
}
func InitBenefactorKindBoxValidator(cfg config.Config, redisAdapter redis.Adapter, db *mysql.DB) benefactorkindboxvalidator.Validator {
return benefactorkindboxvalidator.New(
InitKindBoxRepo(db),
InitBenefactorService(cfg, redisAdapter, db),
InitBenefactorAddressService(db),
InitAdminReferTimeService(db),
)
}

View File

@ -62,13 +62,16 @@ func initDependencies(cfg config.Config, redisAdapter redis.Adapter, db *mysql.D
BenefactorVld: initial.InitBenefactorValidator(),
BenefactorKindBoxReqVld: initial.InitBenefactorKindBoxReqValidator(cfg, redisAdapter, db),
BenefactorAddressVld: initial.InitBenefactorAddressValidator(cfg, redisAdapter, db),
BenefactorKindBoxVld: initial.InitBenefactorKindBoxValidator(cfg, redisAdapter, db),
AdminKindBoxReqVld: initial.InitAdminKindBoxReqValidator(db, cfg),
AdminVld: initial.InitAdminValidator(db),
AdminKindBoxVld: initial.InitAdminKindBoxValidator(db, cfg),
},
initial.Services{
BenefactorSvc: initial.InitBenefactorService(cfg, redisAdapter, db),
BenefactorKindBoxReqSvc: initial.InitBenefactorKindBoxReqService(db),
BenefactorAddressSvc: initial.InitBenefactorAddressService(db),
BenefactorKindBoxSvc: initial.InitBenefactorKindBoxService(db),
AdminKindBoxSvc: initial.InitAdminKindBoxService(db),
AdminKindBoxReqSvc: initial.InitAdminKindBoxReqService(db),
AdminSvc: initial.InitAdminService(cfg, db),
@ -85,8 +88,10 @@ func initAndRunServer(cfg config.Config, dependencies *Dependencies) {
dependencies.BenefactorSvc, dependencies.BenefactorVld, dependencies.BenefactorAuthSvc,
dependencies.BenefactorKindBoxReqSvc, dependencies.BenefactorKindBoxReqVld,
dependencies.BenefactorAddressSvc, dependencies.BenefactorAddressVld,
dependencies.BenefactorKindBoxSvc, dependencies.BenefactorKindBoxVld,
dependencies.AdminSvc, dependencies.AdminVld, dependencies.AdminAuthSvc,
dependencies.AdminKindBoxReqSvc, dependencies.AdminKindBoxReqVld, dependencies.AdminAuthorizationSvc)
dependencies.AdminKindBoxReqSvc, dependencies.AdminKindBoxReqVld, dependencies.AdminAuthorizationSvc,
dependencies.AdminKindBoxSvc, dependencies.AdminKindBoxVld)
server.Serve()
}

View File

@ -0,0 +1,8 @@
package adminserviceparam
type BenefactorExistByIDRequest struct {
ID uint
}
type BenefactorExistByIDResponse struct {
Existed bool
}

View File

@ -0,0 +1,10 @@
package adminserviceparam
import "git.gocasts.ir/ebhomengo/niki/entity"
type GetAddressByIDRequest struct {
ID uint
}
type GetAddressByIDResponse struct {
Address *entity.Address
}

View File

@ -1,8 +1,9 @@
package adminkindboxparam
import (
entity "git.gocasts.ir/ebhomengo/niki/entity"
"time"
entity "git.gocasts.ir/ebhomengo/niki/entity"
)
type AddKindBoxRequest struct {

View File

@ -0,0 +1,6 @@
package adminkindboxparam
type AssignReceiverRequest struct {
KindBoxID uint `json:"-" param:"id"`
ReceiverAgentID uint `json:"receiver_agent_id"`
}

View File

@ -3,8 +3,7 @@ package adminkindboxparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
type KindBoxGetRequest struct {
BenefactorID uint
KindBoxID uint
KindBoxID uint `param:"id"`
}
type KindBoxGetResponse struct {

View File

@ -1,9 +1,17 @@
package adminkindboxparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/param"
)
type KindBoxGetAllRequest struct{}
type KindBoxGetAllRequest struct {
Pagination param.PaginationRequest
Sort param.SortRequest
Filter param.FilterRequest
}
type KindBoxGetAllResponse struct {
AllKindBox []entity.KindBox
AllKindBox []entity.KindBox `json:"all_kind_box"`
Pagination param.PaginationResponse `json:"pagination"`
}

View File

@ -3,9 +3,11 @@ package adminkindboxreqparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
type KindBoxReqAddRequest struct {
BenefactorID uint
TypeID uint
CountRequested uint
BenefactorID uint `json:"benefactor_id" example:"1"`
KindBoxType entity.KindBoxType `json:"kind_box_type" example:"1"`
DeliverAddressID uint `json:"deliver_address_id" example:"1"`
DeliverReferDate string `json:"deliver_refer_date" example:"2025-01-02 15:04:05"`
CountRequested uint `json:"count_requested" example:"2"`
}
type KindBoxReqAddResponse struct {

View File

@ -1,13 +1,17 @@
package adminkindboxreqparam
import (
entity "git.gocasts.ir/ebhomengo/niki/entity"
paginationparam "git.gocasts.ir/ebhomengo/niki/param"
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/param"
)
type KindBoxReqGetAllRequest struct{}
type KindBoxReqGetAllRequest struct {
Pagination param.PaginationRequest
Sort param.SortRequest
Filter param.FilterRequest
}
type KindBoxReqGetAllResponse struct {
AllKindBoxReq []entity.KindBoxReq `json:"all_kind_box_req"`
Pagination paginationparam.PaginationResponse `json:"pagination"`
AllKindBoxReq []entity.KindBoxReq `json:"all_awaiting_kind_box_req"`
Pagination param.PaginationResponse `json:"pagination"`
}

View File

@ -0,0 +1,17 @@
package adminkindboxreqparam
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/param"
)
type DeliveryAwaitingGetAllRequest struct {
Pagination param.PaginationRequest
Sort param.SortRequest
Filter param.FilterRequest
}
type DeliveryAwaitingGetAllResponse struct {
AllAwaitingKindBoxReq []entity.KindBoxReq `json:"all_awaiting_kind_box_req"`
Pagination param.PaginationResponse `json:"pagination"`
}

View File

@ -1,14 +1,19 @@
package adminkindboxreqparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
import (
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
)
type KindBoxReqUpdateRequest struct {
BenefactorID uint
KindBoxReqID uint
TypeID uint
CountRequested uint
}
type KindBoxReqUpdateResponse struct {
KindBoxReq entity.KindBoxReq
ID uint `json:"-" param:"id" example:"1"`
KindBoxType entity.KindBoxType `json:"kind_box_type" example:"2"`
CountRequested uint `json:"count_requested" example:"5"`
CountAccepted uint `json:"count_accepted" example:"3"`
Description string `json:"description" example:"description"`
DeliverReferTimeID uint `json:"deliver_refer_time_id" example:"1"`
DeliverReferDate time.Time `json:"deliver_refer_date" example:"2025-01-02T15:04:05Z"`
DeliverAddressID uint `json:"deliver_address_id" example:"1"`
SenderAgentID uint `json:"sender_agent_id" example:"1"`
}

View File

@ -0,0 +1,19 @@
package benefactorkindboxparam
import (
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
)
type KindBoxRegisterEmptyingRequest struct {
KindBoxID uint `json:"-" param:"id"`
BenefactorID uint `json:"-"`
ReturnAddressID uint `json:"return_address_id" example:"1"`
ReturnReferTimeID uint `json:"return_refer_time_id" example:"1"`
ReturnReferDate time.Time `json:"return_refer_date" example:"2025-01-02T15:04:05Z"`
}
type KindBoxRegisterEmptyingRequestResponse struct {
entity.KindBox `json:"kind_box"`
}

View File

@ -7,7 +7,7 @@ import (
type KindBoxReqAddRequest struct {
BenefactorID uint `json:"benefactor_id" example:"1"`
TypeID entity.KindBoxType `json:"type_id" example:"1"`
KindBoxType entity.KindBoxType `json:"kind_box_type" example:"1"`
DeliverAddressID uint `json:"deliver_address_id" example:"1"`
DeliverReferDate time.Time `json:"deliver_refer_date" example:"2025-01-02T15:04:05Z"`
DeliverReferTimeID uint `json:"deliver_refer_time_id" example:"1"`

View File

@ -1,11 +1,17 @@
package benefactorkindboxreqparam
import entity "git.gocasts.ir/ebhomengo/niki/entity"
import (
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/param"
)
type KindBoxReqGetAllRequest struct {
BenefactorID uint
type GetAllRequest struct {
Pagination param.PaginationRequest
Sort param.SortRequest
Filter param.FilterRequest
}
type KindBoxReqGetAllResponse struct {
AllKindBoxReq []entity.KindBoxReq `json:"all_kind_box_req"`
type GetAllResponse struct {
AllKindBoxReq []entity.KindBoxReq `json:"all_kind_box_req"`
Pagination param.PaginationResponse `json:"pagination"`
}

View File

@ -5,7 +5,7 @@ import entity "git.gocasts.ir/ebhomengo/niki/entity"
type KindBoxReqUpdateRequest struct {
BenefactorID uint
KindBoxReqID uint
TypeID entity.KindBoxType
KindBoxType entity.KindBoxType
CountRequested uint
}

3
param/filter.go Normal file
View File

@ -0,0 +1,3 @@
package param
type FilterRequest map[string]any

View File

@ -2,12 +2,12 @@ package param
const (
defaultPageNumber = 1
dafaultPageSize = 10
defaultPageSize = 10
)
type PaginationRequest struct {
PageSize uint
PageNumber uint
PageSize uint `query:"page_size" example:"10"`
PageNumber uint `query:"page_number" example:"1"`
}
type PaginationResponse struct {
@ -32,9 +32,10 @@ func (p *PaginationRequest) GetPageSize() uint {
validPageSizes := []uint{10, 25, 50, 100}
for _, size := range validPageSizes {
if p.PageSize == size {
return size
return p.PageSize
}
}
p.PageSize = defaultPageSize
return dafaultPageSize
return p.PageSize
}

13
param/sort.go Normal file
View File

@ -0,0 +1,13 @@
package param
type SortDirection string
const (
AscSortDirection = SortDirection("asc")
DescSortDirection = SortDirection("desc")
)
type SortRequest struct {
Field string `query:"sort_field"`
Direction SortDirection `query:"sort_direction"`
}

View File

@ -21,12 +21,17 @@ const (
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 greater than count requested"
ErrorMsgCantInsertRecord = "can't insert record"
ErrorMsgCantRetrieveLastInsertID = "can't retrieve last insert id"
ErrorMsgCantUpdateRecord = "can't update record"
ErrorMsgCountAcceptedOverflow = "count accepted is greater than count requested"
ErrorMsgCantInsertRecord = "can't insert record"
ErrorMsgCantRetrieveLastInsertID = "can't retrieve last insert id"
ErrorMsgCantUpdateRecord = "can't update record"
ErrorMsgReferTimeNotFound = "refer time not found"
ErrorMsgReferTimeIsNotActive = "refer time is not active"
ErrorMsgKindBoxReqDoesntBelongToBenefactor = "kind box req doesnt belong to benefactor"
ErrorMsgCantDeleteAddress = "can't delete address"
ErrorMsgFiltersAreNotValid = "filters are not valid"
ErrorMsgSortFieldIsRequired = "sort field is required"
ErrorMsgSortDirectionShouldBeAscOrDesc = "sort direction should be asc or desc"
ErrorMsgSortFieldIsNotValid = "sort field is not valid"
ErrorMsgAssignReceiverAgentKindBoxStatus = "only ready to return kindboxes can be assigned to a receiver agent"
)

View File

@ -0,0 +1,17 @@
package mysqlquerybuilder
import "fmt"
func BuildFilterQuery(filter map[string]interface{}) (string, []any) {
var (
filterQuery string
args = []any{}
)
for key, value := range filter {
filterQuery += fmt.Sprintf("AND %s = ? ", key)
args = append(args, value)
}
return filterQuery, args
}

View File

@ -0,0 +1,31 @@
package mysqlquerybuilder
import (
"fmt"
"git.gocasts.ir/ebhomengo/niki/param"
)
func BuildGetAllQuery(baseQuery string, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest) (string, []any) {
filterQuery, fArgs := BuildFilterQuery(filter)
paginationQuery, pArgs := BuildPaginationQuery(pagination)
sortQuery := BuildSortQuery(sort)
args := []any{}
args = append(args, fArgs...)
args = append(args, pArgs...)
query := baseQuery
if filterQuery != "" {
query = fmt.Sprintf("%s %s", query, filterQuery)
}
if sortQuery != "" {
query = fmt.Sprintf("%s %s", query, sortQuery)
}
if paginationQuery != "" {
query = fmt.Sprintf("%s %s", query, paginationQuery)
}
return query, args
}

View File

@ -0,0 +1,9 @@
package mysqlquerybuilder
import (
"git.gocasts.ir/ebhomengo/niki/param"
)
func BuildPaginationQuery(pagination param.PaginationRequest) (string, []any) {
return "LIMIT ? OFFSET ?", []any{pagination.GetPageSize(), pagination.GetOffset()}
}

View File

@ -0,0 +1,14 @@
package mysqlquerybuilder
import (
"fmt"
"git.gocasts.ir/ebhomengo/niki/param"
)
func BuildSortQuery(sort param.SortRequest) string {
if sort.Field == "" && sort.Direction == "" {
return ""
}
return fmt.Sprintf("ORDER BY %s %s", sort.Field, sort.Direction)
}

18
pkg/query_param/echo.go Normal file
View File

@ -0,0 +1,18 @@
package queryparam
import (
"strings"
"github.com/labstack/echo/v4"
)
func GetFilterParams(c echo.Context) map[string]any {
queryParams := make(map[string]any)
for key, values := range c.QueryParams() {
if len(values) > 0 && strings.HasPrefix(key, "filter_") {
queryParams[strings.TrimPrefix(key, "filter_")] = values[0]
}
}
return queryParams
}

View File

@ -2,6 +2,7 @@ package mysqladmin
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"

View File

@ -75,3 +75,17 @@ func (d DB) GetAdminByID(ctx context.Context, adminID uint) (entity.Admin, error
return admin, nil
}
func (d DB) AgentExistByID(ctx context.Context, agentID uint) (bool, error) {
const op = "mysqladmin.AgentExistByID"
query := `select count(*) from admins where role = ? and id = ?`
var count int
err := d.conn.Conn().QueryRowContext(ctx, query, entity.AdminAgentRole.String(), agentID).Scan(&count)
if err != nil {
return false, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return count > 0, nil
}

View File

@ -0,0 +1,86 @@
package mysqladmin
import (
"context"
"database/sql"
"errors"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
"time"
)
func (d *DB) IsExistBenefactorByID(ctx context.Context, id uint) (bool, error) {
const op = "mysqlbenefactor.IsExistBenefactorByID"
row := d.conn.Conn().QueryRowContext(ctx, `select * from benefactors where id = ?`, id)
_, err := scanBenefactor(row)
if err != nil {
sErr := sql.ErrNoRows
//TODO-errorsas: second argument to errors.As should not be *error
//nolint
if errors.As(err, &sErr) {
return false, nil
}
// TODO - log unexpected error for better observability
return false, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return true, nil
}
func scanBenefactor(scanner mysql.Scanner) (entity.Benefactor, error) {
var createdAt, updatedAt time.Time
var benefactor entity.Benefactor
// TODO - use db model and mapper between entity and db model OR use this approach
var benefactorNullableFields benefactorNullableFields
err := scanner.Scan(&benefactor.ID, &benefactorNullableFields.firstName,
&benefactorNullableFields.lastName, &benefactor.PhoneNumber, &benefactorNullableFields.description,
&benefactorNullableFields.email, &benefactorNullableFields.genderStr,
&benefactorNullableFields.birthdate, &createdAt, &updatedAt)
mapNotNullToBenefactor(benefactorNullableFields, &benefactor)
return benefactor, err
}
type benefactorNullableFields struct {
firstName sql.NullString
lastName sql.NullString
address sql.NullString
description sql.NullString
email sql.NullString
city sql.NullString
genderStr sql.NullString
birthdate sql.NullTime
}
// TODO - find the other solution.
func mapNotNullToBenefactor(data benefactorNullableFields, benefactor *entity.Benefactor) {
if data.firstName.Valid {
benefactor.FirstName = data.firstName.String
}
if data.lastName.Valid {
benefactor.LastName = data.lastName.String
}
if data.description.Valid {
benefactor.Description = data.description.String
}
if data.email.Valid {
benefactor.Email = data.email.String
}
if data.genderStr.Valid {
benefactor.Gender = entity.MapToGender(data.genderStr.String)
}
if data.birthdate.Valid {
benefactor.BirthDate = data.birthdate.Time
}
}

View File

@ -0,0 +1,46 @@
package mysqladmin
import (
"context"
"database/sql"
"errors"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
"time"
)
func (d *DB) GetAddressByID(ctx context.Context, id uint) (*entity.Address, error) {
const op = "mysqladdress.IsExistAddressByID"
row := d.conn.Conn().QueryRowContext(ctx, `select * from addresses where id = ? and deleted_at is null`, id)
address, err := scanAddress(row)
if err != nil {
sErr := sql.ErrNoRows
//TODO-errorsas: second argument to errors.As should not be *error
//nolint
if errors.As(err, &sErr) {
return nil, nil
}
// TODO - log unexpected error for better observability
return nil, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return &address, nil
}
func scanAddress(scanner mysql.Scanner) (entity.Address, error) {
var createdAt, updatedAt time.Time
var deletedAt sql.NullTime
var address entity.Address
err := scanner.Scan(&address.ID, &address.PostalCode, &address.Address, &address.Lat, &address.Lon,
&address.Name, &address.CityID, &address.ProvinceID, &address.BenefactorID,
&createdAt, &updatedAt, &deletedAt)
return address, err
}

View File

@ -4,11 +4,12 @@ import (
"context"
"database/sql"
"errors"
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
"time"
)
func (d DB) IsExistBenefactorByPhoneNumber(ctx context.Context, phoneNumber string) (bool, entity.Benefactor, error) {
@ -56,7 +57,6 @@ func (d *DB) IsExistBenefactorByID(ctx context.Context, id uint) (bool, error) {
}
func scanBenefactor(scanner mysql.Scanner) (entity.Benefactor, error) {
var createdAt, updatedAt time.Time
var benefactor entity.Benefactor
// TODO - use db model and mapper between entity and db model OR use this approach

View File

@ -12,7 +12,7 @@ func (d DB) AddKindBox(ctx context.Context, kindBox entity.KindBox) error {
const op = "mysqlkindbox.AddKindBox"
_, err := d.conn.Conn().ExecContext(ctx, `insert into kind_boxes(kind_box_req_id,benefactor_id,type,status,sender_agent_id) values (?,?,?,?,?)`,
kindBox.KindBoxReqID, kindBox.BenefactorID, kindBox.Type, entity.KindBoxDeliveredStatus.String(), kindBox.SenderAgentID)
kindBox.KindBoxReqID, kindBox.BenefactorID, kindBox.KindBoxType, entity.KindBoxDeliveredStatus.String(), kindBox.SenderAgentID)
if err != nil {
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected)
@ -29,7 +29,7 @@ func (d DB) AddBatchKindBox(ctx context.Context, kindBoxes []entity.KindBox) err
for _, kb := range kindBoxes {
queryStr += "(?, ?, ?, ?, ?, ?, ?, ?),"
values = append(values, kb.KindBoxReqID, kb.BenefactorID, kb.Type, kb.Status.String(), kb.DeliverReferDate, kb.DeliverAddressID, kb.SenderAgentID, kb.DeliveredAt)
values = append(values, kb.KindBoxReqID, kb.BenefactorID, kb.KindBoxType, kb.Status.String(), kb.DeliverReferDate, kb.DeliverAddressID, kb.SenderAgentID, kb.DeliveredAt)
}
// trim the last ,

View File

@ -0,0 +1,23 @@
package mysqlkindbox
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) AssignReceiverAgent(ctx context.Context, kindBox entity.KindBox) error {
const op = "mysqlkindbox.AssignReceiverAgent"
query := `UPDATE kind_boxes SET receiver_agent_id = ?, status = ? WHERE status = ? AND id = ?`
_, err := d.conn.Conn().ExecContext(ctx, query,
kindBox.ReceiverAgentID, entity.KindBoxAssignedReceiverAgentStatus.String(), entity.KindBoxReadyToReturnStatus.String(), kindBox.ID)
if err != nil {
return richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return nil
}

View File

@ -0,0 +1,34 @@
package mysqlkindbox
import (
"context"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (d DB) BenefactorKindBoxExist(ctx context.Context, benefactorID, kindBoxID uint) (bool, error) {
const op = "mysqlkindbox.BenefactorKindBoxExist"
var count int
if err := d.conn.Conn().QueryRowContext(ctx, `SELECT COUNT(*) FROM kind_boxes WHERE benefactor_id = ? AND id = ?`, benefactorID, kindBoxID).Scan(&count); err != nil {
return false, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return count > 0, nil
}
func (d DB) KindBoxExist(ctx context.Context, kindBoxID uint) (bool, error) {
const op = "mysqlkindbox.KindBoxExist"
var count int
if err := d.conn.Conn().QueryRowContext(ctx, `SELECT COUNT(*) FROM kind_boxes WHERE id = ?`, kindBoxID).Scan(&count); err != nil {
return false, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return count > 0, nil
}

View File

@ -0,0 +1,29 @@
package mysqlkindbox
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) GetKindBox(ctx context.Context, kindBoxID uint) (entity.KindBox, error) {
const op = "mysqlkindbox.GetKindBox"
query := `SELECT * FROM kind_boxes WHERE id = ? AND deleted_at IS NULL`
row := d.conn.Conn().QueryRowContext(ctx, query, kindBoxID)
k, err := scanKindBox(row)
if err != nil {
if err == sql.ErrNoRows {
return entity.KindBox{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindNotFound)
}
return entity.KindBox{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
return k, nil
}

View File

@ -0,0 +1,47 @@
package mysqlkindbox
import (
"context"
"git.gocasts.ir/ebhomengo/niki/entity"
params "git.gocasts.ir/ebhomengo/niki/param"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
builder "git.gocasts.ir/ebhomengo/niki/pkg/query_builder/mysql"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (d DB) GetAllKindBox(ctx context.Context, filter params.FilterRequest, pagination params.PaginationRequest, sort params.SortRequest) ([]entity.KindBox, uint, error) {
const op = "mysqlkindbox.GetAllKindBox"
baseQuery := `SELECT * FROM kind_boxes WHERE deleted_at IS NULL`
query, args := builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
rows, qErr := d.conn.Conn().QueryContext(ctx, query, args...)
if qErr != nil {
return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
defer rows.Close()
kindBoxes := make([]entity.KindBox, 0)
for rows.Next() {
kindBox, sErr := scanKindBox(rows)
if sErr != nil {
return nil, 0, richerror.New(op).WithErr(sErr).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
kindBoxes = append(kindBoxes, kindBox)
}
if rErr := rows.Err(); rErr != nil {
return nil, 0, richerror.New(op).WithErr(rErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
var total uint
baseQuery = `SELECT COUNT(*) FROM kind_boxes WHERE deleted_at IS NULL`
query, args = builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
qErr = d.conn.Conn().QueryRowContext(ctx, query, args...).Scan(&total)
if qErr != nil {
return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return kindBoxes, total, nil
}

View File

@ -0,0 +1,27 @@
package mysqlkindbox
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) RegisterEmptyingRequestForKindBox(ctx context.Context, kindBox entity.KindBox) error {
const op = "mysqlkindbox.RegisterEmptyingRequest"
query := `UPDATE kind_boxes
SET return_address_id = ?, return_refer_time_id = ?, return_refer_date = ?, status = ?
WHERE id = ? AND benefactor_id = ? AND status = ? AND deleted_at IS NULL`
_, err := d.conn.Conn().ExecContext(ctx, query,
kindBox.ReturnAddressID, kindBox.ReturnReferTimeID, kindBox.ReturnReferDate, kindBox.Status.String(),
kindBox.ID, kindBox.BenefactorID, entity.KindBoxDeliveredStatus.String())
if err != nil {
return richerror.New(op).WithErr(err).WithMessage(errmsg.ErrorMsgSomethingWentWrong).
WithKind(richerror.KindUnexpected)
}
return nil
}

View File

@ -0,0 +1,86 @@
package mysqlkindbox
import (
"database/sql"
"time"
"git.gocasts.ir/ebhomengo/niki/entity"
"git.gocasts.ir/ebhomengo/niki/repository/mysql"
)
func scanKindBox(scanner mysql.Scanner) (entity.KindBox, error) {
var kindBox entity.KindBox
var (
kindBoxType string
amount sql.NullInt64
serialNumber sql.NullString
status string
senderAgentID sql.NullInt64
deliveredAt sql.NullTime
returnReferTimeID sql.NullInt64
returnReferDate sql.NullTime
returnAddressID sql.NullInt64
receiverAgentID sql.NullInt64
returnedAt sql.NullTime
createdAt time.Time
updatedAt time.Time
deletedAt sql.NullTime
)
err := scanner.Scan(
&kindBox.ID,
&kindBox.KindBoxReqID,
&kindBox.BenefactorID,
&kindBoxType,
&amount,
&serialNumber,
&status,
&kindBox.DeliverReferDate,
&kindBox.DeliverAddressID,
&kindBox.SenderAgentID,
&kindBox.DeliveredAt,
&returnReferTimeID,
&returnReferDate,
&returnAddressID,
&receiverAgentID,
&returnedAt,
&createdAt,
&updatedAt,
&deletedAt,
)
if err != nil {
return entity.KindBox{}, err
}
kindBox.KindBoxType = entity.MapToKindBoxType(kindBoxType)
if amount.Valid {
kindBox.Amount = uint(amount.Int64)
}
if serialNumber.Valid {
kindBox.SerialNumber = serialNumber.String
}
kindBox.Status = entity.MapToKindBoxStatus(status)
if senderAgentID.Valid {
kindBox.SenderAgentID = uint(senderAgentID.Int64)
}
if deliveredAt.Valid {
kindBox.DeliveredAt = deliveredAt.Time
}
if returnReferTimeID.Valid {
kindBox.ReturnReferTimeID = uint(returnReferTimeID.Int64)
}
if returnReferDate.Valid {
kindBox.ReturnReferDate = returnReferDate.Time
}
if returnAddressID.Valid {
kindBox.ReturnAddressID = uint(returnAddressID.Int64)
}
if receiverAgentID.Valid {
kindBox.ReceiverAgentID = uint(receiverAgentID.Int64)
}
if returnedAt.Valid {
kindBox.ReturnedAt = returnedAt.Time
}
return kindBox, nil
}

View File

@ -2,6 +2,7 @@ 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"

View File

@ -10,8 +10,8 @@ import (
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())
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,deliver_refer_time_id,status) values (?,?,?,?,?,?,?)`,
kindBoxReq.BenefactorID, kindBoxReq.KindBoxType.String(), kindBoxReq.DeliverAddressID, kindBoxReq.CountRequested, kindBoxReq.DeliverReferDate, kindBoxReq.DeliverReferTimeID, kindBoxReq.Status.String())
if err != nil {
return entity.KindBoxReq{}, richerror.New(op).WithErr(err).
WithMessage(errmsg.ErrorMsgNotFound).WithKind(richerror.KindUnexpected)

View File

@ -2,6 +2,7 @@ package mysqlkindboxreq
import (
"context"
entity "git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"

View File

@ -2,9 +2,10 @@ package mysqlkindboxreq
import (
"context"
"time"
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 {

View File

@ -3,6 +3,7 @@ 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"

View File

@ -2,68 +2,46 @@ package mysqlkindboxreq
import (
"context"
"git.gocasts.ir/ebhomengo/niki/param"
builder "git.gocasts.ir/ebhomengo/niki/pkg/query_builder/mysql"
"git.gocasts.ir/ebhomengo/niki/entity"
paginationparam "git.gocasts.ir/ebhomengo/niki/param"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (d DB) GetAllKindBoxReq(ctx context.Context, pagination paginationparam.PaginationRequest) ([]entity.KindBoxReq, paginationparam.PaginationResponse, error) {
func (d DB) GetAllKindBoxReq(ctx context.Context, filter param.FilterRequest, pagination param.PaginationRequest, sort param.SortRequest) ([]entity.KindBoxReq, uint, error) {
const op = "mysqlkindboxreq.GetAllKindBoxReq"
// TODO: create getCount function
var count uint
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)
baseQuery := `SELECT * FROM kind_box_reqs WHERE deleted_at IS NULL`
query, args := builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
rows, qErr := d.conn.Conn().QueryContext(ctx, query, args...)
if qErr != nil {
return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
defer rows.Close()
// Iterate through the rows (should only be one) and extract the count:
for rows.Next() {
err := rows.Scan(&count)
if err != nil {
panic(err)
}
}
if rErr := rows.Err(); rErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(rErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
// TODO - add sort and filter
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)
}
defer rows.Close()
// An album slice to hold data from returned rows.
var kindBoxReqs []entity.KindBoxReq
// Loop through rows, using Scan to assign column data to struct fields.
kindBoxReqs := make([]entity.KindBoxReq, 0)
for rows.Next() {
kindBoxReq, sErr := scanKindBoxReq(rows)
if sErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(sErr).
return nil, 0, richerror.New(op).WithErr(sErr).
WithMessage(errmsg.ErrorMsgCantScanQueryResult).WithKind(richerror.KindUnexpected)
}
kindBoxReqs = append(kindBoxReqs, kindBoxReq)
}
if rErr := rows.Err(); rErr != nil {
return nil, paginationparam.PaginationResponse{}, richerror.New(op).WithErr(rErr).
return nil, 0, richerror.New(op).WithErr(rErr).
WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return kindBoxReqs, paginationparam.PaginationResponse{
PageSize: pagination.GetPageSize(),
PageNumber: pagination.GetPageNumber(),
Total: count,
}, nil
var total uint
baseQuery = `SELECT COUNT(*) FROM kind_box_reqs WHERE deleted_at IS NULL`
query, args = builder.BuildGetAllQuery(baseQuery, filter, pagination, sort)
qErr = d.conn.Conn().QueryRowContext(ctx, query, args...).Scan(&total)
if qErr != nil {
return nil, 0, richerror.New(op).WithErr(qErr).WithMessage(errmsg.ErrorMsgSomethingWentWrong).WithKind(richerror.KindUnexpected)
}
return kindBoxReqs, total, nil
}

View File

@ -12,8 +12,8 @@ import (
func (d DB) GetAwaitingDeliveryByAgent(ctx context.Context, kindBoxReqID uint, agentID uint) (entity.KindBoxReq, error) {
const op = "mysqlkindboxreq.GetAwaitingDeliveryByAgent"
query := `SELECT * FROM kind_box_reqs WHERE id = ? AND sender_agent_id = ? AND status = 'assigned-sender-agent' AND deleted_at IS NULL `
row := d.conn.Conn().QueryRowContext(ctx, query, kindBoxReqID, agentID)
query := `SELECT * FROM kind_box_reqs WHERE id = ? AND sender_agent_id = ? AND status = ? AND deleted_at IS NULL `
row := d.conn.Conn().QueryRowContext(ctx, query, kindBoxReqID, agentID, entity.KindBoxReqAssignedSenderAgentStatus.String())
k, err := scanKindBoxReq(row)
if err != nil {
if err == sql.ErrNoRows {

View File

@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"git.gocasts.ir/ebhomengo/niki/entity"
errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"

View File

@ -2,6 +2,7 @@ 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"

View File

@ -30,6 +30,7 @@ func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) {
&countAccepted,
&description,
&status,
&kindBoxReq.DeliverReferTimeID,
&kindBoxReq.DeliverReferDate,
&kindBoxReq.DeliverAddressID,
&senderAgentID,
@ -39,6 +40,7 @@ func scanKindBoxReq(scanner mysql.Scanner) (entity.KindBoxReq, error) {
&deletedAt,
)
if err != nil {
return entity.KindBoxReq{}, err
}

View File

@ -0,0 +1,46 @@
package mysqlkindboxreq
import (
"context"
"database/sql"
"time"
"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) UpdateKindBoxReq(ctx context.Context, kindBoxReq entity.KindBoxReq) error {
const op = "mysqlkindboxreq.UpdateKindBoxReq"
var (
senderAgentID sql.NullInt64
deliveredAt sql.NullTime
)
if kindBoxReq.SenderAgentID != 0 {
senderAgentID = sql.NullInt64{Int64: int64(kindBoxReq.SenderAgentID), Valid: true}
} else {
senderAgentID = sql.NullInt64{Int64: 0, Valid: false}
}
if !kindBoxReq.DeliveredAt.IsZero() {
deliveredAt = sql.NullTime{Time: kindBoxReq.DeliveredAt, Valid: true}
} else {
deliveredAt = sql.NullTime{Time: time.Time{}, Valid: false}
}
query := `UPDATE kind_box_reqs
SET benefactor_id = ?, kind_box_type = ?, count_requested = ?, count_accepted = ?,
description = ?, status = ?, deliver_refer_time_id = ?, deliver_refer_date = ?,
deliver_address_id = ?, sender_agent_id = ?, delivered_at = ?
WHERE id = ? AND deleted_at IS NULL`
_, uErr := d.conn.Conn().ExecContext(ctx, query, kindBoxReq.BenefactorID, kindBoxReq.KindBoxType,
kindBoxReq.CountRequested, kindBoxReq.CountAccepted, kindBoxReq.Description, kindBoxReq.Status,
kindBoxReq.DeliverReferTimeID, kindBoxReq.DeliverReferDate, kindBoxReq.DeliverAddressID,
senderAgentID, deliveredAt, kindBoxReq.ID)
if uErr != nil {
return richerror.New(op).WithErr(uErr).WithMessage(errmsg.ErrorMsgCantUpdateRecord).
WithKind(richerror.KindUnexpected)
}
return nil
}

View File

@ -11,6 +11,7 @@ CREATE TABLE `kind_boxes` (
`deliver_address_id` INT NOT NULL,
`sender_agent_id` INT NOT NULL,
`delivered_at` DATETIME NOT NULL,
`return_refer_time_id` INT,
`return_refer_date` DATETIME,
`return_address_id` INT,
`receiver_agent_id` INT,
@ -18,10 +19,12 @@ CREATE TABLE `kind_boxes` (
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted_at` TIMESTAMP NULL,
FOREIGN KEY (`kind_box_req_id`) REFERENCES `kind_box_reqs` (`id`),
FOREIGN KEY (`benefactor_id`) REFERENCES `benefactors` (`id`),
FOREIGN KEY (`deliver_address_id`) REFERENCES `addresses` (`id`),
FOREIGN KEY (`sender_agent_id`) REFERENCES `admins` (`id`),
FOREIGN KEY (`return_refer_time_id`)REFERENCES `refer_times` (`id`),
FOREIGN KEY (`return_address_id`) REFERENCES `addresses` (`id`),
FOREIGN KEY (`receiver_agent_id`) REFERENCES `admins` (`id`),
INDEX `index_serial_number` (`serial_number`)

View File

@ -8,7 +8,12 @@ ALTER TABLE `admin_access_controls` MODIFY COLUMN `permission`
'kindboxreq-deliver',
'kindboxreq-assign_sender_agent',
'admin-getall_agent',
'kindboxreq-get_awaiting_delivery'
'kindboxreq-get_awaiting_delivery',
'kindbox-get',
'kindboxreq-add',
'kindbox-assign_receiver_agent',
'kindbox-getall',
'kindboxreq-update'
) NOT NULL;
-- +migrate Down

View File

@ -15,7 +15,17 @@ INSERT INTO `admin_access_controls` (`id`, `actor_id`, `actor_type`,`permission`
(13, 1 , 'role','admin-getall_agent'),
(14, 2 , 'role','admin-getall_agent'),
(15, 1 , 'role','kindboxreq-get_awaiting_delivery'),
(16, 3 , 'role','kindboxreq-get_awaiting_delivery');
(16, 3 , 'role','kindboxreq-get_awaiting_delivery'),
(17, 1 , 'role','kindbox-get'),
(18, 2 , 'role','kindbox-get'),
(19, 1 , 'role','kindbox-assign_receiver_agent'),
(20, 2 , 'role','kindbox-assign_receiver_agent'),
(21, 1 , 'role','kindboxreq-add'),
(22, 2 , 'role','kindboxreq-add'),
(23, 1 , 'role','kindbox-getall'),
(24, 2 , 'role','kindbox-getall'),
(25, 1 , 'role','kindboxreq-update'),
(26, 2 , 'role','kindboxreq-update');
-- +migrate Down

View File

@ -0,0 +1,18 @@
package adminservice
import (
"context"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) AgentExistByID(ctx context.Context, agentID uint) (bool, error) {
const op = "adminservice.AgentExistByID"
exists, err := s.repo.AgentExistByID(ctx, agentID)
if err != nil {
return false, richerror.New(op).WithErr(err)
}
return exists, nil
}

View File

@ -19,6 +19,7 @@ type Repository interface {
GetAdminByPhoneNumber(ctx context.Context, phoneNumber string) (entity.Admin, error)
GetAdminByID(ctx context.Context, adminID uint) (entity.Admin, error)
GetAllAgent(ctx context.Context) ([]entity.Admin, error)
AgentExistByID(ctx context.Context, agentID uint) (bool, error)
}
type Service struct {

View File

@ -0,0 +1,18 @@
package benefactor
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) AddressExistByID(ctx context.Context, req param.GetAddressByIDRequest) (param.GetAddressByIDResponse, error) {
const op = "adminaddressservice.BenefactorExistByID"
address, err := s.repo.GetAddressByID(ctx, req.ID)
if err != nil {
return param.GetAddressByIDResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.GetAddressByIDResponse{Address: address}, nil
}

View File

@ -0,0 +1,18 @@
package benefactor
import (
"context"
param "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)
func (s Service) BenefactorExistByID(ctx context.Context, req param.BenefactorExistByIDRequest) (param.BenefactorExistByIDResponse, error) {
const op = "adminservice.BenefactorExistByID"
isExisted, err := s.repo.IsExistBenefactorByID(ctx, req.ID)
if err != nil {
return param.BenefactorExistByIDResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
}
return param.BenefactorExistByIDResponse{Existed: isExisted}, nil
}

View File

@ -0,0 +1,25 @@
package benefactor
import (
"context"
"git.gocasts.ir/ebhomengo/niki/entity"
param "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
)
type Repository interface {
IsExistBenefactorByID(ctx context.Context, id uint) (bool, error)
GetAddressByID(ctx context.Context, id uint) (*entity.Address, error)
}
type BenefactorForAdminSvc interface {
BenefactorExistByID(ctx context.Context, request param.BenefactorExistByIDRequest) (param.BenefactorExistByIDResponse, error)
AddressExistByID(ctx context.Context, request param.GetAddressByIDRequest) (param.GetAddressByIDResponse, error)
}
type Service struct {
repo Repository
benefactorSvc BenefactorForAdminSvc
}
func New(repo Repository) Service {
return Service{repo: repo}
}

View File

@ -14,7 +14,7 @@ func (s Service) AddBatchKindBox(ctx context.Context, req param.AddKindBoxReques
kb := entity.KindBox{
KindBoxReqID: req.KindBoxReqID,
BenefactorID: req.BenefactorID,
Type: req.Type,
KindBoxType: req.Type,
DeliverReferDate: req.DeliverReferDate,
DeliverAddressID: req.DeliverAddressID,
DeliveredAt: req.DeliveredAt,

View File

@ -0,0 +1,23 @@
package adminkindboxservice
import (
"context"
"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) AssignReceiverAgent(ctx context.Context, req param.AssignReceiverRequest) error {
const op = "AdminKindBoxService.AssignReceiverAgent"
err := s.repo.AssignReceiverAgent(ctx, entity.KindBox{
ID: req.KindBoxID,
ReceiverAgentID: req.ReceiverAgentID,
})
if err != nil {
return richerror.New(op).WithErr(err)
}
return nil
}

View File

@ -0,0 +1,19 @@
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, request param.KindBoxGetRequest) (param.KindBoxGetResponse, error) {
const op = "adminkindboxservice.Get"
kindBox, err := s.repo.GetKindBox(ctx, request.KindBoxID)
if err != nil {
return param.KindBoxGetResponse{}, richerror.New(op).WithErr(err)
}
return param.KindBoxGetResponse{KindBox: kindBox}, nil
}

Some files were not shown because too many files have changed in this diff Show More