Add visa/master payment orders API and related names on loan paid letters.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
// Package cards groups payment cards, card orders, PIN orders, and their
|
||||
// reference data (reasons, payment card types) under one bounded context,
|
||||
// replacing the flat internal/admin/* listing.
|
||||
// Package cards groups payment cards, card orders, PIN orders, visa/master
|
||||
// payment orders, and their reference data (reasons, payment card types)
|
||||
// under one bounded context, replacing the flat internal/admin/* listing.
|
||||
package cards
|
||||
|
||||
import (
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
paymentcarddb "online-back/internal/cards/paymentcard/db"
|
||||
"online-back/internal/cards/reasonscard"
|
||||
reasonscarddb "online-back/internal/cards/reasonscard/db"
|
||||
"online-back/internal/cards/visamaster"
|
||||
visamasterdb "online-back/internal/cards/visamaster/db"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
@@ -35,5 +37,6 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
|
||||
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
|
||||
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
|
||||
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
|
||||
visamaster.NewHandler(logger, visamasterdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
|
||||
357
internal/cards/visamaster/db/postgresql.go
Normal file
357
internal/cards/visamaster/db/postgresql.go
Normal file
@@ -0,0 +1,357 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/visamaster"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[visamaster.VisaMasterPaymentOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) visamaster.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "visa_master_payment_orders", orderColumnsSQL, scanOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`
|
||||
|
||||
var orderWritableColumns = []string{
|
||||
"unique_id", "type", "passport_name", "passport_surname", "phone", "email",
|
||||
"region", "branch_id", "user_id", "address",
|
||||
"sender_datas", "payment_reciever", "documents",
|
||||
"status", "notes",
|
||||
"sender_full_name", "sender_passport_serie", "sender_passport_number", "sender_deposit_account",
|
||||
"reciever_full_name", "reciever_passport_serie", "reciever_passport_number", "reciever_deposit_account",
|
||||
"paid",
|
||||
}
|
||||
|
||||
var orderColumns = append(append([]string{"id"}, orderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
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, ", ")
|
||||
}
|
||||
|
||||
func resolveStatus(status *string) *string {
|
||||
if status == nil || strings.TrimSpace(*status) == "" {
|
||||
pending := "pending"
|
||||
return &pending
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func resolvePaid(paid *bool) bool {
|
||||
if paid == nil {
|
||||
return false
|
||||
}
|
||||
return *paid
|
||||
}
|
||||
|
||||
func jsonArg(raw json.RawMessage, fallback string) []byte {
|
||||
if len(raw) == 0 {
|
||||
return []byte(fallback)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func createArgs(dto visamaster.CreateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
|
||||
dto.Region, dto.BranchId, dto.UserId, dto.Address,
|
||||
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
resolvePaid(dto.Paid),
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto visamaster.UpdateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
|
||||
dto.Region, dto.BranchId, dto.UserId, dto.Address,
|
||||
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
dto.Paid,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (visamaster.ListVisaMasterPaymentOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM visa_master_payment_orders o`+whereClause, args...).Scan(&count); err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY o.id DESC LIMIT $%d OFFSET $%d`,
|
||||
orderSelectColumns, orderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []visamaster.VisaMasterPaymentOrderDTO
|
||||
for rows.Next() {
|
||||
item, err := scanOrder(rows)
|
||||
if err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{Count: count, VisaMasterPaymentOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Name != "" {
|
||||
args = append(args, likePattern(filter.Name))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d
|
||||
OR o.sender_full_name ILIKE $%[1]d OR COALESCE(o.reciever_full_name, '') ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("o.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("o.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " 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) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (visamaster.ListBranchesByProvinceDTO, error) {
|
||||
args := []interface{}{provinceID}
|
||||
where := ` WHERE province_id = $1`
|
||||
if activeOnly {
|
||||
where += ` AND active = true`
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT id, COALESCE(unique_code, ''), name, region, province_id, active
|
||||
FROM branches` + where + `
|
||||
ORDER BY name->>'tm', name->>'en', id`
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
branches := make([]visamaster.BranchByProvinceDTO, 0)
|
||||
for rows.Next() {
|
||||
var item visamaster.BranchByProvinceDTO
|
||||
var nameJSON []byte
|
||||
if err := rows.Scan(&item.Id, &item.UniqueCode, &nameJSON, &item.Region, &item.ProvinceId, &item.Active); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
branches = append(branches, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return visamaster.ListBranchesByProvinceDTO{}, err
|
||||
}
|
||||
|
||||
return visamaster.ListBranchesByProvinceDTO{
|
||||
Count: int64(len(branches)),
|
||||
Branches: branches,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1`
|
||||
return scanOrder(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto visamaster.CreateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO visa_master_payment_orders (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN users u ON u.id = o.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
orderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
orderColumnsSQL, orderSelectColumns,
|
||||
)
|
||||
|
||||
return scanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto visamaster.UpdateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(orderWritableColumns))
|
||||
for i, column := range orderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN users u ON u.id = o.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
strings.Join(assignments, ", "), len(args), orderColumnsSQL, orderSelectColumns,
|
||||
)
|
||||
|
||||
item, err := scanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
var item visamaster.VisaMasterPaymentOrderDTO
|
||||
var senderDatas, paymentReciever, documents []byte
|
||||
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
var branchRegion, userName, userUsername, userPhone, userEmail string
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Type, &item.PassportName, &item.PassportSurname, &item.Phone, &item.Email,
|
||||
&item.Region, &item.BranchId, &item.UserId, &item.Address,
|
||||
&senderDatas, &paymentReciever, &documents,
|
||||
&item.Status, &item.Notes,
|
||||
&item.SenderFullName, &item.SenderPassportSerie, &item.SenderPassportNumber, &item.SenderDepositAccount,
|
||||
&item.RecieverFullName, &item.RecieverPassportSerie, &item.RecieverPassportNumber, &item.RecieverDepositAccount,
|
||||
&item.Paid, &item.CreatedAt, &item.UpdatedAt,
|
||||
®ionNameJSON, &branchNameJSON, &item.Branch.UniqueCode, &branchRegion, &item.Branch.ProvinceId, &provinceNameJSON,
|
||||
&userName, &userUsername, &userPhone, &userEmail,
|
||||
)
|
||||
if err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
item.SenderDatas = jsonOrDefault(senderDatas, `{}`)
|
||||
item.PaymentReciever = jsonOrDefault(paymentReciever, `[]`)
|
||||
item.Documents = jsonOrDefault(documents, `{}`)
|
||||
|
||||
item.Branch.Id = item.BranchId
|
||||
item.Branch.Region = branchRegion
|
||||
if err := unmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
if err := unmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
if err := unmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
if item.UserId != nil {
|
||||
item.User = &visamaster.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func jsonOrDefault(raw []byte, fallback string) json.RawMessage {
|
||||
if len(raw) == 0 {
|
||||
return json.RawMessage(fallback)
|
||||
}
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
func unmarshalLocalized(raw []byte, dest *visamaster.LocalizedText) error {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(raw, dest)
|
||||
}
|
||||
86
internal/cards/visamaster/db/postgresql_get_test.go
Normal file
86
internal/cards/visamaster/db/postgresql_get_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/internal/cards/visamaster"
|
||||
"online-back/internal/config"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
func testRepo(t *testing.T) (visamaster.Repository, func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
|
||||
Host: "localhost",
|
||||
Port: "5424",
|
||||
Database: "bank_db",
|
||||
Username: "bank_admin",
|
||||
Password: "bank@#23#@_password",
|
||||
PgPoolMaxConn: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
|
||||
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
|
||||
}
|
||||
|
||||
func TestGetByIDIncludesBranchAndUser(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
ctx := context.Background()
|
||||
|
||||
item, err := repo.GetByID(ctx, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID: %v", err)
|
||||
}
|
||||
|
||||
if item.BranchId == 0 {
|
||||
t.Fatal("branchId is empty")
|
||||
}
|
||||
if item.Branch.Id != item.BranchId {
|
||||
t.Fatalf("branch.id=%d does not match branchId=%d", item.Branch.Id, item.BranchId)
|
||||
}
|
||||
if item.Branch.Name.Tm == "" && item.Branch.Name.En == "" {
|
||||
t.Fatalf("branchId=%d but branch.name is empty: %+v", item.BranchId, item.Branch.Name)
|
||||
}
|
||||
if item.UserId != nil {
|
||||
if item.User == nil {
|
||||
t.Fatalf("userId=%d but user object is nil", *item.UserId)
|
||||
}
|
||||
if item.User.Name == "" && item.User.Username == "" {
|
||||
t.Fatalf("userId=%d but user name/username are empty", *item.UserId)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("id=%d branchId=%d branch=%q userId=%v user=%v",
|
||||
item.Id, item.BranchId, item.Branch.Name.Tm, item.UserId, item.User)
|
||||
}
|
||||
|
||||
func TestListIncludesBranchAndUser(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
|
||||
list, err := repo.List(context.Background(), visamaster.ListFilter{Page: 1, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if list.Count == 0 || len(list.VisaMasterPaymentOrders) == 0 {
|
||||
t.Fatal("List returned no orders")
|
||||
}
|
||||
|
||||
for _, item := range list.VisaMasterPaymentOrders {
|
||||
if item.BranchId != 0 && item.Branch.Name.Tm == "" && item.Branch.Name.En == "" {
|
||||
t.Errorf("order %d branchId=%d missing branch.name", item.Id, item.BranchId)
|
||||
}
|
||||
if item.UserId != nil && (item.User == nil || (item.User.Name == "" && item.User.Username == "")) {
|
||||
t.Errorf("order %d userId=%d missing user details", item.Id, *item.UserId)
|
||||
}
|
||||
}
|
||||
}
|
||||
145
internal/cards/visamaster/dto.go
Normal file
145
internal/cards/visamaster/dto.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package visamaster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type CreateVisaMasterPaymentOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
PassportName string `json:"passportName" binding:"required"`
|
||||
PassportSurname string `json:"passportSurname" binding:"required"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
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" binding:"required"`
|
||||
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
|
||||
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
|
||||
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
|
||||
RecieverFullName *string `json:"recieverFullName"`
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
type UpdateVisaMasterPaymentOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
PassportName string `json:"passportName" binding:"required"`
|
||||
PassportSurname string `json:"passportSurname" binding:"required"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
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" binding:"required"`
|
||||
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
|
||||
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
|
||||
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
|
||||
RecieverFullName *string `json:"recieverFullName"`
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Name string
|
||||
Status *string
|
||||
BranchId *int64
|
||||
UserId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListVisaMasterPaymentOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
VisaMasterPaymentOrders []VisaMasterPaymentOrderDTO `json:"visaMasterPaymentOrders"`
|
||||
}
|
||||
|
||||
type BranchByProvinceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
Region string `json:"region"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListBranchesByProvinceDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Branches []BranchByProvinceDTO `json:"branches"`
|
||||
}
|
||||
310
internal/cards/visamaster/handler.go
Normal file
310
internal/cards/visamaster/handler.go
Normal file
@@ -0,0 +1,310 @@
|
||||
package visamaster
|
||||
|
||||
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 = "/visa-master-payment-orders"
|
||||
|
||||
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("/branches", h.listBranchesByProvince)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List visa/master payment orders
|
||||
// @Description Returns paginated visa/master payment orders with branch and user details
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param name query string false "Filter by passport name or surname"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @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 /visa-master-payment-orders [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 visa master payment orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// listBranchesByProvince godoc
|
||||
// @Summary List branches by province
|
||||
// @Description Returns branches for the selected province for visa/master payment order forms
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param province_id query int true "Province ID"
|
||||
// @Param active query bool false "Only active branches" default(true)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/branches [get]
|
||||
func (h *handler) listBranchesByProvince(c *gin.Context) {
|
||||
provinceID, ok := parseID(c.Query("province_id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
activeOnly := true
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
activeOnly = active
|
||||
}
|
||||
|
||||
result, err := h.repository.ListBranchesByProvince(c.Request.Context(), provinceID, activeOnly)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list branches by province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get visa/master payment order by ID
|
||||
// @Description Returns a single visa/master payment order with branch and user details
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @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"))
|
||||
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 visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create visa/master payment order
|
||||
// @Description Creates a new visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateVisaMasterPaymentOrderDTO
|
||||
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 {
|
||||
h.logger.Errorf("create visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update visa/master payment order
|
||||
// @Description Updates an existing visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Param body body UpdateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @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"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateVisaMasterPaymentOrderDTO
|
||||
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 {
|
||||
h.logger.Errorf("update visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete visa/master payment order
|
||||
// @Description Deletes a visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @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"))
|
||||
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 visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
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 != "" {
|
||||
filter.Name = raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("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 raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
12
internal/cards/visamaster/storage.go
Normal file
12
internal/cards/visamaster/storage.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package visamaster
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListVisaMasterPaymentOrderDTO, error)
|
||||
ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (ListBranchesByProvinceDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (VisaMasterPaymentOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -30,7 +30,8 @@ const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last
|
||||
|
||||
const letterFromClause = ` FROM loan_paid_off_letters l
|
||||
LEFT JOIN branches b ON b.id = l.branch_id
|
||||
LEFT JOIN users u ON u.id = l.user_id`
|
||||
LEFT JOIN users u ON u.id = l.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`
|
||||
|
||||
// letterWritableColumns lists every loan_paid_off_letters column except id, created_at
|
||||
// and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read.
|
||||
@@ -48,7 +49,7 @@ var letterColumnsSQL = strings.Join(letterColumns, ", ")
|
||||
|
||||
var letterWritableColumnsSQL = strings.Join(letterWritableColumns, ", ")
|
||||
|
||||
var letterSelectColumns = prefixedColumns("l", letterColumns) + `, b.name, ` + userDisplaySQL
|
||||
var letterSelectColumns = prefixedColumns("l", letterColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), b.province_id, p.name, ` + userDisplaySQL + `, COALESCE(u.username, '')`
|
||||
|
||||
func prefixedColumns(alias string, cols []string) string {
|
||||
parts := make([]string, len(cols))
|
||||
@@ -221,7 +222,8 @@ func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPa
|
||||
SELECT %s
|
||||
FROM inserted l
|
||||
LEFT JOIN branches b ON b.id = l.branch_id
|
||||
LEFT JOIN users u ON u.id = l.user_id`,
|
||||
LEFT JOIN users u ON u.id = l.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
letterWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
letterColumnsSQL, letterSelectColumns,
|
||||
)
|
||||
@@ -247,7 +249,8 @@ func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.Up
|
||||
SELECT %s
|
||||
FROM updated l
|
||||
LEFT JOIN branches b ON b.id = l.branch_id
|
||||
LEFT JOIN users u ON u.id = l.user_id`,
|
||||
LEFT JOIN users u ON u.id = l.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
strings.Join(assignments, ", "), len(args), letterColumnsSQL, letterSelectColumns,
|
||||
)
|
||||
|
||||
@@ -264,7 +267,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
|
||||
func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
var item loanpaidletter.LoanPaidLetterDTO
|
||||
var branchNameJSON []byte
|
||||
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId,
|
||||
@@ -273,15 +276,27 @@ func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterD
|
||||
&item.Status, &item.Notes, &item.LoanContractNumber, &item.LoanContractDate,
|
||||
&item.LoanAmount, &item.LoanReason, &item.LoanFile,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
&branchNameJSON, &item.UserName,
|
||||
®ionNameJSON, &branchNameJSON, &item.BranchUniqueCode, &item.ProvinceId, &provinceNameJSON,
|
||||
&item.UserName, &item.UserUsername,
|
||||
)
|
||||
if err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
if len(branchNameJSON) > 0 {
|
||||
if err := json.Unmarshal(branchNameJSON, &item.BranchName); err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
if err := unmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
if err := unmarshalLocalized(branchNameJSON, &item.BranchName); err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
if err := unmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func unmarshalLocalized(raw []byte, dest *loanpaidletter.LocalizedText) error {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(raw, dest)
|
||||
}
|
||||
|
||||
93
internal/lending/loanpaidletter/db/postgresql_get_test.go
Normal file
93
internal/lending/loanpaidletter/db/postgresql_get_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
func testRepo(t *testing.T) (loanpaidletter.Repository, func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
pool, err := postgresql.NewClient(ctx, 2, config.StorageConfig{
|
||||
Host: "localhost",
|
||||
Port: "5424",
|
||||
Database: "bank_db",
|
||||
Username: "bank_admin",
|
||||
Password: "bank@#23#@_password",
|
||||
PgPoolMaxConn: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
|
||||
return NewRepository(pool, logging.GetLogger()), func() { pool.Close() }
|
||||
}
|
||||
|
||||
func TestGetByIDIncludesNamesNextToIDs(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
ctx := context.Background()
|
||||
|
||||
item, err := repo.GetByID(ctx, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByID: %v", err)
|
||||
}
|
||||
|
||||
if item.BranchId == 0 {
|
||||
t.Fatal("branchId is empty")
|
||||
}
|
||||
if item.BranchName.Tm == "" && item.BranchName.En == "" {
|
||||
t.Fatalf("branchId=%d but branchName is empty: %+v", item.BranchId, item.BranchName)
|
||||
}
|
||||
if item.BranchUniqueCode == "" {
|
||||
t.Fatalf("branchId=%d but branchUniqueCode is empty", item.BranchId)
|
||||
}
|
||||
if item.ProvinceId == nil || *item.ProvinceId == 0 {
|
||||
t.Fatal("provinceId is empty")
|
||||
}
|
||||
if item.ProvinceName.Tm == "" && item.ProvinceName.En == "" {
|
||||
t.Fatalf("provinceId=%d but provinceName is empty: %+v", *item.ProvinceId, item.ProvinceName)
|
||||
}
|
||||
if item.RegionName.Tm == "" && item.RegionName.En == "" {
|
||||
t.Fatalf("region=%q but regionName is empty: %+v", item.Region, item.RegionName)
|
||||
}
|
||||
if item.UserId != nil {
|
||||
if item.UserName == "" && item.UserUsername == "" {
|
||||
t.Fatalf("userId=%d but userName and userUsername are empty", *item.UserId)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("id=%d branchId=%d branch=%q/%s provinceId=%d province=%q userId=%v user=%q",
|
||||
item.Id, item.BranchId, item.BranchName.Tm, item.BranchUniqueCode,
|
||||
*item.ProvinceId, item.ProvinceName.Tm, item.UserId, item.UserName)
|
||||
}
|
||||
|
||||
func TestListIncludesNamesNextToIDs(t *testing.T) {
|
||||
repo, closeRepo := testRepo(t)
|
||||
defer closeRepo()
|
||||
|
||||
list, err := repo.List(context.Background(), loanpaidletter.ListFilter{Page: 1, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("List: %v", err)
|
||||
}
|
||||
if list.Count == 0 || len(list.LoanPaidLetters) == 0 {
|
||||
t.Fatal("List returned no letters")
|
||||
}
|
||||
|
||||
for _, item := range list.LoanPaidLetters {
|
||||
if item.BranchId != 0 && item.BranchName.Tm == "" && item.BranchName.En == "" {
|
||||
t.Errorf("letter %d branchId=%d missing branchName", item.Id, item.BranchId)
|
||||
}
|
||||
if item.UserId != nil && item.UserName == "" && item.UserUsername == "" {
|
||||
t.Errorf("letter %d userId=%d missing userName", item.Id, *item.UserId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,15 @@ type LoanPaidLetterDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region"`
|
||||
RegionName LocalizedText `json:"regionName"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
BranchName LocalizedText `json:"branchName"`
|
||||
BranchUniqueCode string `json:"branchUniqueCode"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
ProvinceName LocalizedText `json:"provinceName"`
|
||||
UserId *int64 `json:"userId"`
|
||||
UserName string `json:"userName"`
|
||||
UserUsername string `json:"userUsername"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
|
||||
Reference in New Issue
Block a user