Enrich cards API responses with joined relations and share common helpers.
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled

Nest user/branch/cardType/cardState on card, order, pin-order, and visa-master
reads; accept flexible dates/IDs on pin create; widen pin region; ignore undefined
list query params; extract internal/cards/shared to remove duplicated types and helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-26 12:46:50 +05:00
parent 1fd0abbcb2
commit 0098422798
27 changed files with 942 additions and 777 deletions

View File

@@ -219,7 +219,7 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
user_id bigint,
card_type_id bigint NOT NULL,
card_number character varying(255),
region character varying(2) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,

View File

@@ -0,0 +1,3 @@
ALTER TABLE card_pin_orders
ALTER COLUMN region TYPE character varying(2)
USING LEFT(region, 2);

View File

@@ -0,0 +1,2 @@
ALTER TABLE card_pin_orders
ALTER COLUMN region TYPE character varying(255);

View File

@@ -500,7 +500,7 @@ INSERT INTO loan_orders (
loan_order_required_doc_id, status, satisfiable, notes
) VALUES
(
'LO-2026-0001', 'web', 9, 1, 'AG', 1,
'0001', 'mobile', 9, 1, 'AG', 1,
'Kerim', 'Atayew', 'Begliýewiç',
'Ashgabat, Bitaraplyk 20', 'Ashgabat, Bitaraplyk 20', 'I-AG', '101010',
'2017-01-15', 'Ashgabat City Police', 'Ashgabat', '1989-03-21',
@@ -517,7 +517,7 @@ INSERT INTO loan_orders (
1, 'pending', 'yes', 'Consumer loan application'
),
(
'LO-2026-0002', 'web', 10, 3, 'AG', 2,
'0002', 'mobile', 10, 3, 'AG', 2,
'Leyla', 'Gurbanowa', 'Saparowna',
'Ashgabat, Andalyp 8', 'Ashgabat, Andalyp 8', 'I-AG', '303030',
'2016-09-10', 'Ashgabat City Police', 'Ashgabat', '1994-08-02',
@@ -531,7 +531,7 @@ INSERT INTO loan_orders (
2, 'approved', 'yes', 'Auto loan approved'
),
(
'LO-2026-0003', 'branch', 7, 2, 'MR', 7,
'0003', 'mobile', 7, 2, 'MR', 7,
'Dovran', 'Annayew', 'Hojamyradowiç',
'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233',
'2012-04-22', 'Mary Police', 'Mary', '1995-01-25',
@@ -548,7 +548,7 @@ INSERT INTO loan_orders (
4, 'review', 'pending', 'Mortgage under review'
),
(
'LO-2026-0004', 'web', NULL, 4, 'LB', 6,
'0004', 'mobile', NULL, 4, 'LB', 6,
'Oguljenan', 'Çaryýewa', 'Myradowna',
'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060',
'2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12',

View File

@@ -4,9 +4,9 @@ import (
"context"
"fmt"
"strings"
"time"
"online-back/internal/cards/cardorder"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -41,6 +41,15 @@ var cardOrderColumnsSQL = strings.Join(cardOrderColumns, ", ")
var cardOrderWritableColumnsSQL = strings.Join(cardOrderWritableColumns, ", ")
const cardOrderFromClause = ` FROM card_orders co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`
var cardOrderSelectColumns = shared.PrefixedColumns("co", cardOrderColumns) + `,
cs.name, 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"
@@ -59,46 +68,56 @@ func resolvePaid(paid *bool) bool {
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, optionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, optionalInt64(dto.UserId), resolvePaid(dto.Paid),
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), resolvePaid(dto.Paid),
}
}
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, optionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, optionalInt64(dto.UserId), dto.Paid,
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), dto.Paid,
}
}
func optionalTime(t *cardorder.FlexibleTime) *time.Time {
if t == nil || t.IsZero() {
return nil
}
tt := t.Time()
return &tt
}
func optionalInt64(n *cardorder.FlexibleInt64) *int64 {
if n == nil {
return nil
}
v := n.Int64()
return &v
}
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_orders co`+whereClause, args...).Scan(&count); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY co.id LIMIT $%d OFFSET $%d`,
cardOrderSelectColumns, cardOrderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
defer rows.Close()
var items []cardorder.CardOrderDTO
for rows.Next() {
item, err := scanCardOrderWithJoins(rows)
if err != nil {
return cardorder.ListCardOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardorder.ListCardOrderDTO{}, err
}
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
}
@@ -108,34 +127,34 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.status = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds)
conditions, args = rbac.AppendBranchIDs(conditions, args, "co.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.user_id = $%d", len(args)))
}
if filter.CardStateId != nil {
args = append(args, *filter.CardStateId)
conditions = append(conditions, fmt.Sprintf("card_state_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.card_state_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("co.region = $%d", len(args)))
}
if len(conditions) == 0 {
@@ -146,7 +165,8 @@ func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []int
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1`
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
@@ -157,12 +177,22 @@ func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDT
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_orders (%s) VALUES (%s) RETURNING %s`,
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardOrderColumnsSQL,
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO card_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`,
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
cardOrderColumnsSQL, cardOrderSelectColumns,
)
return scanCardOrder(r.client.QueryRow(ctx, query, args...))
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
@@ -174,12 +204,22 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d
RETURNING %s
)
SELECT %s
FROM updated co
LEFT JOIN card_states cs ON cs.id = co.card_state_id
LEFT JOIN card_types ct ON ct.id = co.card_type_id
LEFT JOIN branches b ON b.id = co.branch_id
LEFT JOIN users u ON u.id = co.user_id`,
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL, cardOrderSelectColumns,
)
item, err := scanCardOrder(r.client.QueryRow(ctx, query, args...))
item, err := scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardorder.CardOrderDTO{}, err
}
@@ -191,17 +231,67 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
return scanCardOrderRow(row, false)
}
func scanCardOrderWithJoins(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
return scanCardOrderRow(row, true)
}
func scanCardOrderRow(row genericrepo.Scanner, withJoins bool) (cardorder.CardOrderDTO, error) {
var item cardorder.CardOrderDTO
err := row.Scan(
dest := []interface{}{
&item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.OldSurname, &item.Citizenship,
&item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy, &item.BornPlace,
&item.JobLocation, &item.PassportAddress, &item.RealAddress, &item.Phone, &item.PhoneAdditional,
&item.Status, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour, &item.Notes, &item.UserId, &item.Paid,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
}
var cardStateNameJSON, cardTypeNameJSON, branchNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withJoins {
dest = append(dest,
&cardStateNameJSON, &cardTypeNameJSON, &branchNameJSON,
&userName, &userUsername, &userPhone, &userEmail,
)
}
if err := row.Scan(dest...); err != nil {
return cardorder.CardOrderDTO{}, err
}
if !withJoins {
return item, nil
}
var cardStateName, cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardStateNameJSON, &cardStateName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardorder.CardOrderDTO{}, err
}
if item.CardStateId != 0 {
item.CardState = &shared.NamedInfo{Id: item.CardStateId, Name: cardStateName}
}
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
}

View File

@@ -1,212 +1,112 @@
package cardorder
import (
"encoding/json"
"strconv"
"strings"
"time"
"online-back/internal/cards/shared"
)
type FlexibleTime time.Time
func (t FlexibleTime) Time() time.Time { return time.Time(t) }
func (t FlexibleTime) IsZero() bool { return time.Time(t).IsZero() }
func (t FlexibleTime) MarshalJSON() ([]byte, error) {
return time.Time(t).MarshalJSON()
}
func (t *FlexibleTime) UnmarshalJSON(b []byte) error {
*t = FlexibleTime{}
raw := strings.TrimSpace(string(b))
if raw == "" || raw == "null" {
return nil
}
var n json.Number
if err := json.Unmarshal(b, &n); err == nil {
s := n.String()
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
return nil
}
if unix, err := n.Int64(); err == nil && unix > 0 {
*t = FlexibleTime(time.Unix(unix, 0).UTC())
}
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return nil
}
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
}
return nil
}
func parseFlexibleTime(s string) (FlexibleTime, bool) {
s = strings.TrimSpace(s)
if s == "" {
return FlexibleTime{}, false
}
switch strings.ToLower(s) {
case "string", "undefined", "null", "none", "invalid", "nan", "-":
return FlexibleTime{}, false
}
for _, layout := range []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
"02.01.2006",
"02/01/2006",
"02-01-2006",
"2006/01/02",
"20060102",
} {
if parsed, err := time.Parse(layout, s); err == nil {
return FlexibleTime(parsed), true
}
}
return FlexibleTime{}, false
}
type FlexibleInt64 int64
func (n FlexibleInt64) Int64() int64 { return int64(n) }
func (n *FlexibleInt64) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
*n = 0
return nil
}
var v int64
if err := json.Unmarshal(b, &v); err == nil {
*n = FlexibleInt64(v)
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
s = strings.TrimSpace(s)
if s == "" {
*n = 0
return nil
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*n = FlexibleInt64(v)
return nil
}
type CardOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"cardStateId"`
CardTypeId int64 `json:"cardTypeId"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
CustomerName string `json:"customerName"`
CustomerSurname string `json:"customerSurname"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportGivenAt time.Time `json:"passportGivenAt"`
PassportGivenBy string `json:"passportGivenBy"`
BornPlace string `json:"bornPlace"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Notes *string `json:"notes"`
UserId *int64 `json:"userId"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CardStateId int64 `json:"-"`
CardState *shared.NamedInfo `json:"cardState,omitempty"`
CardTypeId int64 `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
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"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship"`
PassportSerie string `json:"passportSerie"`
PassportId string `json:"passportId"`
PassportGivenAt time.Time `json:"passportGivenAt"`
PassportGivenBy string `json:"passportGivenBy"`
BornPlace string `json:"bornPlace"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Notes *string `json:"notes"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"`
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid *bool `json:"paid"`
UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
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" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid *bool `json:"paid"`
}
type UpdateCardOrderDTO struct {
UniqueId *string `json:"uniqueId"`
CardStateId FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
Region string `json:"region" binding:"required"`
BranchId FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *FlexibleTime `json:"bornAt" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid bool `json:"paid"`
UniqueId *string `json:"uniqueId"`
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
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" swaggertype:"string" format:"date"`
OldSurname *string `json:"oldSurname"`
Citizenship string `json:"citizenship" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" binding:"required"`
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
BornPlace string `json:"bornPlace" binding:"required"`
JobLocation *string `json:"jobLocation"`
PassportAddress *string `json:"passportAddress"`
RealAddress *string `json:"realAddress"`
Phone *string `json:"phone"`
PhoneAdditional *string `json:"phoneAdditional"`
Status *string `json:"status"`
PassportOne string `json:"passportOne" binding:"required"`
PassportTwo string `json:"passportTwo" binding:"required"`
PassportThree string `json:"passportThree" binding:"required"`
PassportFour string `json:"passportFour" binding:"required"`
Notes *string `json:"notes"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
Paid bool `json:"paid"`
}
type ListFilter struct {

View File

@@ -3,10 +3,9 @@ package cardorder
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
@@ -83,7 +82,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -151,7 +150,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -195,7 +194,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -217,74 +216,42 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card order removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := optionalQueryID(c, "branch_id", "branchId"); !ok {
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if id, ok := optionalQueryID(c, "card_state_id", "cardStateId"); !ok {
if id, ok := shared.OptionalQueryID(c, "card_state_id", "cardStateId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardStateId = id
}
if id, ok := optionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardTypeId = id
}
if raw := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > maxLimit {
limit = maxLimit
}
filter.Limit = limit
}
if raw := queryValue(c, "status"); raw != "" {
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := queryValue(c, "region"); raw != "" {
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
@@ -307,24 +274,3 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
}
return rbac.GuardBranch(c, item.BranchId)
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
raw := queryValue(c, keys...)
if raw == "" {
return nil, true
}
id, ok := parseID(raw)
if !ok {
return nil, false
}
return &id, true
}

View File

@@ -6,6 +6,7 @@ import (
"strings"
"online-back/internal/cards/cardpinorders"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -26,8 +27,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorde
}
}
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
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",
@@ -41,10 +40,18 @@ 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, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
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,
}
@@ -52,8 +59,8 @@ func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
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,
}
@@ -62,10 +69,36 @@ func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
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 %s%s%s ORDER BY cpo.id LIMIT $%d OFFSET $%d`,
cardPinOrderSelectColumns, cardPinOrderFromClause, 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()
var items []cardpinorders.CardPinOrderDTO
for rows.Next() {
item, err := scanCardPinOrderWithJoins(rows)
if 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
}
@@ -75,29 +108,29 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.status = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "branch_id", filter.BranchIds)
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("branch_id = $%d", len(args)))
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("user_id = $%d", len(args)))
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("card_type_id = $%d", len(args)))
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("region = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
}
if len(conditions) == 0 {
@@ -108,7 +141,8 @@ func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args [
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1`
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
@@ -119,12 +153,21 @@ func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPin
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO card_pin_orders (%s) VALUES (%s) RETURNING %s`,
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
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 scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
@@ -136,12 +179,21 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d
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 := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
item, err := scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardpinorders.CardPinOrderDTO{}, err
}
@@ -153,16 +205,57 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
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
err := row.Scan(
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,
)
if err != nil {
}
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
}

