Files
online-backend/internal/lending/loanpaidletter/handler.go
GuwandykA f1337706f0
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled
swagger: document the ?lang= query parameter on every admin endpoint
appresult.Localize applies to all /api/admin routes, so each handler's
godoc now declares lang (tm, ru, en, all; default tm) and Swagger UI
offers it as a dropdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:08:32 +05:00

342 lines
11 KiB
Go

package loanpaidletter
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/loan-paid-off-letters"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Require(perm.Loans))
group.GET("", h.list)
group.GET("/branches", h.listBranchesByProvince)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List loan paid off letters
// @Description Returns paginated loan paid off letters with optional filters
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param passport_id query string false "Filter by passport ID"
// @Param name query string false "Filter by customer name"
// @Param status query string false "Filter by status"
// @Param branch_id query int false "Filter by branch ID"
// @Param region query string false "Filter by region"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list loan paid off letters failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// listBranchesByProvince godoc
// @Summary List branches by province
// @Description Returns branches for the selected province (etrap) id for loan paid-off letter forms
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param province_id query int true "Province ID"
// @Param active query bool false "Only active branches" default(true)
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/branches [get]
func (h *handler) listBranchesByProvince(c *gin.Context) {
provinceID, ok := shared.ParseID(c.Query("province_id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
activeOnly := true
if raw := c.Query("active"); raw != "" {
active, err := strconv.ParseBool(raw)
if err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
activeOnly = active
}
result, err := h.repository.ListBranchesByProvince(c.Request.Context(), provinceID, activeOnly)
if err != nil {
h.logger.Errorf("list branches by province failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get loan paid off letter by ID
// @Description Returns a single loan paid off letter
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create loan paid off letter
// @Description Creates a new loan paid off letter
// @Tags loan-paid-off-letters
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateLoanPaidLetterDTO true "Loan paid off letter payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters [post]
func (h *handler) create(c *gin.Context) {
var dto CreateLoanPaidLetterDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update loan paid off letter
// @Description Updates an existing loan paid off letter
// @Tags loan-paid-off-letters
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Param body body UpdateLoanPaidLetterDTO true "Loan paid off letter payload"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateLoanPaidLetterDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete loan paid off letter
// @Description Deletes a loan paid off letter
// @Tags loan-paid-off-letters
// @Produce json
// @Security BearerAuth
// @Param id path int true "Loan paid off letter ID"
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /loan-paid-off-letters/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete loan paid off letter failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: shared.DefaultPage,
Limit: shared.DefaultLimit,
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > shared.MaxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("passport_id")); raw != "" {
filter.PassportId = raw
}
if raw := strings.TrimSpace(c.Query("name")); raw != "" {
filter.Name = raw
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
filter.Region = raw
}
if raw := c.Query("branch_id"); raw != "" {
id, ok := shared.ParseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
}
raw := strings.TrimSpace(c.Query("user_id"))
if raw == "" {
raw = strings.TrimSpace(c.Query("userId"))
}
if raw != "" {
id, ok := shared.ParseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}