changed arhitecture
This commit is contained in:
214
internal/lending/loanorders/db/postgresql.go
Normal file
214
internal/lending/loanorders/db/postgresql.go
Normal file
@@ -0,0 +1,214 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loanorders"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loanorders.LoanOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loanorders.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_orders", loanOrderColumnsSQL, scanLoanOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// loanOrderWritableColumns lists every loan_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateLoanOrderDTO/UpdateLoanOrderDTO fields are read.
|
||||
var loanOrderWritableColumns = []string{
|
||||
"unique_id", "source", "user_id", "loan_type", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name",
|
||||
"passport_address", "real_address", "passport_serie", "passport_id", "passport_given_at", "passport_given_by",
|
||||
"born_place", "born_at", "email", "phone", "phone_additional", "phone_home",
|
||||
"work_region", "work_province_id", "work_company", "work_company_accountant_number", "work_started_at",
|
||||
"work_salary", "work_position", "education", "marriage_status",
|
||||
"passport_one", "passport_two", "passport_three", "passport_four",
|
||||
"loan_amount", "card_number", "card_name", "card_month", "card_year",
|
||||
"guarantor_name", "guarantor_surname", "guarantor_patronic_name", "guarantor_passport_serie", "guarantor_passport_id",
|
||||
"guarantor_card_number", "guarantor_card_name", "guarantor_card_month", "guarantor_card_year", "guarantor_note",
|
||||
"guarantor_2_name", "guarantor_2_surname", "guarantor_2_patronic_name", "guarantor_2_passport_serie", "guarantor_2_passport_id",
|
||||
"guarantor_2_card_number", "guarantor_2_card_name", "guarantor_2_card_month", "guarantor_2_card_year", "guarantor_2_note",
|
||||
"loan_card_number", "loan_card_name", "loan_card_month", "loan_card_year",
|
||||
"loan_order_required_doc_id", "status", "satisfiable", "notes",
|
||||
}
|
||||
|
||||
var loanOrderColumns = append(append([]string{"id"}, loanOrderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var loanOrderColumnsSQL = strings.Join(loanOrderColumns, ", ")
|
||||
|
||||
var loanOrderWritableColumnsSQL = strings.Join(loanOrderWritableColumns, ", ")
|
||||
|
||||
func resolveSource(source string) string {
|
||||
source = strings.TrimSpace(source)
|
||||
if source == "" {
|
||||
return "web"
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), dto.UserId, dto.LoanType, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt, dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
dto.WorkRegion, dto.WorkProvinceId, dto.WorkCompany, dto.WorkCompanyAccountantNumber, dto.WorkStartedAt,
|
||||
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
|
||||
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
|
||||
dto.GuarantorName, dto.GuarantorSurname, dto.GuarantorPatronicName, dto.GuarantorPassportSerie, dto.GuarantorPassportId,
|
||||
dto.GuarantorCardNumber, dto.GuarantorCardName, dto.GuarantorCardMonth, dto.GuarantorCardYear, dto.GuarantorNote,
|
||||
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
|
||||
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
|
||||
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
|
||||
dto.LoanOrderRequiredDocId, dto.Status, dto.Satisfiable, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, resolveSource(dto.Source), dto.UserId, dto.LoanType, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName,
|
||||
dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy,
|
||||
dto.BornPlace, dto.BornAt, dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome,
|
||||
dto.WorkRegion, dto.WorkProvinceId, dto.WorkCompany, dto.WorkCompanyAccountantNumber, dto.WorkStartedAt,
|
||||
dto.WorkSalary, dto.WorkPosition, dto.Education, dto.MarriageStatus,
|
||||
dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.LoanAmount, dto.CardNumber, dto.CardName, dto.CardMonth, dto.CardYear,
|
||||
dto.GuarantorName, dto.GuarantorSurname, dto.GuarantorPatronicName, dto.GuarantorPassportSerie, dto.GuarantorPassportId,
|
||||
dto.GuarantorCardNumber, dto.GuarantorCardName, dto.GuarantorCardMonth, dto.GuarantorCardYear, dto.GuarantorNote,
|
||||
dto.Guarantor2Name, dto.Guarantor2Surname, dto.Guarantor2PatronicName, dto.Guarantor2PassportSerie, dto.Guarantor2PassportId,
|
||||
dto.Guarantor2CardNumber, dto.Guarantor2CardName, dto.Guarantor2CardMonth, dto.Guarantor2CardYear, dto.Guarantor2Note,
|
||||
dto.LoanCardNumber, dto.LoanCardName, dto.LoanCardMonth, dto.LoanCardYear,
|
||||
dto.LoanOrderRequiredDocId, dto.Status, dto.Satisfiable, dto.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loanorders.ListFilter) (loanorders.ListLoanOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
if err != nil {
|
||||
return loanorders.ListLoanOrderDTO{}, err
|
||||
}
|
||||
|
||||
return loanorders.ListLoanOrderDTO{Count: count, LoanOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
// nextUniqueIDSQL computes unique_id as the last value stored in loan_orders plus
|
||||
// one, zero-padded to 4 digits, mirroring a serial/auto-increment column.
|
||||
const nextUniqueIDSQL = `(SELECT LPAD((COALESCE(MAX(unique_id::bigint), 0) + 1)::text, 4, '0') FROM loan_orders)`
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
// unique_id is supplied positionally via nextUniqueIDSQL below, so drop it
|
||||
// from the bound args to avoid double-supplying the first column.
|
||||
args := createArgs(dto)[1:]
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO loan_orders (%s) VALUES (%s, %s) RETURNING %s`,
|
||||
loanOrderWritableColumnsSQL, nextUniqueIDSQL, strings.Join(placeholders, ", "), loanOrderColumnsSQL,
|
||||
)
|
||||
|
||||
return scanLoanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loanorders.UpdateLoanOrderDTO) (loanorders.LoanOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(loanOrderWritableColumns))
|
||||
for i, column := range loanOrderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE loan_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), loanOrderColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanLoanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return loanorders.LoanOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanOrder(row genericrepo.Scanner) (loanorders.LoanOrderDTO, error) {
|
||||
var item loanorders.LoanOrderDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Source, &item.UserId, &item.LoanType, &item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName,
|
||||
&item.PassportAddress, &item.RealAddress, &item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy,
|
||||
&item.BornPlace, &item.BornAt, &item.Email, &item.Phone, &item.PhoneAdditional, &item.PhoneHome,
|
||||
&item.WorkRegion, &item.WorkProvinceId, &item.WorkCompany, &item.WorkCompanyAccountantNumber, &item.WorkStartedAt,
|
||||
&item.WorkSalary, &item.WorkPosition, &item.Education, &item.MarriageStatus,
|
||||
&item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
|
||||
&item.LoanAmount, &item.CardNumber, &item.CardName, &item.CardMonth, &item.CardYear,
|
||||
&item.GuarantorName, &item.GuarantorSurname, &item.GuarantorPatronicName, &item.GuarantorPassportSerie, &item.GuarantorPassportId,
|
||||
&item.GuarantorCardNumber, &item.GuarantorCardName, &item.GuarantorCardMonth, &item.GuarantorCardYear, &item.GuarantorNote,
|
||||
&item.Guarantor2Name, &item.Guarantor2Surname, &item.Guarantor2PatronicName, &item.Guarantor2PassportSerie, &item.Guarantor2PassportId,
|
||||
&item.Guarantor2CardNumber, &item.Guarantor2CardName, &item.Guarantor2CardMonth, &item.Guarantor2CardYear, &item.Guarantor2Note,
|
||||
&item.LoanCardNumber, &item.LoanCardName, &item.LoanCardMonth, &item.LoanCardYear,
|
||||
&item.LoanOrderRequiredDocId, &item.Status, &item.Satisfiable, &item.Notes,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return loanorders.LoanOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
230
internal/lending/loanorders/dto.go
Normal file
230
internal/lending/loanorders/dto.go
Normal file
@@ -0,0 +1,230 @@
|
||||
package loanorders
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
LoanType int64 `json:"loanType"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
PassportAddress string `json:"passportAddress"`
|
||||
RealAddress string `json:"realAddress"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt"`
|
||||
PassportGivenBy string `json:"passportGivenBy"`
|
||||
BornPlace string `json:"bornPlace"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education"`
|
||||
MarriageStatus string `json:"marriageStatus"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanOrderDTO struct {
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
LoanType int64 `json:"loanType" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
PassportAddress string `json:"passportAddress" binding:"required"`
|
||||
RealAddress string `json:"realAddress" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
BornAt time.Time `json:"bornAt" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education" binding:"required"`
|
||||
MarriageStatus string `json:"marriageStatus" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type UpdateLoanOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Source string `json:"source"`
|
||||
UserId *int64 `json:"userId"`
|
||||
LoanType int64 `json:"loanType" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
PassportAddress string `json:"passportAddress" binding:"required"`
|
||||
RealAddress string `json:"realAddress" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
BornAt time.Time `json:"bornAt" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
PhoneHome *string `json:"phoneHome"`
|
||||
WorkRegion *string `json:"workRegion"`
|
||||
WorkProvinceId *int64 `json:"workProvinceId"`
|
||||
WorkCompany *string `json:"workCompany"`
|
||||
WorkCompanyAccountantNumber *string `json:"workCompanyAccountantNumber"`
|
||||
WorkStartedAt *time.Time `json:"workStartedAt"`
|
||||
WorkSalary *string `json:"workSalary"`
|
||||
WorkPosition *string `json:"workPosition"`
|
||||
Education string `json:"education" binding:"required"`
|
||||
MarriageStatus string `json:"marriageStatus" binding:"required"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CardName *string `json:"cardName"`
|
||||
CardMonth *string `json:"cardMonth"`
|
||||
CardYear *string `json:"cardYear"`
|
||||
GuarantorName *string `json:"guarantorName"`
|
||||
GuarantorSurname *string `json:"guarantorSurname"`
|
||||
GuarantorPatronicName *string `json:"guarantorPatronicName"`
|
||||
GuarantorPassportSerie *string `json:"guarantorPassportSerie"`
|
||||
GuarantorPassportId *string `json:"guarantorPassportId"`
|
||||
GuarantorCardNumber *string `json:"guarantorCardNumber"`
|
||||
GuarantorCardName *string `json:"guarantorCardName"`
|
||||
GuarantorCardMonth *string `json:"guarantorCardMonth"`
|
||||
GuarantorCardYear *string `json:"guarantorCardYear"`
|
||||
GuarantorNote *string `json:"guarantorNote"`
|
||||
Guarantor2Name *string `json:"guarantor2Name"`
|
||||
Guarantor2Surname *string `json:"guarantor2Surname"`
|
||||
Guarantor2PatronicName *string `json:"guarantor2PatronicName"`
|
||||
Guarantor2PassportSerie *string `json:"guarantor2PassportSerie"`
|
||||
Guarantor2PassportId *string `json:"guarantor2PassportId"`
|
||||
Guarantor2CardNumber *string `json:"guarantor2CardNumber"`
|
||||
Guarantor2CardName *string `json:"guarantor2CardName"`
|
||||
Guarantor2CardMonth *string `json:"guarantor2CardMonth"`
|
||||
Guarantor2CardYear *string `json:"guarantor2CardYear"`
|
||||
Guarantor2Note *string `json:"guarantor2Note"`
|
||||
LoanCardNumber *string `json:"loanCardNumber"`
|
||||
LoanCardName *string `json:"loanCardName"`
|
||||
LoanCardMonth *string `json:"loanCardMonth"`
|
||||
LoanCardYear *string `json:"loanCardYear"`
|
||||
LoanOrderRequiredDocId *int64 `json:"loanOrderRequiredDocId"`
|
||||
Status *string `json:"status"`
|
||||
Satisfiable *string `json:"satisfiable"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
UserId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanOrders []LoanOrderDTO `json:"loanOrders"`
|
||||
}
|
||||
265
internal/lending/loanorders/handler.go
Normal file
265
internal/lending/loanorders/handler.go
Normal file
@@ -0,0 +1,265 @@
|
||||
package loanorders
|
||||
|
||||
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 = "/loan-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("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan orders
|
||||
// @Description Returns paginated loan orders with optional filters
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @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 /loan-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 loan orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan order by ID
|
||||
// @Description Returns a single loan order
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-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 loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan order
|
||||
// @Description Creates a new loan order
|
||||
// @Tags loan-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanOrderDTO true "Loan order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanOrderDTO
|
||||
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 loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan order
|
||||
// @Description Updates an existing loan order
|
||||
// @Tags loan-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Param body body UpdateLoanOrderDTO true "Loan order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-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 UpdateLoanOrderDTO
|
||||
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 loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan order
|
||||
// @Description Deletes a loan order
|
||||
// @Tags loan-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-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 loan order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan 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("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
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/lending/loanorders/storage.go
Normal file
11
internal/lending/loanorders/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package loanorders
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanOrderDTO) (LoanOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanOrderDTO) (LoanOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
171
internal/lending/loanpaidletter/db/postgresql.go
Normal file
171
internal/lending/loanpaidletter/db/postgresql.go
Normal file
@@ -0,0 +1,171 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loanpaidletter.LoanPaidLetterDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loanpaidletter.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_paid_off_letters", letterColumnsSQL, scanLoanPaidLetter),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// letterWritableColumns lists every loan_paid_off_letters column except id, created_at
|
||||
// and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read.
|
||||
var letterWritableColumns = []string{
|
||||
"unique_id", "region", "branch_id", "user_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at",
|
||||
"phone", "passport_serie", "passport_id",
|
||||
"status", "notes", "loan_contract_number", "loan_contract_date",
|
||||
"loan_amount", "loan_reason", "loan_file",
|
||||
}
|
||||
|
||||
var letterColumns = append(append([]string{"id"}, letterWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var letterColumnsSQL = strings.Join(letterColumns, ", ")
|
||||
|
||||
var letterWritableColumnsSQL = strings.Join(letterWritableColumns, ", ")
|
||||
|
||||
func createArgs(dto loanpaidletter.CreateLoanPaidLetterDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
|
||||
dto.Phone, dto.PassportSerie, dto.PassportId,
|
||||
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
|
||||
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto loanpaidletter.UpdateLoanPaidLetterDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Region, dto.BranchId, dto.UserId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt,
|
||||
dto.Phone, dto.PassportSerie, dto.PassportId,
|
||||
dto.Status, dto.Notes, dto.LoanContractNumber, dto.LoanContractDate,
|
||||
dto.LoanAmount, dto.LoanReason, dto.LoanFile,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loanpaidletter.ListFilter) (loanpaidletter.ListLoanPaidLetterDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
if err != nil {
|
||||
return loanpaidletter.ListLoanPaidLetterDTO{}, err
|
||||
}
|
||||
|
||||
return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, likePattern(filter.PassportId))
|
||||
conditions = append(conditions, fmt.Sprintf("passport_id ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("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) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loanpaidletter.CreateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO loan_paid_off_letters (%s) VALUES (%s) RETURNING %s`,
|
||||
letterWritableColumnsSQL, strings.Join(placeholders, ", "), letterColumnsSQL,
|
||||
)
|
||||
|
||||
return scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loanpaidletter.UpdateLoanPaidLetterDTO) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(letterWritableColumns))
|
||||
for i, column := range letterWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE loan_paid_off_letters SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), letterColumnsSQL,
|
||||
)
|
||||
|
||||
item, err := scanLoanPaidLetter(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanPaidLetter(row genericrepo.Scanner) (loanpaidletter.LoanPaidLetterDTO, error) {
|
||||
var item loanpaidletter.LoanPaidLetterDTO
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Region, &item.BranchId, &item.UserId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt,
|
||||
&item.Phone, &item.PassportSerie, &item.PassportId,
|
||||
&item.Status, &item.Notes, &item.LoanContractNumber, &item.LoanContractDate,
|
||||
&item.LoanAmount, &item.LoanReason, &item.LoanFile,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return loanpaidletter.LoanPaidLetterDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
83
internal/lending/loanpaidletter/dto.go
Normal file
83
internal/lending/loanpaidletter/dto.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package loanpaidletter
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanPaidLetterDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanPaidLetterDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
}
|
||||
|
||||
type UpdateLoanPaidLetterDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
LoanContractNumber *string `json:"loanContractNumber"`
|
||||
LoanContractDate *time.Time `json:"loanContractDate"`
|
||||
LoanAmount *string `json:"loanAmount"`
|
||||
LoanReason *string `json:"loanReason"`
|
||||
LoanFile *string `json:"loanFile"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PassportId string
|
||||
Status *string
|
||||
BranchId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanPaidLetterDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanPaidLetters []LoanPaidLetterDTO `json:"loanPaidLetters"`
|
||||
}
|
||||
261
internal/lending/loanpaidletter/handler.go
Normal file
261
internal/lending/loanpaidletter/handler.go
Normal file
@@ -0,0 +1,261 @@
|
||||
package loanpaidletter
|
||||
|
||||
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 = "/loan-paid-off-letters"
|
||||
|
||||
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.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan paid off letters
|
||||
// @Description Returns paginated loan paid off letters with optional filters
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param passport_id query string false "Filter by passport ID"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch 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 /loan-paid-off-letters [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 loan paid off letters failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan paid off letter by ID
|
||||
// @Description Returns a single loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{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 loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan paid off letter
|
||||
// @Description Creates a new loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanPaidLetterDTO true "Loan paid off letter payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanPaidLetterDTO
|
||||
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 loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan paid off letter
|
||||
// @Description Updates an existing loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Param body body UpdateLoanPaidLetterDTO true "Loan paid off letter payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{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 UpdateLoanPaidLetterDTO
|
||||
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 loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan paid off letter
|
||||
// @Description Deletes a loan paid off letter
|
||||
// @Tags loan-paid-off-letters
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan paid off letter ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-paid-off-letters/{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 loan paid off letter failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan paid off letter 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("passport_id")); raw != "" {
|
||||
filter.PassportId = 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
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/lending/loanpaidletter/storage.go
Normal file
11
internal/lending/loanpaidletter/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package loanpaidletter
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanPaidLetterDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanPaidLetterDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanPaidLetterDTO) (LoanPaidLetterDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanPaidLetterDTO) (LoanPaidLetterDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
135
internal/lending/loansdocument/db/postgresql.go
Normal file
135
internal/lending/loansdocument/db/postgresql.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loansdocument"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loansdocument.LoanDocumentDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loansdocument.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_order_required_docs d", documentColumns, scanLoanDocument),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const documentColumns = `d.id, d.name, d.value, d.active, d.created_at, d.updated_at`
|
||||
|
||||
const documentReturningColumns = `id, name, value, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansdocument.ListFilter) (loansdocument.ListLoanDocumentDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loansdocument.ListLoanDocumentDTO{}, err
|
||||
}
|
||||
|
||||
return loansdocument.ListLoanDocumentDTO{Count: count, LoansDocuments: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansdocument.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.DocumentName != "" {
|
||||
args = append(args, likePattern(filter.DocumentName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`d.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if filter.Active != nil {
|
||||
args = append(args, *filter.Active)
|
||||
conditions = append(conditions, fmt.Sprintf("d.active = $%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) GetByID(ctx context.Context, id int64) (loansdocument.LoanDocumentDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loansdocument.CreateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loan_order_required_docs (name, value, active)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
return scanLoanDocument(r.client.QueryRow(ctx, query, dto.Name, dto.Value, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loansdocument.UpdateLoanDocumentDTO) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_order_required_docs SET
|
||||
name = $1, value = $2, active = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, dto.Name, dto.Value, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (loansdocument.LoanDocumentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_order_required_docs SET
|
||||
active = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2
|
||||
RETURNING %s`, documentReturningColumns)
|
||||
|
||||
item, err := scanLoanDocument(r.client.QueryRow(ctx, query, active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanDocument(row genericrepo.Scanner) (loansdocument.LoanDocumentDTO, error) {
|
||||
var item loansdocument.LoanDocumentDTO
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Name, &item.Value, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loansdocument.LoanDocumentDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
40
internal/lending/loansdocument/dto.go
Normal file
40
internal/lending/loansdocument/dto.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package loansdocument
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanDocumentDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanDocumentDTO struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Value string `json:"value" binding:"required"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentDTO struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Value string `json:"value" binding:"required"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanDocumentActiveDTO struct {
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
DocumentName string
|
||||
Active *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanDocumentDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoansDocuments []LoanDocumentDTO `json:"loansDocuments"`
|
||||
}
|
||||
293
internal/lending/loansdocument/handler.go
Normal file
293
internal/lending/loansdocument/handler.go
Normal file
@@ -0,0 +1,293 @@
|
||||
package loansdocument
|
||||
|
||||
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 = "/loans-documents"
|
||||
|
||||
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/active", h.updateActive)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan documents
|
||||
// @Description Returns paginated loan documents with optional filters
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param document_name query string false "Filter by name"
|
||||
// @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
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents [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 loan documents failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan document by ID
|
||||
// @Description Returns a single loan document
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan document
|
||||
// @Description Creates a new loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanDocumentDTO true "Loan document payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanDocumentDTO
|
||||
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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan document
|
||||
// @Description Updates an existing loan document
|
||||
// @Tags loan-document
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Param body body UpdateLoanDocumentDTO true "Loan document 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} [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 UpdateLoanDocumentDTO
|
||||
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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// 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 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}/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 UpdateLoanDocumentActiveDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
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 active failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan document
|
||||
// @Description Deletes a loan document
|
||||
// @Tags loan-document
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan document ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-documents/{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 loan document failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan document 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("document_name")); raw != "" {
|
||||
filter.DocumentName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Active = &active
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
12
internal/lending/loansdocument/storage.go
Normal file
12
internal/lending/loansdocument/storage.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package loansdocument
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanDocumentDTO, error)
|
||||
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)
|
||||
UpdateActive(ctx context.Context, id int64, active bool) (LoanDocumentDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
108
internal/lending/loansrepayment/db/postgresql.go
Normal file
108
internal/lending/loansrepayment/db/postgresql.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loansrepayment"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loansrepayment.LoanRepaymentDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loansrepayment.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loans l", loanColumns, scanLoanRepayment),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const loanColumns = `l.id, l.user_id, l.passport_serie, l.passport_id, l.account_number, l.created_at, l.updated_at`
|
||||
|
||||
const loanReturningColumns = `id, user_id, passport_serie, passport_id, account_number, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loansrepayment.ListFilter) (loansrepayment.ListLoanRepaymentDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loansrepayment.ListLoanRepaymentDTO{}, err
|
||||
}
|
||||
|
||||
return loansrepayment.ListLoanRepaymentDTO{Count: count, Loans: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PassportId != "" {
|
||||
args = append(args, likePattern(filter.PassportId))
|
||||
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%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) GetByID(ctx context.Context, id int64) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loansrepayment.CreateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loans (user_id, passport_serie, passport_id, account_number)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING %s`, loanReturningColumns)
|
||||
|
||||
return scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loansrepayment.UpdateLoanRepaymentDTO) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loans SET
|
||||
user_id = $1, passport_serie = $2, passport_id = $3, account_number = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
RETURNING %s`, loanReturningColumns)
|
||||
|
||||
item, err := scanLoanRepayment(r.client.QueryRow(ctx, query, dto.UserId, dto.PassportSerie, dto.PassportId, dto.AccountNumber, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loansrepayment.LoanRepaymentDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanLoanRepayment(row genericrepo.Scanner) (loansrepayment.LoanRepaymentDTO, error) {
|
||||
var item loansrepayment.LoanRepaymentDTO
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.PassportSerie, &item.PassportId, &item.AccountNumber, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loansrepayment.LoanRepaymentDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
38
internal/lending/loansrepayment/dto.go
Normal file
38
internal/lending/loansrepayment/dto.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package loansrepayment
|
||||
|
||||
import "time"
|
||||
|
||||
type LoanRepaymentDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
AccountNumber string `json:"accountNumber"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanRepaymentDTO struct {
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
AccountNumber string `json:"accountNumber" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateLoanRepaymentDTO struct {
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
AccountNumber string `json:"accountNumber" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PassportId string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanRepaymentDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Loans []LoanRepaymentDTO `json:"loans"`
|
||||
}
|
||||
242
internal/lending/loansrepayment/handler.go
Normal file
242
internal/lending/loansrepayment/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package loansrepayment
|
||||
|
||||
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 = "/loans-repayment"
|
||||
|
||||
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.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan repayments
|
||||
// @Description Returns paginated loan repayments with optional filters
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param passport_id query string false "Filter by passport ID"
|
||||
// @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 /loans-repayment [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 loan repayments failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan repayment by ID
|
||||
// @Description Returns a single loan repayment
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{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 loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan repayment
|
||||
// @Description Creates a new loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanRepaymentDTO true "Loan repayment payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanRepaymentDTO
|
||||
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 loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan repayment
|
||||
// @Description Updates an existing loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Param body body UpdateLoanRepaymentDTO true "Loan repayment payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{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 UpdateLoanRepaymentDTO
|
||||
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 loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan repayment
|
||||
// @Description Deletes a loan repayment record
|
||||
// @Tags loans-repayment
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan repayment ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loans-repayment/{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 loan repayment failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan repayment 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("passport_id")); raw != "" {
|
||||
filter.PassportId = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/lending/loansrepayment/storage.go
Normal file
11
internal/lending/loansrepayment/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package loansrepayment
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanRepaymentDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanRepaymentDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanRepaymentDTO) (LoanRepaymentDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanRepaymentDTO) (LoanRepaymentDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
146
internal/lending/loantype/db/postgresql.go
Normal file
146
internal/lending/loantype/db/postgresql.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/lending/loantype"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[loantype.LoanTypeDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) loantype.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "loan_types lt", loanTypeColumns, scanLoanType),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const loanTypeColumns = `lt.id, lt.name, lt.tax, lt.maturity, lt.notes, lt.active, lt.created_at, lt.updated_at`
|
||||
|
||||
const loanTypeReturningColumns = `id, name, tax, maturity, notes, active, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter loantype.ListFilter) (loantype.ListLoanTypeDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return loantype.ListLoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
return loantype.ListLoanTypeDTO{Count: count, LoanTypes: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter loantype.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.LoanTypeName != "" {
|
||||
args = append(args, likePattern(filter.LoanTypeName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
lt.name->>'en' ILIKE $%[1]d OR lt.name->>'ru' ILIKE $%[1]d OR lt.name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
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) GetByID(ctx context.Context, id int64) (loantype.LoanTypeDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto loantype.CreateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
|
||||
name, notes, err := marshalJSON(dto.Title, dto.Content)
|
||||
if err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO loan_types (name, tax, maturity, notes, active)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
return scanLoanType(r.client.QueryRow(ctx, query, name, dto.Tax, dto.LoanTerm, notes, active))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto loantype.UpdateLoanTypeDTO) (loantype.LoanTypeDTO, error) {
|
||||
name, notes, err := marshalJSON(dto.Title, dto.Content)
|
||||
if err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE loan_types SET
|
||||
name = $1, tax = $2, maturity = $3, notes = $4, active = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING %s`, loanTypeReturningColumns)
|
||||
|
||||
item, err := scanLoanType(r.client.QueryRow(ctx, query, name, dto.Tax, dto.LoanTerm, notes, dto.Active, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalJSON(title, content loantype.LocalizedTitle) ([]byte, []byte, error) {
|
||||
titleJSON, err := json.Marshal(title)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
contentJSON, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return titleJSON, contentJSON, nil
|
||||
}
|
||||
|
||||
func scanLoanType(row genericrepo.Scanner) (loantype.LoanTypeDTO, error) {
|
||||
var item loantype.LoanTypeDTO
|
||||
var nameJSON, notesJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &nameJSON, &item.Tax, &item.LoanTerm, ¬esJSON, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Title); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(notesJSON, &item.Content); err != nil {
|
||||
return loantype.LoanTypeDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
47
internal/lending/loantype/dto.go
Normal file
47
internal/lending/loantype/dto.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package loantype
|
||||
|
||||
import "time"
|
||||
|
||||
type LocalizedTitle struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type LoanTypeDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedTitle `json:"title"`
|
||||
Tax float64 `json:"tax"`
|
||||
LoanTerm string `json:"loanTerm"`
|
||||
Content LocalizedTitle `json:"content"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateLoanTypeDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Tax float64 `json:"tax" binding:"required"`
|
||||
LoanTerm string `json:"loanTerm" binding:"required"`
|
||||
Content LocalizedTitle `json:"content" binding:"required"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateLoanTypeDTO struct {
|
||||
Title LocalizedTitle `json:"title" binding:"required"`
|
||||
Tax float64 `json:"tax" binding:"required"`
|
||||
LoanTerm string `json:"loanTerm" binding:"required"`
|
||||
Content LocalizedTitle `json:"content" binding:"required"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
LoanTypeName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListLoanTypeDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
LoanTypes []LoanTypeDTO `json:"loanTypes"`
|
||||
}
|
||||
242
internal/lending/loantype/handler.go
Normal file
242
internal/lending/loantype/handler.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package loantype
|
||||
|
||||
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 = "/loan-types"
|
||||
|
||||
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.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List loan types
|
||||
// @Description Returns paginated loan types with optional filters
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param loan_type_name query string false "Filter by title (en, ru, tm)"
|
||||
// @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 /loan-types [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 loan types failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get loan type by ID
|
||||
// @Description Returns a single loan type
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create loan type
|
||||
// @Description Creates a new loan type
|
||||
// @Tags loan-type
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateLoanTypeDTO true "Loan type payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateLoanTypeDTO
|
||||
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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update loan type
|
||||
// @Description Updates an existing loan type
|
||||
// @Tags loan-type
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Param body body UpdateLoanTypeDTO true "Loan type payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 UpdateLoanTypeDTO
|
||||
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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete loan type
|
||||
// @Description Deletes a loan type
|
||||
// @Tags loan-type
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Loan type ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /loan-types/{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 loan type failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("loan type 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("loan_type_name")); raw != "" {
|
||||
filter.LoanTypeName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/lending/loantype/storage.go
Normal file
11
internal/lending/loantype/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package loantype
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListLoanTypeDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (LoanTypeDTO, error)
|
||||
Create(ctx context.Context, dto CreateLoanTypeDTO) (LoanTypeDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateLoanTypeDTO) (LoanTypeDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
39
internal/lending/router.go
Normal file
39
internal/lending/router.go
Normal file
@@ -0,0 +1,39 @@
|
||||
// Package lending groups loan orders and their related documents,
|
||||
// repayments, types, and paid-off letters under one bounded context,
|
||||
// replacing the flat internal/admin/* listing.
|
||||
package lending
|
||||
|
||||
import (
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/lending/loanorders"
|
||||
loanordersdb "online-back/internal/lending/loanorders/db"
|
||||
"online-back/internal/lending/loanpaidletter"
|
||||
loanpaidletterdb "online-back/internal/lending/loanpaidletter/db"
|
||||
"online-back/internal/lending/loansdocument"
|
||||
loansdocumentdb "online-back/internal/lending/loansdocument/db"
|
||||
"online-back/internal/lending/loansrepayment"
|
||||
loansrepaymentdb "online-back/internal/lending/loansrepayment/db"
|
||||
"online-back/internal/lending/loantype"
|
||||
loantypedb "online-back/internal/lending/loantype/db"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Register wires every lending module's handler into router.
|
||||
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||
for _, h := range Handlers(client, logger) {
|
||||
h.Register(router)
|
||||
}
|
||||
}
|
||||
|
||||
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||
return []handlers.Handler{
|
||||
loantype.NewHandler(logger, loantypedb.NewRepository(client, logger)),
|
||||
loansdocument.NewHandler(logger, loansdocumentdb.NewRepository(client, logger)),
|
||||
loansrepayment.NewHandler(logger, loansrepaymentdb.NewRepository(client, logger)),
|
||||
loanorders.NewHandler(logger, loanordersdb.NewRepository(client, logger)),
|
||||
loanpaidletter.NewHandler(logger, loanpaidletterdb.NewRepository(client, logger)),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user