View File

@@ -1,74 +1,81 @@
package cardpinorders
import "time"
import (
"time"
"online-back/internal/cards/shared"
)
type CardPinOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region"`
BranchId int64 `json:"branchId"`
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"`
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"`
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 CreateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
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"`
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber *string `json:"cardNumber"`
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" swaggertype:"string" format:"date"`
Phone *string `json:"phone"`
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 UpdateCardPinOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"userId"`
CardTypeId int64 `json:"cardTypeId" binding:"required"`
CardNumber *string `json:"cardNumber"`
Region string `json:"region" binding:"required"`
BranchId int64 `json:"branchId" binding:"required"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt *time.Time `json:"bornAt"`
Phone *string `json:"phone"`
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"`
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber *string `json:"cardNumber"`
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" swaggertype:"string" format:"date"`
Phone *string `json:"phone"`
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 {

View File

@@ -3,10 +3,9 @@ package cardpinorders
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
@@ -82,7 +81,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -149,7 +148,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -192,7 +191,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /card-pin-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -214,71 +213,36 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin order removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
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 raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
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 := c.Query("card_type_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.CardTypeId = &id
}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}

View File

@@ -6,6 +6,7 @@ import (
"strings"
"online-back/internal/cards/cards"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
@@ -38,6 +39,12 @@ var cardColumnsSQL = strings.Join(cardColumns, ", ")
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
const cardFromClause = ` FROM cards c
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, '')`
func createArgs(dto cards.CreateCardDTO) []interface{} {
return []interface{}{
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
@@ -53,10 +60,36 @@ func updateArgs(dto cards.UpdateCardDTO) []interface{} {
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM cards c`+whereClause, args...).Scan(&count); err != nil {
return cards.ListCardDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
cardSelectColumns, cardFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cards.ListCardDTO{}, err
}
defer rows.Close()
var items []cards.CardDTO
for rows.Next() {
item, err := scanCardWithUser(rows)
if err != nil {
return cards.ListCardDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cards.ListCardDTO{}, err
}
return cards.ListCardDTO{Count: count, Cards: items}, nil
}
@@ -66,17 +99,17 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("c.user_id = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("user_id", len(args)))
conditions = append(conditions, rbac.UserInBranchSQL("c.user_id", len(args)))
}
if filter.Type != nil {
args = append(args, *filter.Type)
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))
conditions = append(conditions, fmt.Sprintf("c.type = $%d", len(args)))
}
if len(conditions) == 0 {
@@ -87,7 +120,8 @@ func buildListQuery(filter cards.ListFilter) (whereClause string, args []interfa
}
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
return r.generic.GetByID(ctx, id)
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1`
return scanCardWithUser(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
@@ -98,12 +132,19 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
placeholders[i] = fmt.Sprintf("$%d", i+1)
}
query := fmt.Sprintf(
`INSERT INTO cards (%s) VALUES (%s) RETURNING %s`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "), cardColumnsSQL,
query := fmt.Sprintf(`
WITH inserted AS (
INSERT INTO cards (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted c
LEFT JOIN users u ON u.id = c.user_id`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "),
cardColumnsSQL, cardSelectColumns,
)
return scanCard(r.client.QueryRow(ctx, query, args...))
return scanCardWithUser(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
@@ -115,12 +156,19 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
}
args = append(args, id)
query := fmt.Sprintf(
`UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL,
query := fmt.Sprintf(`
WITH updated AS (
UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d
RETURNING %s
)
SELECT %s
FROM updated c
LEFT JOIN users u ON u.id = c.user_id`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL, cardSelectColumns,
)
item, err := scanCard(r.client.QueryRow(ctx, query, args...))
item, err := scanCardWithUser(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cards.CardDTO{}, err
}
@@ -132,13 +180,36 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
}
func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) {
return scanCardRow(row, false)
}
func scanCardWithUser(row genericrepo.Scanner) (cards.CardDTO, error) {
return scanCardRow(row, true)
}
func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error) {
var item cards.CardDTO
err := row.Scan(
dest := []interface{}{
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,
&item.CreatedAt, &item.UpdatedAt,
)
if err != nil {
}
var userName, userUsername, userPhone, userEmail string
if withUser {
dest = append(dest, &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,
}
}
return item, nil
}

View File

@@ -1,17 +1,22 @@
package cards
import "time"
import (
"time"
"online-back/internal/cards/shared"
)
type CardDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"userId"`
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:"type"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardDTO struct {

View File

@@ -3,10 +3,9 @@ package cards
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
@@ -79,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -150,7 +149,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -193,7 +192,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -215,54 +214,23 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
if raw := strings.TrimSpace(c.Query("type")); raw != "" {
if raw := shared.QueryValue(c, "type"); raw != "" {
filter.Type = &raw
}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -8,6 +8,7 @@ import (
"strings"
"online-back/internal/cards/paymentcard"
"online-back/internal/cards/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -133,7 +134,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
func marshalName(title shared.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}

View File

@@ -1,31 +1,27 @@
package paymentcard
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
import "online-back/internal/cards/shared"
type PaymentCardDTO struct {
Id int64 `json:"id"`
Price string `json:"price"`
Title LocalizedText `json:"title"`
Notes string `json:"notes"`
Active bool `json:"active"`
Id int64 `json:"id"`
Price string `json:"price"`
Title shared.LocalizedText `json:"title"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type CreatePaymentCardDTO struct {
Price string `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
Price string `json:"price" binding:"required"`
Title shared.LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
}
type UpdatePaymentCardDTO struct {
Price string `json:"price" binding:"required"`
Title LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
Price string `json:"price" binding:"required"`
Title shared.LocalizedText `json:"title" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type UpdatePaymentCardActiveDTO struct {

View File

@@ -4,9 +4,9 @@ import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/pkg/logging"
@@ -79,7 +79,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -143,7 +143,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -184,7 +184,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id}/active [put]
func (h *handler) updateActive(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -223,7 +223,7 @@ func (h *handler) updateActive(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /payment-cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -241,47 +241,18 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("card_name")); raw != "" {
if raw := shared.QueryValue(c, "card_name", "cardName"); raw != "" {
filter.CardName = raw
}
if raw := c.Query("active"); raw != "" {
if raw := shared.QueryValue(c, "active"); raw != "" {
active, err := strconv.ParseBool(raw)
if err != nil {
return ListFilter{}, false

View File

@@ -8,6 +8,7 @@ import (
"strings"
"online-back/internal/cards/reasonscard"
"online-back/internal/cards/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
@@ -115,7 +116,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
func marshalName(title shared.LocalizedText) ([]byte, error) {
return json.Marshal(title)
}

View File

@@ -1,35 +1,33 @@
package reasonscard
import "time"
import (
"time"
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
"online-back/internal/cards/shared"
)
type ReasonCardDTO struct {
Id int64 `json:"id"`
Title LocalizedText `json:"title"`
Price string `json:"price"`
Notes string `json:"notes"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
Title shared.LocalizedText `json:"title"`
Price string `json:"price"`
Notes string `json:"notes"`
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
Title shared.LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active *bool `json:"active"`
}
type UpdateReasonCardDTO struct {
Title LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
Title shared.LocalizedText `json:"title" binding:"required"`
Price string `json:"price" binding:"required"`
Notes string `json:"notes"`
Active bool `json:"active"`
}
type ListFilter struct {

View File

@@ -3,10 +3,9 @@ package reasonscard
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/pkg/logging"
@@ -77,7 +76,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -141,7 +140,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -180,7 +179,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /reasons-cards/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -198,43 +197,14 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("reason card removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("reason_name")); raw != "" {
if raw := shared.QueryValue(c, "reason_name", "reasonName"); raw != "" {
filter.ReasonName = raw
}

View File

@@ -0,0 +1,111 @@
package shared
import (
"encoding/json"
"strconv"
"strings"
"time"
)
type FlexibleTime time.Time
func (t FlexibleTime) Time() time.Time { return time.Time(t) }
func (t FlexibleTime) IsZero() bool { return time.Time(t).IsZero() }
func (t FlexibleTime) MarshalJSON() ([]byte, error) {
return time.Time(t).MarshalJSON()
}
func (t *FlexibleTime) UnmarshalJSON(b []byte) error {
*t = FlexibleTime{}
raw := strings.TrimSpace(string(b))
if raw == "" || raw == "null" {
return nil
}
var n json.Number
if err := json.Unmarshal(b, &n); err == nil {
s := n.String()
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
return nil
}
if unix, err := n.Int64(); err == nil && unix > 0 {
*t = FlexibleTime(time.Unix(unix, 0).UTC())
}
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return nil
}
if parsed, ok := parseFlexibleTime(s); ok {
*t = parsed
}
return nil
}
func parseFlexibleTime(s string) (FlexibleTime, bool) {
s = strings.TrimSpace(s)
if s == "" {
return FlexibleTime{}, false
}
switch strings.ToLower(s) {
case "string", "undefined", "null", "none", "invalid", "nan", "-":
return FlexibleTime{}, false
}
for _, layout := range []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05",
"2006-01-02 15:04:05",
"2006-01-02",
"02.01.2006",
"02/01/2006",
"02-01-2006",
"2006/01/02",
"20060102",
} {
if parsed, err := time.Parse(layout, s); err == nil {
return FlexibleTime(parsed), true
}
}
return FlexibleTime{}, false
}
type FlexibleInt64 int64
func (n FlexibleInt64) Int64() int64 { return int64(n) }
func (n *FlexibleInt64) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
*n = 0
return nil
}
var v int64
if err := json.Unmarshal(b, &v); err == nil {
*n = FlexibleInt64(v)
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
s = strings.TrimSpace(s)
if s == "" {
*n = 0
return nil
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*n = FlexibleInt64(v)
return nil
}

View File

@@ -0,0 +1,69 @@
package shared
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
const (
DefaultPage = 1
DefaultLimit = 10
MaxLimit = 100
)
func ParseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func QueryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func OptionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
raw := QueryValue(c, keys...)
if raw == "" {
return nil, true
}
id, ok := ParseID(raw)
if !ok {
return nil, false
}
return &id, true
}
func ParsePageLimit(c *gin.Context) (page, limit int, ok bool) {
page = DefaultPage
limit = DefaultLimit
if raw := QueryValue(c, "page"); raw != "" {
p, err := strconv.Atoi(raw)
if err != nil || p < 1 {
return 0, 0, false
}
page = p
}
if raw := QueryValue(c, "limit"); raw != "" {
l, err := strconv.Atoi(raw)
if err != nil || l < 1 {
return 0, 0, false
}
if l > MaxLimit {
l = MaxLimit
}
limit = l
}
return page, limit, true
}

View File

@@ -0,0 +1,40 @@
package shared
import (
"encoding/json"
"strings"
"time"
)
const UserDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
func PrefixedColumns(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func UnmarshalLocalized(raw []byte, dest *LocalizedText) error {
if len(raw) == 0 {
return nil
}
return json.Unmarshal(raw, dest)
}
func OptionalTime(t *FlexibleTime) *time.Time {
if t == nil || t.IsZero() {
return nil
}
tt := t.Time()
return &tt
}
func OptionalInt64(n *FlexibleInt64) *int64 {
if n == nil {
return nil
}
v := n.Int64()
return &v
}

View File

@@ -0,0 +1,20 @@
package shared
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type NamedInfo struct {
Id int64 `json:"id"`
Name LocalizedText `json:"name"`
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"strings"
"online-back/internal/cards/shared"
"online-back/internal/cards/visamaster"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
@@ -27,8 +28,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) visamaster.
}
}
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const orderFromClause = ` FROM visa_master_payment_orders o
LEFT JOIN branches b ON b.id = o.branch_id
LEFT JOIN users u ON u.id = o.user_id
@@ -50,15 +49,7 @@ var orderColumnsSQL = strings.Join(orderColumns, ", ")
var orderWritableColumnsSQL = strings.Join(orderWritableColumns, ", ")
var orderSelectColumns = prefixedColumns("o", orderColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), COALESCE(b.region, ''), b.province_id, p.name, ` + userDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func prefixedColumns(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
var orderSelectColumns = shared.PrefixedColumns("o", orderColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), COALESCE(b.region, ''), b.province_id, p.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
@@ -282,18 +273,18 @@ func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, e
item.Branch.Id = item.BranchId
item.Branch.Region = branchRegion
if err := unmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
if err := shared.UnmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := unmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil {
if err := shared.UnmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if err := unmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil {
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil {
return visamaster.VisaMasterPaymentOrderDTO{}, err
}
if item.UserId != nil {
item.User = &visamaster.UserInfo{
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
@@ -311,10 +302,3 @@ func jsonOrDefault(raw []byte, fallback string) json.RawMessage {
}
return json.RawMessage(raw)
}
func unmarshalLocalized(raw []byte, dest *visamaster.LocalizedText) error {
if len(raw) == 0 {
return nil
}
return json.Unmarshal(raw, dest)
}

View File

@@ -3,62 +3,50 @@ package visamaster
import (
"encoding/json"
"time"
"online-back/internal/cards/shared"
)
type LocalizedText struct {
En string `json:"en"`
Ru string `json:"ru"`
Tm string `json:"tm"`
}
type BranchInfo struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name LocalizedText `json:"name"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName LocalizedText `json:"provinceName"`
}
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name shared.LocalizedText `json:"name"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
ProvinceName shared.LocalizedText `json:"provinceName"`
}
type VisaMasterPaymentOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
PassportName string `json:"passportName"`
PassportSurname string `json:"passportSurname"`
Phone string `json:"phone"`
Email *string `json:"email"`
Region string `json:"region"`
RegionName LocalizedText `json:"regionName"`
BranchId int64 `json:"branchId"`
Branch BranchInfo `json:"branch"`
UserId *int64 `json:"userId"`
User *UserInfo `json:"user"`
Address string `json:"address"`
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
Documents json.RawMessage `json:"documents" swaggertype:"object"`
Status *string `json:"status"`
Notes *string `json:"notes"`
SenderFullName string `json:"senderFullName"`
SenderPassportSerie string `json:"senderPassportSerie"`
SenderPassportNumber string `json:"senderPassportNumber"`
SenderDepositAccount string `json:"senderDepositAccount"`
RecieverFullName *string `json:"recieverFullName"`
RecieverPassportSerie *string `json:"recieverPassportSerie"`
RecieverPassportNumber *string `json:"recieverPassportNumber"`
RecieverDepositAccount *string `json:"recieverDepositAccount"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Type *string `json:"type"`
PassportName string `json:"passportName"`
PassportSurname string `json:"passportSurname"`
Phone string `json:"phone"`
Email *string `json:"email"`
Region string `json:"region"`
RegionName shared.LocalizedText `json:"regionName,omitempty"`
BranchId int64 `json:"-"`
Branch BranchInfo `json:"branch"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Address string `json:"address"`
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
Documents json.RawMessage `json:"documents" swaggertype:"object"`
Status *string `json:"status"`
Notes *string `json:"notes"`
SenderFullName string `json:"senderFullName"`
SenderPassportSerie string `json:"senderPassportSerie"`
SenderPassportNumber string `json:"senderPassportNumber"`
SenderDepositAccount string `json:"senderDepositAccount"`
RecieverFullName *string `json:"recieverFullName"`
RecieverPassportSerie *string `json:"recieverPassportSerie"`
RecieverPassportNumber *string `json:"recieverPassportNumber"`
RecieverDepositAccount *string `json:"recieverDepositAccount"`
Paid bool `json:"paid"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateVisaMasterPaymentOrderDTO struct {

View File

@@ -3,10 +3,9 @@ package visamaster
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
@@ -82,7 +81,7 @@ func (h *handler) list(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -149,7 +148,7 @@ func (h *handler) create(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -192,7 +191,7 @@ func (h *handler) update(c *gin.Context) {
// @Failure 500 {object} appresult.AppError
// @Router /visa-master-payment-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
@@ -214,68 +213,35 @@ func (h *handler) delete(c *gin.Context) {
c.JSON(http.StatusOK, appresult.SuccessWithData("visa master payment order removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
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 > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("name")); raw != "" {
if raw := shared.QueryValue(c, "name"); raw != "" {
filter.Name = raw
}
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
if raw := c.Query("branch_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.BranchId = &id
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if raw := c.Query("user_id"); raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
rbac.BindBranchIDs(c, &filter.BranchIds)

View File

@@ -196,9 +196,10 @@ func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrde
return scanLoanOrder(r.client.QueryRow(ctx, query, id))
}
// nextUniqueIDSQL computes unique_id as the last value stored in loan_orders plus
// one, zero-padded to 4 digits, mirroring a serial/auto-increment column.
const nextUniqueIDSQL = `(SELECT LPAD((COALESCE(MAX(unique_id::bigint), 0) + 1)::text, 4, '0') FROM loan_orders)`
// nextUniqueIDSQL computes unique_id as the last numeric value stored in
// loan_orders plus one, zero-padded to 4 digits. Non-numeric rows (e.g. legacy
// "LO-2026-0001") are ignored so CREATE does not fail with a cast error.
const nextUniqueIDSQL = `(SELECT LPAD((COALESCE(MAX(CASE WHEN unique_id ~ '^[0-9]+$' THEN unique_id::bigint END), 0) + 1)::text, 4, '0') FROM loan_orders)`
func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
// unique_id is supplied positionally via nextUniqueIDSQL below, so drop it