269 lines
9.4 KiB
Go
269 lines
9.4 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"online-back/internal/cards/cardpinorders"
|
|
"online-back/internal/identity/rbac"
|
|
"online-back/internal/shared"
|
|
"online-back/pkg/client/postgresql"
|
|
"online-back/pkg/logging"
|
|
"online-back/pkg/repository/genericrepo"
|
|
)
|
|
|
|
type repository struct {
|
|
client postgresql.Client
|
|
generic *genericrepo.Repository[cardpinorders.CardPinOrderDTO]
|
|
logger *logging.Logger
|
|
}
|
|
|
|
func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository {
|
|
return &repository{
|
|
client: client,
|
|
generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder),
|
|
logger: logger,
|
|
}
|
|
}
|
|
|
|
var cardPinOrderWritableColumns = []string{
|
|
"unique_id", "user_id", "card_type_id", "card_number", "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 cardPinOrderColumns = append(append([]string{"id"}, cardPinOrderWritableColumns...), "created_at", "updated_at")
|
|
|
|
var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
|
|
|
|
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
|
|
|
|
const cardPinOrderFromClause = ` FROM card_pin_orders cpo
|
|
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
|
LEFT JOIN branches b ON b.id = cpo.branch_id
|
|
LEFT JOIN users u ON u.id = cpo.user_id`
|
|
|
|
var cardPinOrderSelectColumns = shared.PrefixedColumns("cpo", cardPinOrderColumns) + `,
|
|
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
|
|
|
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
|
|
return []interface{}{
|
|
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
|
|
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
|
|
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
|
dto.Status, dto.Notes,
|
|
}
|
|
}
|
|
|
|
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
|
|
return []interface{}{
|
|
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
|
|
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
|
|
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
|
dto.Status, dto.Notes,
|
|
}
|
|
}
|
|
|
|
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
|
|
whereClause, args := buildListQuery(filter)
|
|
|
|
var count int64
|
|
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_pin_orders cpo`+whereClause, args...).Scan(&count); err != nil {
|
|
return cardpinorders.ListCardPinOrderDTO{}, err
|
|
}
|
|
|
|
offset := (filter.Page - 1) * filter.Limit
|
|
limitPlaceholder := len(args) + 1
|
|
offsetPlaceholder := len(args) + 2
|
|
query := fmt.Sprintf(
|
|
`SELECT cpo.id, cpo.unique_id, cpo.card_number, cpo.customer_name, cpo.customer_surname,
|
|
cpo.region, bp.name, cpo.phone, cpo.status, cpo.created_at
|
|
FROM card_pin_orders cpo
|
|
LEFT JOIN branches b ON b.id = cpo.branch_id
|
|
LEFT JOIN provinces bp ON bp.id = b.province_id%s ORDER BY cpo.id LIMIT $%d OFFSET $%d`,
|
|
whereClause, limitPlaceholder, offsetPlaceholder,
|
|
)
|
|
|
|
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
|
if err != nil {
|
|
return cardpinorders.ListCardPinOrderDTO{}, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
items := []cardpinorders.CardPinOrderListItemDTO{}
|
|
for rows.Next() {
|
|
var item cardpinorders.CardPinOrderListItemDTO
|
|
var provinceNameJSON []byte
|
|
if err := rows.Scan(
|
|
&item.Id, &item.UniqueId, &item.CardNumber, &item.CustomerName, &item.CustomerSurname,
|
|
&item.Region, &provinceNameJSON, &item.Phone, &item.Status, &item.CreatedAt,
|
|
); err != nil {
|
|
return cardpinorders.ListCardPinOrderDTO{}, err
|
|
}
|
|
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
|
return cardpinorders.ListCardPinOrderDTO{}, err
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return cardpinorders.ListCardPinOrderDTO{}, err
|
|
}
|
|
|
|
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
|
|
}
|
|
|
|
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
|
|
conditions := []string{"cpo.deleted_at IS NULL"}
|
|
|
|
if filter.Status != nil {
|
|
args = append(args, *filter.Status)
|
|
conditions = append(conditions, fmt.Sprintf("cpo.status = $%d", len(args)))
|
|
}
|
|
|
|
if len(filter.BranchIds) > 0 {
|
|
conditions, args = rbac.AppendBranchIDs(conditions, args, "cpo.branch_id", filter.BranchIds)
|
|
} else if filter.BranchId != nil {
|
|
args = append(args, *filter.BranchId)
|
|
conditions = append(conditions, fmt.Sprintf("cpo.branch_id = $%d", len(args)))
|
|
}
|
|
|
|
if filter.UserId != nil {
|
|
args = append(args, *filter.UserId)
|
|
conditions = append(conditions, fmt.Sprintf("cpo.user_id = $%d", len(args)))
|
|
}
|
|
|
|
if filter.CardTypeId != nil {
|
|
args = append(args, *filter.CardTypeId)
|
|
conditions = append(conditions, fmt.Sprintf("cpo.card_type_id = $%d", len(args)))
|
|
}
|
|
|
|
if filter.Region != "" {
|
|
args = append(args, filter.Region)
|
|
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
|
|
}
|
|
|
|
return " WHERE " + strings.Join(conditions, " AND "), args
|
|
}
|
|
|
|
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
|
|
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1 AND cpo.deleted_at IS NULL`
|
|
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
|
}
|
|
|
|
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, 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_pin_orders (%s) VALUES (%s)
|
|
RETURNING %s
|
|
)
|
|
SELECT %s
|
|
FROM inserted cpo
|
|
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
|
LEFT JOIN branches b ON b.id = cpo.branch_id
|
|
LEFT JOIN users u ON u.id = cpo.user_id`,
|
|
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
|
cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
|
|
)
|
|
|
|
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
|
}
|
|
|
|
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
|
args := updateArgs(dto)
|
|
|
|
assignments := make([]string, len(cardPinOrderWritableColumns))
|
|
for i, column := range cardPinOrderWritableColumns {
|
|
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
|
}
|
|
args = append(args, id)
|
|
|
|
query := fmt.Sprintf(`
|
|
WITH updated AS (
|
|
UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
WHERE id = $%d AND deleted_at IS NULL
|
|
RETURNING %s
|
|
)
|
|
SELECT %s
|
|
FROM updated cpo
|
|
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
|
LEFT JOIN branches b ON b.id = cpo.branch_id
|
|
LEFT JOIN users u ON u.id = cpo.user_id`,
|
|
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
|
|
)
|
|
|
|
item, err := scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
|
if err != nil {
|
|
return cardpinorders.CardPinOrderDTO{}, err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
return r.generic.Delete(ctx, id)
|
|
}
|
|
|
|
func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
|
|
return scanCardPinOrderRow(row, false)
|
|
}
|
|
|
|
func scanCardPinOrderWithJoins(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
|
|
return scanCardPinOrderRow(row, true)
|
|
}
|
|
|
|
func scanCardPinOrderRow(row genericrepo.Scanner, withJoins bool) (cardpinorders.CardPinOrderDTO, error) {
|
|
var item cardpinorders.CardPinOrderDTO
|
|
dest := []interface{}{
|
|
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &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 cardpinorders.CardPinOrderDTO{}, err
|
|
}
|
|
if !withJoins {
|
|
return item, nil
|
|
}
|
|
|
|
var cardTypeName, branchName shared.LocalizedText
|
|
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
|
return cardpinorders.CardPinOrderDTO{}, err
|
|
}
|
|
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
|
return cardpinorders.CardPinOrderDTO{}, 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
|
|
}
|