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
|
||||
}
|
||||
Reference in new issue
Block a user