Add backups, currencies and dashboard APIs, and scope access by guard_name.
Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
0d000f9af6
commit
28509eb4ca
65 files changed
+9132
-296
No files matched your search
@@ -0,0 +1,228 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardbalance"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) cardbalance.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
// cardBalanceColumns lists the columns returned to callers. card_last4 and
|
||||
// expiry_at are DB-generated (see migration), so they are never written but
|
||||
// are always readable; the raw card_number is intentionally excluded here so
|
||||
// full PANs never leave the API - only the masked last4 is exposed.
|
||||
var cardBalanceColumns = []string{
|
||||
"id", "passport_number", "card_last4", "expiry_month", "expiry_year", "expiry_at",
|
||||
"balance_amount", "balance_currency", "status", "checked_at",
|
||||
"created_by", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
var cardBalanceColumnsSQL = strings.Join(cardBalanceColumns, ", ")
|
||||
|
||||
var cardBalanceWritableColumns = []string{
|
||||
"passport_number", "card_number", "expiry_month", "expiry_year",
|
||||
"balance_amount", "balance_currency", "status", "checked_at", "created_by",
|
||||
}
|
||||
|
||||
var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ")
|
||||
|
||||
const cardBalanceFromClause = ` FROM card_balances cb
|
||||
LEFT JOIN users u ON u.id = cb.created_by`
|
||||
|
||||
var cardBalanceSelectColumns = shared.PrefixedColumns("cb", cardBalanceColumns) + `,
|
||||
COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL
|
||||
|
||||
func resolveStatus(status *string) string {
|
||||
if status == nil || strings.TrimSpace(*status) == "" {
|
||||
return "pending"
|
||||
}
|
||||
return *status
|
||||
}
|
||||
|
||||
func resolveCurrency(currency *string) string {
|
||||
if currency == nil || strings.TrimSpace(*currency) == "" {
|
||||
return "TMT"
|
||||
}
|
||||
return *currency
|
||||
}
|
||||
|
||||
func createArgs(dto cardbalance.CreateCardBalanceDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
|
||||
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
|
||||
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy),
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cardbalance.UpdateCardBalanceDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
|
||||
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
|
||||
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardbalance.ListFilter) (cardbalance.ListCardBalanceDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_balances cb`+whereClause, args...).Scan(&count); err != nil {
|
||||
return cardbalance.ListCardBalanceDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY cb.id DESC LIMIT $%d OFFSET $%d`,
|
||||
cardBalanceSelectColumns, cardBalanceFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return cardbalance.ListCardBalanceDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []cardbalance.CardBalanceDTO
|
||||
for rows.Next() {
|
||||
item, err := scanCardBalanceWithJoins(rows)
|
||||
if err != nil {
|
||||
return cardbalance.ListCardBalanceDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return cardbalance.ListCardBalanceDTO{}, err
|
||||
}
|
||||
|
||||
return cardbalance.ListCardBalanceDTO{Count: count, CardBalances: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardbalance.ListFilter) (whereClause string, args []interface{}) {
|
||||
conditions := []string{"cb.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("cb.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.PassportNumber != "" {
|
||||
args = append(args, filter.PassportNumber)
|
||||
conditions = append(conditions, fmt.Sprintf("cb.passport_number = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CreatedBy != nil {
|
||||
args = append(args, *filter.CreatedBy)
|
||||
conditions = append(conditions, fmt.Sprintf("cb.created_by = $%d", len(args)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardbalance.CardBalanceDTO, error) {
|
||||
query := `SELECT ` + cardBalanceSelectColumns + cardBalanceFromClause + ` WHERE cb.id = $1 AND cb.deleted_at IS NULL`
|
||||
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardbalance.CreateCardBalanceDTO) (cardbalance.CardBalanceDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO card_balances (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted cb
|
||||
LEFT JOIN users u ON u.id = cb.created_by`,
|
||||
cardBalanceWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
cardBalanceColumnsSQL, cardBalanceSelectColumns,
|
||||
)
|
||||
|
||||
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardbalance.UpdateCardBalanceDTO) (cardbalance.CardBalanceDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(cardBalanceWritableColumns))
|
||||
for i, column := range cardBalanceWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_balances SET %s, updated_at = now()
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated cb
|
||||
LEFT JOIN users u ON u.id = cb.created_by`,
|
||||
strings.Join(assignments, ", "), len(args), cardBalanceColumnsSQL, cardBalanceSelectColumns,
|
||||
)
|
||||
|
||||
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `UPDATE card_balances SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanCardBalanceWithJoins(row genericrepo.Scanner) (cardbalance.CardBalanceDTO, error) {
|
||||
var item cardbalance.CardBalanceDTO
|
||||
var userUsername, userPhone, userEmail, userName string
|
||||
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.PassportNumber, &item.CardLast4, &item.ExpiryMonth, &item.ExpiryYear, &item.ExpiryAt,
|
||||
&item.BalanceAmount, &item.BalanceCurrency, &item.Status, &item.CheckedAt,
|
||||
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
|
||||
&userUsername, &userPhone, &userEmail, &userName,
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cardbalance.CardBalanceDTO{}, err
|
||||
}
|
||||
|
||||
if item.CreatedById != nil {
|
||||
item.CreatedBy = &shared.UserInfo{
|
||||
Id: *item.CreatedById,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package cardbalance
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
)
|
||||
|
||||
type CardBalanceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
PassportNumber string `json:"passportNumber"`
|
||||
CardLast4 string `json:"cardLast4"`
|
||||
ExpiryMonth int16 `json:"expiryMonth"`
|
||||
ExpiryYear int16 `json:"expiryYear"`
|
||||
ExpiryAt time.Time `json:"expiryAt"`
|
||||
BalanceAmount *float64 `json:"balanceAmount"`
|
||||
BalanceCurrency string `json:"balanceCurrency"`
|
||||
Status string `json:"status"`
|
||||
CheckedAt *time.Time `json:"checkedAt"`
|
||||
CreatedById *int64 `json:"-"`
|
||||
CreatedBy *shared.UserInfo `json:"createdBy,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardBalanceDTO struct {
|
||||
PassportNumber string `json:"passportNumber" binding:"required"`
|
||||
CardNumber string `json:"cardNumber" binding:"required"`
|
||||
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
|
||||
ExpiryYear int16 `json:"expiryYear" binding:"required"`
|
||||
BalanceAmount *float64 `json:"balanceAmount"`
|
||||
BalanceCurrency *string `json:"balanceCurrency"`
|
||||
Status *string `json:"status"`
|
||||
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
|
||||
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
|
||||
}
|
||||
|
||||
type UpdateCardBalanceDTO struct {
|
||||
PassportNumber string `json:"passportNumber" binding:"required"`
|
||||
CardNumber string `json:"cardNumber" binding:"required"`
|
||||
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
|
||||
ExpiryYear int16 `json:"expiryYear" binding:"required"`
|
||||
BalanceAmount *float64 `json:"balanceAmount"`
|
||||
BalanceCurrency *string `json:"balanceCurrency"`
|
||||
Status *string `json:"status"`
|
||||
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
|
||||
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
PassportNumber string
|
||||
CreatedBy *int64
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardBalanceDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardBalances []CardBalanceDTO `json:"cardBalances"`
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package cardbalance
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/card-balances"
|
||||
|
||||
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 := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List card balances
|
||||
// @Description Returns paginated card balance checks with optional filters
|
||||
// @Tags card-balances
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param passport_number query string false "Filter by passport number"
|
||||
// @Param created_by query int false "Filter by creator user ID"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-balances [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 card balances failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get card balance by ID
|
||||
// @Description Returns a single card balance check
|
||||
// @Tags card-balances
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card balance ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-balances/{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 card balance failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create card balance
|
||||
// @Description Creates a new card balance check record
|
||||
// @Tags card-balances
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateCardBalanceDTO true "Card balance payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-balances [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardBalanceDTO
|
||||
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 card balance failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update card balance
|
||||
// @Description Updates an existing card balance check record
|
||||
// @Tags card-balances
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card balance ID"
|
||||
// @Param body body UpdateCardBalanceDTO true "Card balance payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-balances/{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
|
||||
}
|
||||
|
||||
var dto UpdateCardBalanceDTO
|
||||
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 card balance failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete card balance
|
||||
// @Description Soft-deletes a card balance check record
|
||||
// @Tags card-balances
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card balance ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-balances/{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 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 card balance failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card balance removed"))
|
||||
}
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
page, limit, ok := shared.ParsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit}
|
||||
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "passport_number", "passportNumber"); raw != "" {
|
||||
filter.PassportNumber = raw
|
||||
}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "created_by", "createdBy"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CreatedBy = id
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cardbalance
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCardBalanceDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CardBalanceDTO, error)
|
||||
Create(ctx context.Context, dto CreateCardBalanceDTO) (CardBalanceDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCardBalanceDTO) (CardBalanceDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -272,5 +272,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -263,5 +263,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardrekwizit"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[cardrekwizit.CardRekwizitOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) cardrekwizit.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "card_rekwizit_orders", cardRekwizitOrderColumnsSQL, scanCardRekwizitOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var cardRekwizitOrderWritableColumns = []string{
|
||||
"unique_id", "user_id", "card_type_id", "card_number", "card_month", "card_year",
|
||||
"region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
|
||||
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
|
||||
"status", "notes",
|
||||
}
|
||||
|
||||
var cardRekwizitOrderColumns = append(append([]string{"id"}, cardRekwizitOrderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var cardRekwizitOrderColumnsSQL = strings.Join(cardRekwizitOrderColumns, ", ")
|
||||
|
||||
var cardRekwizitOrderWritableColumnsSQL = strings.Join(cardRekwizitOrderWritableColumns, ", ")
|
||||
|
||||
const cardRekwizitOrderFromClause = ` FROM card_rekwizit_orders cro
|
||||
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cro.branch_id
|
||||
LEFT JOIN users u ON u.id = cro.user_id`
|
||||
|
||||
var cardRekwizitOrderSelectColumns = shared.PrefixedColumns("cro", cardRekwizitOrderColumns) + `,
|
||||
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func resolveStatus(status *string) *string {
|
||||
if status == nil || strings.TrimSpace(*status) == "" {
|
||||
pending := "pending"
|
||||
return &pending
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func createArgs(dto cardrekwizit.CreateCardRekwizitOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
|
||||
dto.CardNumber, dto.CardMonth, dto.CardYear,
|
||||
dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cardrekwizit.UpdateCardRekwizitOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
|
||||
dto.CardNumber, dto.CardMonth, dto.CardYear,
|
||||
dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardrekwizit.ListFilter) (cardrekwizit.ListCardRekwizitOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_rekwizit_orders cro`+whereClause, args...).Scan(&count); err != nil {
|
||||
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY cro.id LIMIT $%d OFFSET $%d`,
|
||||
cardRekwizitOrderSelectColumns, cardRekwizitOrderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []cardrekwizit.CardRekwizitOrderDTO
|
||||
for rows.Next() {
|
||||
item, err := scanCardRekwizitOrderWithJoins(rows)
|
||||
if err != nil {
|
||||
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
|
||||
}
|
||||
|
||||
return cardrekwizit.ListCardRekwizitOrderDTO{Count: count, CardRekwizitOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardrekwizit.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("cro.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(filter.BranchIds) > 0 {
|
||||
conditions, args = rbac.AppendBranchIDs(conditions, args, "cro.branch_id", filter.BranchIds)
|
||||
} else if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("cro.branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("cro.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardTypeId != nil {
|
||||
args = append(args, *filter.CardTypeId)
|
||||
conditions = append(conditions, fmt.Sprintf("cro.card_type_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("cro.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
query := `SELECT ` + cardRekwizitOrderSelectColumns + cardRekwizitOrderFromClause + ` WHERE cro.id = $1`
|
||||
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardrekwizit.CreateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO card_rekwizit_orders (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted cro
|
||||
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cro.branch_id
|
||||
LEFT JOIN users u ON u.id = cro.user_id`,
|
||||
cardRekwizitOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
|
||||
)
|
||||
|
||||
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardrekwizit.UpdateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(cardRekwizitOrderWritableColumns))
|
||||
for i, column := range cardRekwizitOrderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_rekwizit_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated cro
|
||||
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cro.branch_id
|
||||
LEFT JOIN users u ON u.id = cro.user_id`,
|
||||
strings.Join(assignments, ", "), len(args), cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
|
||||
)
|
||||
|
||||
item, err := scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanCardRekwizitOrder(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
return scanCardRekwizitOrderRow(row, false)
|
||||
}
|
||||
|
||||
func scanCardRekwizitOrderWithJoins(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
return scanCardRekwizitOrderRow(row, true)
|
||||
}
|
||||
|
||||
func scanCardRekwizitOrderRow(row genericrepo.Scanner, withJoins bool) (cardrekwizit.CardRekwizitOrderDTO, error) {
|
||||
var item cardrekwizit.CardRekwizitOrderDTO
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId,
|
||||
&item.CardNumber, &item.CardMonth, &item.CardYear,
|
||||
&item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
|
||||
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
|
||||
&item.Status, &item.Notes,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
}
|
||||
|
||||
var cardTypeNameJSON, branchNameJSON []byte
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withJoins {
|
||||
dest = append(dest, &cardTypeNameJSON, &branchNameJSON, &userName, &userUsername, &userPhone, &userEmail)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderDTO{}, err
|
||||
}
|
||||
if !withJoins {
|
||||
return item, nil
|
||||
}
|
||||
|
||||
var cardTypeName, branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderDTO{}, err
|
||||
}
|
||||
if item.CardTypeId != 0 {
|
||||
item.CardType = &shared.NamedInfo{Id: item.CardTypeId, Name: cardTypeName}
|
||||
}
|
||||
if item.BranchId != 0 {
|
||||
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
|
||||
}
|
||||
if item.UserId != nil {
|
||||
item.User = &shared.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package cardrekwizit
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/shared"
|
||||
)
|
||||
|
||||
type CardRekwizitOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"-"`
|
||||
User *shared.UserInfo `json:"user,omitempty"`
|
||||
CardTypeId int64 `json:"-"`
|
||||
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||
CardNumber string `json:"cardNumber"`
|
||||
CardMonth string `json:"cardMonth"`
|
||||
CardYear string `json:"cardYear"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"-"`
|
||||
Branch *shared.NamedInfo `json:"branch,omitempty"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardRekwizitOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
CardNumber string `json:"cardNumber" binding:"required"`
|
||||
CardMonth string `json:"cardMonth" binding:"required"`
|
||||
CardYear string `json:"cardYear" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type UpdateCardRekwizitOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
CardNumber string `json:"cardNumber" binding:"required"`
|
||||
CardMonth string `json:"cardMonth" binding:"required"`
|
||||
CardYear string `json:"cardYear" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
BranchIds []int64
|
||||
UserId *int64
|
||||
CardTypeId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardRekwizitOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardRekwizitOrders []CardRekwizitOrderDTO `json:"cardRekwizitOrders"`
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package cardrekwizit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/cards/shared"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/card-rekwizit-orders"
|
||||
|
||||
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 := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List card rekwizit orders
|
||||
// @Description Returns paginated card rekwizit (card details) orders with optional filters
|
||||
// @Tags card-rekwizit-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param card_type_id query int false "Filter by card type 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)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-rekwizit-orders [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 card rekwizit orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get card rekwizit order by ID
|
||||
// @Description Returns a single card rekwizit order
|
||||
// @Tags card-rekwizit-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card rekwizit order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-rekwizit-orders/{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 card rekwizit order 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 card rekwizit order
|
||||
// @Description Creates a new card rekwizit (card details) order
|
||||
// @Tags card-rekwizit-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateCardRekwizitOrderDTO true "Card rekwizit order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-rekwizit-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardRekwizitOrderDTO
|
||||
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 card rekwizit order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update card rekwizit order
|
||||
// @Description Updates an existing card rekwizit order
|
||||
// @Tags card-rekwizit-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card rekwizit order ID"
|
||||
// @Param body body UpdateCardRekwizitOrderDTO true "Card rekwizit order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-rekwizit-orders/{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 UpdateCardRekwizitOrderDTO
|
||||
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 card rekwizit order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete card rekwizit order
|
||||
// @Description Deletes a card rekwizit order
|
||||
// @Tags card-rekwizit-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Card rekwizit order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-rekwizit-orders/{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 card rekwizit order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card rekwizit order removed"))
|
||||
}
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
page, limit, ok := shared.ParsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.BranchId = id
|
||||
}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CardTypeId = id
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "region"); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cardrekwizit
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListCardRekwizitOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (CardRekwizitOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cards"
|
||||
@@ -40,10 +41,11 @@ var cardColumnsSQL = strings.Join(cardColumns, ", ")
|
||||
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
|
||||
|
||||
const cardFromClause = ` FROM cards c
|
||||
LEFT JOIN card_types ct ON ct.id::text = c.type
|
||||
LEFT JOIN users u ON u.id = c.user_id`
|
||||
|
||||
var cardSelectColumns = shared.PrefixedColumns("c", cardColumns) + `, ` +
|
||||
shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
var cardSelectColumns = shared.PrefixedColumns("c", cardColumns) + `,
|
||||
ct.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func createArgs(dto cards.CreateCardDTO) []interface{} {
|
||||
return []interface{}{
|
||||
@@ -139,6 +141,7 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted c
|
||||
LEFT JOIN card_types ct ON ct.id::text = c.type
|
||||
LEFT JOIN users u ON u.id = c.user_id`,
|
||||
cardWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
cardColumnsSQL, cardSelectColumns,
|
||||
@@ -164,6 +167,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated c
|
||||
LEFT JOIN card_types ct ON ct.id::text = c.type
|
||||
LEFT JOIN users u ON u.id = c.user_id`,
|
||||
strings.Join(assignments, ", "), len(args), cardColumnsSQL, cardSelectColumns,
|
||||
)
|
||||
@@ -194,22 +198,43 @@ func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error)
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
}
|
||||
|
||||
var cardTypeNameJSON []byte
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withUser {
|
||||
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
|
||||
dest = append(dest, &cardTypeNameJSON, &userName, &userUsername, &userPhone, &userEmail)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
if withUser && item.UserId != nil {
|
||||
item.User = &shared.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
if withUser {
|
||||
var cardTypeName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
if id := parseCardTypeID(item.Type); id != 0 {
|
||||
item.CardType = &shared.NamedInfo{Id: id, Name: cardTypeName}
|
||||
}
|
||||
if item.UserId != nil {
|
||||
item.User = &shared.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func parseCardTypeID(raw *string) int64 {
|
||||
if raw == nil {
|
||||
return 0
|
||||
}
|
||||
id, err := strconv.ParseInt(strings.TrimSpace(*raw), 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return id
|
||||
}
|
||||
+11
-10
@@ -7,16 +7,17 @@ import (
|
||||
)
|
||||
|
||||
type CardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"-"`
|
||||
User *shared.UserInfo `json:"user,omitempty"`
|
||||
Number string `json:"number"`
|
||||
Name string `json:"name"`
|
||||
Month string `json:"month"`
|
||||
Year *string `json:"year"`
|
||||
Type *string `json:"type"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"-"`
|
||||
User *shared.UserInfo `json:"user,omitempty"`
|
||||
Number string `json:"number"`
|
||||
Name string `json:"name"`
|
||||
Month string `json:"month"`
|
||||
Year *string `json:"year"`
|
||||
Type *string `json:"-"`
|
||||
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardDTO struct {
|
||||
|
||||
@@ -94,6 +94,9 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardOwned(c, item.UserId) {
|
||||
return
|
||||
}
|
||||
if item.UserId != nil && !rbac.GuardUser(c, *item.UserId) {
|
||||
return
|
||||
}
|
||||
@@ -236,7 +239,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardCardByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
// Package cards groups payment cards, card orders, PIN orders, visa/master
|
||||
// payment orders, and their reference data (reasons, payment card types)
|
||||
// under one bounded context, replacing the flat internal/admin/* listing.
|
||||
// Package cards groups payment cards, card orders, PIN orders, rekwizit
|
||||
// (card details) orders, visa/master payment orders, and their reference
|
||||
// data (reasons, payment card types) under one bounded context, replacing
|
||||
// the flat internal/admin/* listing.
|
||||
package cards
|
||||
|
||||
import (
|
||||
"online-back/internal/cards/cardbalance"
|
||||
cardbalancedb "online-back/internal/cards/cardbalance/db"
|
||||
"online-back/internal/cards/cardorder"
|
||||
cardorderdb "online-back/internal/cards/cardorder/db"
|
||||
"online-back/internal/cards/cardpinorders"
|
||||
cardpinordersdb "online-back/internal/cards/cardpinorders/db"
|
||||
"online-back/internal/cards/cardrekwizit"
|
||||
cardrekwizitdb "online-back/internal/cards/cardrekwizit/db"
|
||||
cardentity "online-back/internal/cards/cards"
|
||||
cardentitydb "online-back/internal/cards/cards/db"
|
||||
"online-back/internal/cards/paymentcard"
|
||||
@@ -32,9 +37,11 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
cardbalance.NewHandler(logger, cardbalancedb.NewRepository(client, logger)),
|
||||
cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)),
|
||||
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
|
||||
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
|
||||
cardrekwizit.NewHandler(logger, cardrekwizitdb.NewRepository(client, logger)),
|
||||
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
|
||||
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
|
||||
visamaster.NewHandler(logger, visamasterdb.NewRepository(client, logger)),
|
||||
|
||||
@@ -97,7 +97,7 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardBranch(c, item.BranchId) {
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -249,7 +249,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
}
|
||||
|
||||
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
if !rbac.HasBranchScope(c) {
|
||||
if rbac.SkipRecordGuard(c) {
|
||||
return true
|
||||
}
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
@@ -261,5 +261,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardBranch(c, item.BranchId)
|
||||
return rbac.GuardOrder(c, item.UserId, item.BranchId)
|
||||
}
|
||||
Reference in new issue
Block a user