317 lines
11 KiB
Go
317 lines
11 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"online-back/internal/cards/cardrekwizit"
|
|
"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[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, '')`
|
|
|
|
const cardRekwizitOrderListFromClause = cardRekwizitOrderFromClause + `
|
|
LEFT JOIN provinces bp ON bp.id = b.province_id`
|
|
|
|
var cardRekwizitOrderListColumns = `cro.id, cro.unique_id, cro.card_type_id, ct.name,
|
|
cro.customer_name, cro.customer_surname, cro.user_id, ` + shared.UserDisplaySQL + `,
|
|
cro.region, cro.branch_id, b.name, bp.name, cro.status`
|
|
|
|
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`,
|
|
cardRekwizitOrderListColumns, cardRekwizitOrderListFromClause, 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()
|
|
|
|
items := []cardrekwizit.CardRekwizitOrderListItemDTO{}
|
|
for rows.Next() {
|
|
item, err := scanCardRekwizitOrderListItem(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{}) {
|
|
conditions := []string{"cro.deleted_at IS NULL"}
|
|
|
|
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)))
|
|
}
|
|
|
|
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 AND cro.deleted_at IS NULL`
|
|
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 AND deleted_at IS NULL
|
|
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 scanCardRekwizitOrderListItem(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderListItemDTO, error) {
|
|
var item cardrekwizit.CardRekwizitOrderListItemDTO
|
|
var cardTypeId, branchId int64
|
|
var userId *int64
|
|
var cardTypeNameJSON, branchNameJSON, provinceNameJSON []byte
|
|
var userName string
|
|
|
|
if err := row.Scan(
|
|
&item.Id, &item.UniqueId, &cardTypeId, &cardTypeNameJSON,
|
|
&item.CustomerName, &item.CustomerSurname, &userId, &userName,
|
|
&item.Region, &branchId, &branchNameJSON, &provinceNameJSON, &item.Status,
|
|
); err != nil {
|
|
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
|
}
|
|
|
|
var cardTypeName, branchName shared.LocalizedText
|
|
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
|
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
|
}
|
|
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
|
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
|
}
|
|
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
|
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
|
}
|
|
if cardTypeId != 0 {
|
|
item.CardType = &shared.NamedInfo{Id: cardTypeId, Name: cardTypeName}
|
|
}
|
|
if branchId != 0 {
|
|
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
|
|
}
|
|
if userId != nil {
|
|
item.User = &cardrekwizit.ListUserDTO{Id: *userId, Name: userName}
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
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
|
|
}
|