changed column name
This commit is contained in:
@@ -24,16 +24,37 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) branches.Re
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const branchColumns = `b.id, b.title, b.province_id, b.location_id, b.unikal_nomer, b.address,
|
||||
b.billing_username, b.billing_password, b.billing_username_sber, b.billing_password_sber,
|
||||
b.billing_username_visa, b.billing_password_visa,
|
||||
b.billing_username_swift, b.billing_password_swift`
|
||||
const branchFromClause = ` FROM branches b
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`
|
||||
|
||||
const branchSelectColumns = `b.id, b.unique_code, b.name, b.address, b.region, b.province_id, p.name,
|
||||
b.phone_numbers, b.billing_username, b.billing_password,
|
||||
b.billing_sber_username, b.billing_sber_password,
|
||||
b.billing_visa_master_username, b.billing_visa_master_password,
|
||||
b.billing_swift_username, b.billing_swift_password, b.active`
|
||||
|
||||
const branchReturningColumns = `id, unique_code, name, address, region, province_id, phone_numbers,
|
||||
billing_username, billing_password, billing_sber_username, billing_sber_password,
|
||||
billing_visa_master_username, billing_visa_master_password,
|
||||
billing_swift_username, billing_swift_password, active`
|
||||
|
||||
const branchReturnedSelectColumns = `i.id, i.unique_code, i.name, i.address, i.region, i.province_id, p.name,
|
||||
i.phone_numbers, i.billing_username, i.billing_password,
|
||||
i.billing_sber_username, i.billing_sber_password,
|
||||
i.billing_visa_master_username, i.billing_visa_master_password,
|
||||
i.billing_swift_username, i.billing_swift_password, i.active`
|
||||
|
||||
const branchUpdatedSelectColumns = `u.id, u.unique_code, u.name, u.address, u.region, u.province_id, p.name,
|
||||
u.phone_numbers, u.billing_username, u.billing_password,
|
||||
u.billing_sber_username, u.billing_sber_password,
|
||||
u.billing_visa_master_username, u.billing_visa_master_password,
|
||||
u.billing_swift_username, u.billing_swift_password, u.active`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter branches.ListFilter) (branches.ListBranchDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
countQuery := `SELECT COUNT(*) ` + fromClause + whereClause
|
||||
countQuery := `SELECT COUNT(*)` + branchFromClause + whereClause
|
||||
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
|
||||
return branches.ListBranchDTO{}, err
|
||||
}
|
||||
@@ -43,7 +64,7 @@ func (r *repository) List(ctx context.Context, filter branches.ListFilter) (bran
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY b.id LIMIT $%d OFFSET $%d`,
|
||||
branchColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
branchSelectColumns, branchFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
listArgs := append(args, filter.Limit, offset)
|
||||
|
||||
@@ -68,13 +89,7 @@ func (r *repository) List(ctx context.Context, filter branches.ListFilter) (bran
|
||||
return branches.ListBranchDTO{Count: count, Branches: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM branches b`
|
||||
|
||||
if filter.ProvinceName != "" {
|
||||
fromClause += ` JOIN provinces p ON p.id = b.province_id`
|
||||
}
|
||||
|
||||
func buildListQuery(filter branches.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.ProvinceID != nil {
|
||||
@@ -82,16 +97,11 @@ func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string,
|
||||
conditions = append(conditions, fmt.Sprintf("b.province_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.LocationID != nil {
|
||||
args = append(args, *filter.LocationID)
|
||||
conditions = append(conditions, fmt.Sprintf("b.location_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.ProvinceName != "" {
|
||||
args = append(args, likePattern(filter.ProvinceName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
p.title->>'en' ILIKE $%[1]d OR p.title->>'ru' ILIKE $%[1]d OR p.title->>'tm' ILIKE $%[1]d
|
||||
p.name->>'en' ILIKE $%[1]d OR p.name->>'ru' ILIKE $%[1]d OR p.name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
@@ -99,21 +109,21 @@ func buildListQuery(filter branches.ListFilter) (fromClause, whereClause string,
|
||||
args = append(args, likePattern(filter.BranchName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
b.title->>'en' ILIKE $%[1]d OR b.title->>'ru' ILIKE $%[1]d OR b.title->>'tm' ILIKE $%[1]d
|
||||
b.name->>'en' ILIKE $%[1]d OR b.name->>'ru' ILIKE $%[1]d OR b.name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.UnikalNomer != "" {
|
||||
args = append(args, likePattern(filter.UnikalNomer))
|
||||
if filter.UniqueCode != "" {
|
||||
args = append(args, likePattern(filter.UniqueCode))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf("b.unikal_nomer ILIKE $%d", n))
|
||||
conditions = append(conditions, fmt.Sprintf("b.unique_code ILIKE $%d", n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
return "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
@@ -124,7 +134,7 @@ func likePattern(term string) string {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (branches.BranchDTO, error) {
|
||||
query := fmt.Sprintf(`SELECT %s FROM branches b WHERE b.id = $1`, branchColumns)
|
||||
query := fmt.Sprintf(`SELECT %s%s WHERE b.id = $1`, branchSelectColumns, branchFromClause)
|
||||
row := r.client.QueryRow(ctx, query, id)
|
||||
item, err := scanBranch(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -134,68 +144,84 @@ func (r *repository) GetByID(ctx context.Context, id int64) (branches.BranchDTO,
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto branches.CreateBranchDTO) (branches.BranchDTO, error) {
|
||||
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
|
||||
if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
|
||||
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
|
||||
name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers)
|
||||
if err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO branches (
|
||||
title, province_id, location_id, unikal_nomer, address,
|
||||
billing_username, billing_password, billing_username_sber, billing_password_sber,
|
||||
billing_username_visa, billing_password_visa,
|
||||
billing_username_swift, billing_password_swift
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
RETURNING %s`, branchColumns)
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO branches (
|
||||
unique_code, name, address, region, province_id, phone_numbers,
|
||||
billing_username, billing_password, billing_sber_username, billing_sber_password,
|
||||
billing_visa_master_username, billing_visa_master_password,
|
||||
billing_swift_username, billing_swift_password, active
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)
|
||||
RETURNING ` + branchReturningColumns + `
|
||||
)
|
||||
SELECT ` + branchReturnedSelectColumns + `
|
||||
FROM inserted i
|
||||
LEFT JOIN provinces p ON p.id = i.province_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
|
||||
dto.BillingUsernameVisa, dto.BillingPasswordVisa,
|
||||
dto.BillingUsernameSwift, dto.BillingPasswordSwift,
|
||||
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
||||
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
||||
dto.BillingSwiftUsername, dto.BillingSwiftPassword, active,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if isUniqueViolation(err) {
|
||||
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
|
||||
return branches.BranchDTO{}, fmt.Errorf("unique code already exists")
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto branches.UpdateBranchDTO) (branches.BranchDTO, error) {
|
||||
if err := r.ensureRelations(ctx, dto.ProvinceId, dto.LocationId); err != nil {
|
||||
if err := r.ensureProvince(ctx, dto.ProvinceId); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
|
||||
title, address, err := marshalBranchJSON(dto.Title, dto.Address)
|
||||
name, address, phoneNumbers, err := marshalBranchJSON(dto.Name, dto.Address, dto.PhoneNumbers)
|
||||
if err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE branches SET
|
||||
title = $1, province_id = $2, location_id = $3, unikal_nomer = $4, address = $5,
|
||||
billing_username = $6, billing_password = $7, billing_username_sber = $8,
|
||||
billing_password_sber = $9, billing_username_visa = $10, billing_password_visa = $11,
|
||||
billing_username_swift = $12, billing_password_swift = $13
|
||||
WHERE id = $14
|
||||
RETURNING %s`, branchColumns)
|
||||
query := `
|
||||
WITH updated AS (
|
||||
UPDATE branches SET
|
||||
unique_code = $1, name = $2, address = $3, region = $4, province_id = $5,
|
||||
phone_numbers = $6, billing_username = $7, billing_password = $8,
|
||||
billing_sber_username = $9, billing_sber_password = $10,
|
||||
billing_visa_master_username = $11, billing_visa_master_password = $12,
|
||||
billing_swift_username = $13, billing_swift_password = $14, active = $15
|
||||
WHERE id = $16
|
||||
RETURNING ` + branchReturningColumns + `
|
||||
)
|
||||
SELECT ` + branchUpdatedSelectColumns + `
|
||||
FROM updated u
|
||||
LEFT JOIN provinces p ON p.id = u.province_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
title, dto.ProvinceId, dto.LocationId, dto.UnikalNomer, address,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingUsernameSber, dto.BillingPasswordSber,
|
||||
dto.BillingUsernameVisa, dto.BillingPasswordVisa,
|
||||
dto.BillingUsernameSwift, dto.BillingPasswordSwift, id,
|
||||
nullIfEmpty(dto.UniqueCode), name, address, dto.Region, dto.ProvinceId, phoneNumbers,
|
||||
dto.BillingUsername, dto.BillingPassword, dto.BillingSberUsername, dto.BillingSberPassword,
|
||||
dto.BillingVisaMasterUsername, dto.BillingVisaMasterPassword,
|
||||
dto.BillingSwiftUsername, dto.BillingSwiftPassword, dto.Active, id,
|
||||
)
|
||||
item, err := scanBranch(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
if isUniqueViolation(err) {
|
||||
return branches.BranchDTO{}, fmt.Errorf("unikal nomer already exists")
|
||||
return branches.BranchDTO{}, fmt.Errorf("unique code already exists")
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
@@ -211,27 +237,44 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) ensureRelations(ctx context.Context, provinceID, locationID int64) error {
|
||||
func (r *repository) ensureProvince(ctx context.Context, provinceID *int64) error {
|
||||
if provinceID == nil {
|
||||
return nil
|
||||
}
|
||||
var id int64
|
||||
err := r.client.QueryRow(ctx,
|
||||
`SELECT id FROM location WHERE id = $1 AND province_id = $2`, locationID, provinceID,
|
||||
`SELECT id FROM provinces WHERE id = $1`, *provinceID,
|
||||
).Scan(&id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("location not found in province")
|
||||
return fmt.Errorf("province not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func marshalBranchJSON(title, address branches.LocalizedText) ([]byte, []byte, error) {
|
||||
titleJSON, err := json.Marshal(title)
|
||||
func marshalBranchJSON(name, address branches.LocalizedText, phoneNumbers []string) ([]byte, []byte, []byte, error) {
|
||||
nameJSON, err := json.Marshal(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
addressJSON, err := json.Marshal(address)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
return titleJSON, addressJSON, nil
|
||||
if phoneNumbers == nil {
|
||||
phoneNumbers = []string{}
|
||||
}
|
||||
phoneNumbersJSON, err := json.Marshal(phoneNumbers)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
return nameJSON, addressJSON, phoneNumbersJSON, nil
|
||||
}
|
||||
|
||||
func nullIfEmpty(value string) interface{} {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
@@ -245,22 +288,39 @@ type scannable interface {
|
||||
|
||||
func scanBranch(row scannable) (branches.BranchDTO, error) {
|
||||
var item branches.BranchDTO
|
||||
var titleJSON, addressJSON []byte
|
||||
var nameJSON, addressJSON, provinceNameJSON, phoneNumbersJSON []byte
|
||||
var uniqueCode *string
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &titleJSON, &item.ProvinceId, &item.LocationId, &item.UnikalNomer, &addressJSON,
|
||||
&item.BillingUsername, &item.BillingPassword, &item.BillingUsernameSber, &item.BillingPasswordSber,
|
||||
&item.BillingUsernameVisa, &item.BillingPasswordVisa,
|
||||
&item.BillingUsernameSwift, &item.BillingPasswordSwift,
|
||||
&item.Id, &uniqueCode, &nameJSON, &addressJSON, &item.Region, &item.ProvinceId, &provinceNameJSON,
|
||||
&phoneNumbersJSON,
|
||||
&item.BillingUsername, &item.BillingPassword,
|
||||
&item.BillingSberUsername, &item.BillingSberPassword,
|
||||
&item.BillingVisaMasterUsername, &item.BillingVisaMasterPassword,
|
||||
&item.BillingSwiftUsername, &item.BillingSwiftPassword, &item.Active,
|
||||
)
|
||||
if err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
|
||||
if uniqueCode != nil {
|
||||
item.UniqueCode = *uniqueCode
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(addressJSON, &item.Address); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
if provinceNameJSON != nil {
|
||||
if err := json.Unmarshal(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(phoneNumbersJSON, &item.PhoneNumbers); err != nil {
|
||||
return branches.BranchDTO{}, err
|
||||
}
|
||||
if item.PhoneNumbers == nil {
|
||||
item.PhoneNumbers = []string{}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -7,60 +7,66 @@ type LocalizedText struct {
|
||||
}
|
||||
|
||||
type BranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedText `json:"title"`
|
||||
ProvinceId int64 `json:"provinceId"`
|
||||
LocationId int64 `json:"locationId"`
|
||||
UnikalNomer string `json:"unikalNomer"`
|
||||
Address LocalizedText `json:"address"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
Address LocalizedText `json:"address"`
|
||||
Region string `json:"region"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
ProvinceName LocalizedText `json:"provinceName"`
|
||||
PhoneNumbers []string `json:"phoneNumbers"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingSberUsername string `json:"billingSberUsername"`
|
||||
BillingSberPassword string `json:"billingSberPassword"`
|
||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreateBranchDTO struct {
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
ProvinceId int64 `json:"provinceId" binding:"required"`
|
||||
LocationId int64 `json:"locationId" binding:"required"`
|
||||
UnikalNomer string `json:"unikalNomer" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
PhoneNumbers []string `json:"phoneNumbers"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingSberUsername string `json:"billingSberUsername"`
|
||||
BillingSberPassword string `json:"billingSberPassword"`
|
||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateBranchDTO struct {
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
ProvinceId int64 `json:"provinceId" binding:"required"`
|
||||
LocationId int64 `json:"locationId" binding:"required"`
|
||||
UnikalNomer string `json:"unikalNomer" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingUsernameSber string `json:"billingUsernameSber"`
|
||||
BillingPasswordSber string `json:"billingPasswordSber"`
|
||||
BillingUsernameVisa string `json:"billingUsernameVisa"`
|
||||
BillingPasswordVisa string `json:"billingPasswordVisa"`
|
||||
BillingUsernameSwift string `json:"billingUsernameSwift"`
|
||||
BillingPasswordSwift string `json:"billingPasswordSwift"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name" binding:"required"`
|
||||
Address LocalizedText `json:"address" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
PhoneNumbers []string `json:"phoneNumbers"`
|
||||
BillingUsername string `json:"billingUsername"`
|
||||
BillingPassword string `json:"billingPassword"`
|
||||
BillingSberUsername string `json:"billingSberUsername"`
|
||||
BillingSberPassword string `json:"billingSberPassword"`
|
||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
ProvinceID *int64
|
||||
LocationID *int64
|
||||
ProvinceName string
|
||||
BranchName string
|
||||
UnikalNomer string
|
||||
UniqueCode string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
@@ -41,10 +41,9 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param province_id query int false "Filter by province ID"
|
||||
// @Param location_id query int false "Filter by location ID"
|
||||
// @Param province_name query string false "Filter by province name (en, ru, tm)"
|
||||
// @Param branch_name query string false "Filter by branch name (en, ru, tm)"
|
||||
// @Param unikal_nomer query string false "Filter by unique number"
|
||||
// @Param unique_code query string false "Filter by unique code"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -212,7 +211,7 @@ func (h *handler) delete(c *gin.Context) {
|
||||
|
||||
func isClientError(err error) bool {
|
||||
msg := err.Error()
|
||||
return msg == "location not found in province" || msg == "unikal nomer already exists"
|
||||
return msg == "province not found" || msg == "unique code already exists"
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
@@ -243,14 +242,6 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.ProvinceID = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("location_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.LocationID = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
@@ -275,8 +266,8 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.BranchName = raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("unikal_nomer")); raw != "" {
|
||||
filter.UnikalNomer = raw
|
||||
if raw := strings.TrimSpace(c.Query("unique_code")); raw != "" {
|
||||
filter.UniqueCode = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
|
||||
@@ -23,7 +23,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) loansdocume
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const documentColumns = `d.id, d.title, d.content_en, d.content_ru, d.content_tm, d.status, d.created_at, d.updated_at`
|
||||
const documentColumns = `d.id, d.title, d.content_en, d.content_ru, d.content_tm, d.active, d.created_at, d.updated_at`
|
||||
|
||||
const documentReturningColumns = `id, title, content_en, content_ru, content_tm, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
@@ -75,9 +77,9 @@ func buildListQuery(filter loansdocument.ListFilter) (fromClause, whereClause st
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("d.status = $%d", len(args)))
|
||||
if filter.Active != nil {
|
||||
args = append(args, *filter.Active)
|
||||
conditions = append(conditions, fmt.Sprintf("d.active = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
@@ -109,17 +111,17 @@ func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDoc
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
status := true
|
||||
if dto.Status != nil {
|
||||
status = *dto.Status
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loan_required_documents (title, content_en, content_ru, content_tm, status)
|
||||
INSERT INTO loan_required_documents (title, content_en, content_ru, content_tm, active)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING %s`, documentColumns)
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
return scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, status))
|
||||
return scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.UpdateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
@@ -130,27 +132,27 @@ func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.Upd
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_required_documents SET
|
||||
title = $1, content_en = $2, content_ru = $3, content_tm = $4, status = $5,
|
||||
title = $1, content_en = $2, content_ru = $3, content_tm = $4, active = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING %s`, documentColumns)
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, dto.Status, id))
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, title, dto.ContentEn, dto.ContentRu, dto.ContentTm, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (loansdocument.LoanDocumentDTO, error) {
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_required_documents SET
|
||||
status = $1,
|
||||
active = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2
|
||||
RETURNING %s`, documentColumns)
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, status, id))
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
@@ -178,7 +180,7 @@ func scanLoanDocument(row scannable) (loansdocument.LoanDocumentDTO, error) {
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &titleJSON, &item.ContentEn, &item.ContentRu, &item.ContentTm,
|
||||
&item.Status, &item.CreatedAt, &item.UpdatedAt,
|
||||
&item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ type LoanDocumentDTO struct {
|
||||
ContentEn string `json:"contentEn"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
Status bool `json:"status"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
@@ -24,7 +24,7 @@ type CreateLoanDocumentDTO struct {
|
||||
ContentEn string `json:"contentEn" binding:"required"`
|
||||
ContentRu string `json:"contentRu" binding:"required"`
|
||||
ContentTm string `json:"contentTm" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentDTO struct {
|
||||
@@ -32,16 +32,16 @@ type UpdateLoanDocumentDTO struct {
|
||||
ContentEn string `json:"contentEn" binding:"required"`
|
||||
ContentRu string `json:"contentRu" binding:"required"`
|
||||
ContentTm string `json:"contentTm" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentStatusDTO struct {
|
||||
Status bool `json:"status"`
|
||||
type UpdateLoanDocumentActiveDTO struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
DocumentName string
|
||||
Status *bool
|
||||
Active *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.PUT("/:id/active", h.updateActive)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param document_name query string false "Filter by title (en, ru, tm)"
|
||||
// @Param status query bool false "Filter by status"
|
||||
// @Param active query bool false "Filter by active"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -169,40 +169,40 @@ func (h *handler) update(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// updateStatus godoc
|
||||
// @Summary Update loan document status
|
||||
// updateActive godoc
|
||||
// @Summary Update loan document active
|
||||
// @Description Enables or disables a loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Param body body UpdateLoanDocumentStatusDTO true "Status payload"
|
||||
// @Param body body UpdateLoanDocumentActiveDTO true "Active payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{id}/status [put]
|
||||
func (h *handler) updateStatus(c *gin.Context) {
|
||||
// @Router /loans-documents/{id}/active [put]
|
||||
func (h *handler) updateActive(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLoanDocumentStatusDTO
|
||||
var dto UpdateLoanDocumentActiveDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.UpdateStatus(c.Request.Context(), id, dto.Status)
|
||||
item, err := h.repository.UpdateActive(c.Request.Context(), id, dto.Active)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update loan document status failed: %v", err)
|
||||
h.logger.Errorf("update loan document active failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -281,12 +281,12 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.DocumentName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("status"); raw != "" {
|
||||
status, err := strconv.ParseBool(raw)
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Status = &status
|
||||
filter.Active = &active
|
||||
}
|
||||
|
||||
return filter, true
|
||||
|
||||
@@ -7,6 +7,6 @@ type Repository interface {
|
||||
GetByID(ctx context.Context, id int64) (LoanDocumentDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanDocumentDTO) (LoanDocumentDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanDocumentDTO) (LoanDocumentDTO, error)
|
||||
UpdateStatus(ctx context.Context, id int64, status bool) (LoanDocumentDTO, error)
|
||||
UpdateActive(ctx context.Context, id int64, active bool) (LoanDocumentDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Re
|
||||
|
||||
const loanTypeColumns = `lt.id, lt.title, lt.tax, lt.loan_term, lt.content, lt.created_at, lt.updated_at`
|
||||
|
||||
const loanTypeReturningColumns = `id, title, tax, loan_term, content, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
@@ -106,7 +108,7 @@ func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO)
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loan_types (title, tax, loan_term, content)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, loanTypeColumns)
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
return scanLoanType(r.client.QueryRow(ctx, query, title, dto.Tax, dto.LoanTerm, content))
|
||||
}
|
||||
@@ -122,7 +124,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLo
|
||||
title = $1, tax = $2, loan_term = $3, content = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
RETURNING %s`, loanTypeColumns)
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
item, err := scanLoanType(r.client.QueryRow(ctx, query, title, dto.Tax, dto.LoanTerm, content, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/admin/location"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) location.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter location.ListFilter) (location.ListLocationDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
countQuery := `SELECT COUNT(*) ` + fromClause + whereClause
|
||||
if err := r.client.QueryRow(ctx, countQuery, args...).Scan(&count); err != nil {
|
||||
return location.ListLocationDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
listQuery := fmt.Sprintf(
|
||||
`SELECT l.id, l.province_id, l.title, l.status%s%s ORDER BY l.id LIMIT $%d OFFSET $%d`,
|
||||
fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
listArgs := append(args, filter.Limit, offset)
|
||||
|
||||
rows, err := r.client.Query(ctx, listQuery, listArgs...)
|
||||
if err != nil {
|
||||
return location.ListLocationDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []location.LocationDTO
|
||||
for rows.Next() {
|
||||
item, err := scanLocation(rows)
|
||||
if err != nil {
|
||||
return location.ListLocationDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return location.ListLocationDTO{}, err
|
||||
}
|
||||
|
||||
return location.ListLocationDTO{
|
||||
Count: count,
|
||||
Locations: items,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter location.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
||||
fromClause = ` FROM location l`
|
||||
|
||||
if filter.ProvinceName != "" {
|
||||
fromClause += ` JOIN provinces p ON p.id = l.province_id`
|
||||
}
|
||||
|
||||
var conditions []string
|
||||
|
||||
if filter.ProvinceID != nil {
|
||||
args = append(args, *filter.ProvinceID)
|
||||
conditions = append(conditions, fmt.Sprintf("l.province_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.ProvinceName != "" {
|
||||
args = append(args, likePattern(filter.ProvinceName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
p.title->>'en' ILIKE $%[1]d OR p.title->>'ru' ILIKE $%[1]d OR p.title->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.LocationName != "" {
|
||||
args = append(args, likePattern(filter.LocationName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
l.title->>'en' ILIKE $%[1]d OR l.title->>'ru' ILIKE $%[1]d OR l.title->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("l.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return fromClause, "", args
|
||||
}
|
||||
|
||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (location.LocationDTO, error) {
|
||||
row := r.client.QueryRow(ctx,
|
||||
`SELECT id, province_id, title, status FROM location WHERE id = $1`, id,
|
||||
)
|
||||
item, err := scanLocation(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto location.CreateLocationDTO) (location.LocationDTO, error) {
|
||||
if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
|
||||
title, err := json.Marshal(dto.Title)
|
||||
if err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
|
||||
status := true
|
||||
if dto.Status != nil {
|
||||
status = *dto.Status
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`INSERT INTO location (province_id, title, status) VALUES ($1, $2, $3)
|
||||
RETURNING id, province_id, title, status`,
|
||||
dto.ProvinceId, title, status,
|
||||
)
|
||||
return scanLocation(row)
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto location.UpdateLocationDTO) (location.LocationDTO, error) {
|
||||
if err := r.ensureProvinceExists(ctx, dto.ProvinceId); err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
|
||||
title, err := json.Marshal(dto.Title)
|
||||
if err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE location SET province_id = $1, title = $2, status = $3
|
||||
WHERE id = $4
|
||||
RETURNING id, province_id, title, status`,
|
||||
dto.ProvinceId, title, dto.Status, id,
|
||||
)
|
||||
item, err := scanLocation(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (location.LocationDTO, error) {
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE location SET status = $1 WHERE id = $2
|
||||
RETURNING id, province_id, title, status`,
|
||||
status, id,
|
||||
)
|
||||
item, err := scanLocation(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
tag, err := r.client.Exec(ctx, `DELETE FROM location WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) ensureProvinceExists(ctx context.Context, provinceID int64) error {
|
||||
var id int64
|
||||
err := r.client.QueryRow(ctx, `SELECT id FROM provinces WHERE id = $1`, provinceID).Scan(&id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("province not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanLocation(row scannable) (location.LocationDTO, error) {
|
||||
var item location.LocationDTO
|
||||
var titleJSON []byte
|
||||
|
||||
if err := row.Scan(&item.Id, &item.ProvinceId, &titleJSON, &item.Status); err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
|
||||
return location.LocationDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package location
|
||||
|
||||
type LocalizedTitle struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type LocationDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
ProvinceId int64 `json:"provinceId"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type CreateLocationDTO struct {
|
||||
ProvinceId int64 `json:"provinceId" binding:"required"`
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
}
|
||||
|
||||
type UpdateLocationDTO struct {
|
||||
ProvinceId int64 `json:"provinceId" binding:"required"`
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type UpdateLocationStatusDTO struct {
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
ProvinceID *int64
|
||||
ProvinceName string
|
||||
LocationName string
|
||||
Status *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLocationDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Locations []LocationDTO `json:"locations"`
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
package location
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/locations"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List locations
|
||||
// @Description Returns paginated locations with optional filters
|
||||
// @Tags location
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param province_id query int false "Filter by province ID"
|
||||
// @Param province_name query string false "Filter by province name (en, ru, tm)"
|
||||
// @Param location_name query string false "Filter by location name (en, ru, tm)"
|
||||
// @Param status query bool false "Filter by location status"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list locations failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get location by ID
|
||||
// @Description Returns a single location
|
||||
// @Tags location
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Location ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get location failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create location
|
||||
// @Description Creates a new location in a province
|
||||
// @Tags location
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLocationDTO true "Location payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLocationDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
if err.Error() == "province not found" {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
h.logger.Errorf("create location failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update location
|
||||
// @Description Updates an existing location
|
||||
// @Tags location
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Location ID"
|
||||
// @Param body body UpdateLocationDTO true "Location payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLocationDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if err.Error() == "province not found" {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
h.logger.Errorf("update location failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// updateStatus godoc
|
||||
// @Summary Update location status
|
||||
// @Description Enables or disables a location
|
||||
// @Tags location
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Location ID"
|
||||
// @Param body body UpdateLocationStatusDTO true "Status payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations/{id}/status [put]
|
||||
func (h *handler) updateStatus(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateLocationStatusDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.UpdateStatus(c.Request.Context(), id, dto.Status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update location status failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete location
|
||||
// @Description Deletes a location
|
||||
// @Tags location
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Location ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /locations/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete location failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("location 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,
|
||||
}
|
||||
|
||||
if raw := c.Query("province_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.ProvinceID = &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("province_name")); raw != "" {
|
||||
filter.ProvinceName = raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("location_name")); raw != "" {
|
||||
filter.LocationName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("status"); raw != "" {
|
||||
status, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Status = &status
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package location
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLocationDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LocationDTO, error)
|
||||
Create(ctx context.Context, dto CreateLocationDTO) (LocationDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLocationDTO) (LocationDTO, error)
|
||||
UpdateStatus(ctx context.Context, id int64, status bool) (LocationDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -23,7 +23,9 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const cardColumns = `c.id, c.price, c.title, c.content, c.status`
|
||||
const cardColumns = `c.id, c.price, c.title, c.content, c.active`
|
||||
|
||||
const cardReturningColumns = `id, price, title, content, active`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
@@ -75,9 +77,9 @@ func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause stri
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("c.status = $%d", len(args)))
|
||||
if filter.Active != nil {
|
||||
args = append(args, *filter.Active)
|
||||
conditions = append(conditions, fmt.Sprintf("c.active = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
@@ -109,17 +111,17 @@ func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCa
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
status := true
|
||||
if dto.Status != nil {
|
||||
status = *dto.Status
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO payment_cards (price, title, content, status)
|
||||
INSERT INTO payment_cards (price, title, content, active)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, cardColumns)
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, status))
|
||||
return scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.UpdatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
||||
@@ -130,24 +132,24 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE payment_cards SET
|
||||
price = $1, title = $2, content = $3, status = $4
|
||||
price = $1, title = $2, content = $3, active = $4
|
||||
WHERE id = $5
|
||||
RETURNING %s`, cardColumns)
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, dto.Status, id))
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, title, content, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateStatus(ctx context.Context, id int64, status bool) (paymentcard.PaymentCardDTO, error) {
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE payment_cards SET status = $1
|
||||
UPDATE payment_cards SET active = $1
|
||||
WHERE id = $2
|
||||
RETURNING %s`, cardColumns)
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, status, id))
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
@@ -186,7 +188,7 @@ func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) {
|
||||
var titleJSON, contentJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Price, &titleJSON, &contentJSON, &item.Status,
|
||||
&item.Id, &item.Price, &titleJSON, &contentJSON, &item.Active,
|
||||
); err != nil {
|
||||
return paymentcard.PaymentCardDTO{}, err
|
||||
}
|
||||
|
||||
@@ -11,30 +11,30 @@ type PaymentCardDTO struct {
|
||||
Price float64 `json:"price"`
|
||||
Title LocalizedText `json:"title"`
|
||||
Content LocalizedText `json:"content"`
|
||||
Status bool `json:"status"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreatePaymentCardDTO struct {
|
||||
Price float64 `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Content LocalizedText `json:"content" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardDTO struct {
|
||||
Price float64 `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Content LocalizedText `json:"content" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardStatusDTO struct {
|
||||
Status bool `json:"status"`
|
||||
type UpdatePaymentCardActiveDTO struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
CardName string
|
||||
Status *bool
|
||||
Active *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.PUT("/:id/status", h.updateStatus)
|
||||
group.PUT("/:id/active", h.updateActive)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param card_name query string false "Filter by card title (en, ru, tm)"
|
||||
// @Param status query bool false "Filter by status"
|
||||
// @Param active query bool false "Filter by active"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
@@ -169,40 +169,40 @@ func (h *handler) update(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// updateStatus godoc
|
||||
// @Summary Update payment card status
|
||||
// updateActive godoc
|
||||
// @Summary Update payment card active
|
||||
// @Description Enables or disables a payment card
|
||||
// @Tags payment-card
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Payment card ID"
|
||||
// @Param body body UpdatePaymentCardStatusDTO true "Status payload"
|
||||
// @Param body body UpdatePaymentCardActiveDTO true "Active payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id}/status [put]
|
||||
func (h *handler) updateStatus(c *gin.Context) {
|
||||
// @Router /payment-cards/{id}/active [put]
|
||||
func (h *handler) updateActive(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdatePaymentCardStatusDTO
|
||||
var dto UpdatePaymentCardActiveDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.UpdateStatus(c.Request.Context(), id, dto.Status)
|
||||
item, err := h.repository.UpdateActive(c.Request.Context(), id, dto.Active)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update payment card status failed: %v", err)
|
||||
h.logger.Errorf("update payment card active failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
@@ -281,12 +281,12 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.CardName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("status"); raw != "" {
|
||||
status, err := strconv.ParseBool(raw)
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Status = &status
|
||||
filter.Active = &active
|
||||
}
|
||||
|
||||
return filter, true
|
||||
|
||||
@@ -7,6 +7,6 @@ type Repository interface {
|
||||
GetByID(ctx context.Context, id int64) (PaymentCardDTO, error)
|
||||
Create(ctx context.Context, dto CreatePaymentCardDTO) (PaymentCardDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePaymentCardDTO) (PaymentCardDTO, error)
|
||||
UpdateStatus(ctx context.Context, id int64, status bool) (PaymentCardDTO, error)
|
||||
UpdateActive(ctx context.Context, id int64, active bool) (PaymentCardDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
@@ -21,8 +21,10 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) province.Re
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
const provinceSelectColumns = `id, name, region, active`
|
||||
|
||||
func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
|
||||
rows, err := r.client.Query(ctx, `SELECT id, title, status FROM provinces ORDER BY id`)
|
||||
rows, err := r.client.Query(ctx, `SELECT `+provinceSelectColumns+` FROM provinces ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -41,7 +43,7 @@ func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
|
||||
row := r.client.QueryRow(ctx, `SELECT id, title, status FROM provinces WHERE id = $1`, id)
|
||||
row := r.client.QueryRow(ctx, `SELECT `+provinceSelectColumns+` FROM provinces WHERE id = $1`, id)
|
||||
item, err := scanProvince(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return province.ProvinceDTO{}, err
|
||||
@@ -50,32 +52,32 @@ func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDT
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) {
|
||||
title, err := json.Marshal(dto.Title)
|
||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
||||
if err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
|
||||
status := true
|
||||
if dto.Status != nil {
|
||||
status = *dto.Status
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`INSERT INTO provinces (title, status) VALUES ($1, $2) RETURNING id, title, status`,
|
||||
title, status,
|
||||
`INSERT INTO provinces (name, region, active) VALUES ($1, $2, $3) RETURNING `+provinceSelectColumns,
|
||||
name, region, active,
|
||||
)
|
||||
return scanProvince(row)
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto province.UpdateProvinceDTO) (province.ProvinceDTO, error) {
|
||||
title, err := json.Marshal(dto.Title)
|
||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
||||
if err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE provinces SET title = $1, status = $2 WHERE id = $3 RETURNING id, title, status`,
|
||||
title, dto.Status, id,
|
||||
`UPDATE provinces SET name = $1, region = $2, active = $3 WHERE id = $4 RETURNING `+provinceSelectColumns,
|
||||
name, region, dto.Active, id,
|
||||
)
|
||||
item, err := scanProvince(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -95,17 +97,32 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, error) {
|
||||
nameJSON, err := json.Marshal(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
regionJSON, err := json.Marshal(region)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nameJSON, regionJSON, nil
|
||||
}
|
||||
|
||||
type scannable interface {
|
||||
Scan(dest ...interface{}) error
|
||||
}
|
||||
|
||||
func scanProvince(row scannable) (province.ProvinceDTO, error) {
|
||||
var item province.ProvinceDTO
|
||||
var titleJSON []byte
|
||||
if err := row.Scan(&item.Id, &titleJSON, &item.Status); err != nil {
|
||||
var nameJSON, regionJSON []byte
|
||||
if err := row.Scan(&item.Id, &nameJSON, ®ionJSON, &item.Active); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(titleJSON, &item.Title); err != nil {
|
||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(regionJSON, &item.Region); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
package province
|
||||
|
||||
type LocalizedTitle struct {
|
||||
type LocalizedName struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProvinceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Status bool `json:"status"`
|
||||
Id int64 `json:"id"`
|
||||
Name LocalizedName `json:"name"`
|
||||
Region LocalizedName `json:"region"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreateProvinceDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status *bool `json:"status"`
|
||||
Name LocalizedName `json:"name" binding:"required"`
|
||||
Region LocalizedName `json:"region" binding:"required"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateProvinceDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Status bool `json:"status"`
|
||||
Name LocalizedName `json:"name" binding:"required"`
|
||||
Region LocalizedName `json:"region" binding:"required"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete province
|
||||
// @Description Deletes a province and its locations
|
||||
// @Description Deletes a province
|
||||
// @Tags province
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
|
||||
@@ -25,6 +25,8 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard
|
||||
|
||||
const reasonColumns = `r.id, r.title, r.price, r.content, r.created_at, r.updated_at`
|
||||
|
||||
const reasonReturningColumns = `id, title, price, content, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
|
||||
fromClause, whereClause, args := buildListQuery(filter)
|
||||
|
||||
@@ -106,7 +108,7 @@ func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCar
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO reasons_cards (title, price, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, reasonColumns)
|
||||
RETURNING %s`, reasonReturningColumns)
|
||||
|
||||
return scanReasonCard(r.client.QueryRow(ctx, query, title, dto.Price, content))
|
||||
}
|
||||
@@ -122,7 +124,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
||||
title = $1, price = $2, content = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, reasonColumns)
|
||||
RETURNING %s`, reasonReturningColumns)
|
||||
|
||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, title, dto.Price, content, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
|
||||
Reference in New Issue
Block a user