package db import ( "context" "fmt" "strings" "online-back/internal/identity/rbac" "online-back/internal/lending/loanorders" "online-back/internal/shared" "online-back/pkg/client/postgresql" "online-back/pkg/logging" "online-back/pkg/repository/genericrepo" ) type repository struct { client postgresql.Client generic *genericrepo.Repository[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, } } const loanOrderFromClause = ` FROM loan_orders lo LEFT JOIN loan_types lt ON lt.id = lo.loan_type LEFT JOIN branches b ON b.id = lo.branch_id LEFT JOIN users u ON u.id = lo.user_id LEFT JOIN provinces p ON p.id = lo.work_province_id LEFT JOIN loan_order_required_docs d ON d.id = lo.loan_order_required_doc_id` const loanOrderListFromClause = ` FROM loan_orders lo LEFT JOIN loan_types lt ON lt.id = lo.loan_type LEFT JOIN branches b ON b.id = lo.branch_id LEFT JOIN provinces bp ON bp.id = b.province_id` const loanOrderListColumns = `lo.id, lo.loan_type, lt.name, lo.created_at, lo.region, lo.branch_id, b.name, bp.name, lo.customer_name, lo.customer_surname, lo.phone, lo.status` // 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, ", ") var loanOrderSelectColumns = strings.Replace( shared.PrefixedColumns("lo", loanOrderColumns), "lo.source", "COALESCE(lo.source, 'web')", 1, ) + `, lt.name, b.name, ` + shared.UserInfoSQL + `, p.name, COALESCE(d.name, '')` func resolveSource(source string) string { source = strings.TrimSpace(source) if source == "" { return "web" } return source } func createArgs(dto loanorders.CreateLoanOrderDTO) []interface{} { return []interface{}{ resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(), dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome, dto.WorkRegion, shared.OptionalInt64(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, shared.OptionalTime(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, shared.OptionalInt64(dto.LoanOrderRequiredDocId), dto.Status, dto.Satisfiable, dto.Notes, } } func updateArgs(dto loanorders.UpdateLoanOrderDTO) []interface{} { return []interface{}{ resolveSource(dto.Source), shared.OptionalInt64(dto.UserId), dto.LoanType.Int64(), dto.Region, dto.BranchId.Int64(), dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.PassportAddress, dto.RealAddress, dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace, dto.BornAt.Time(), dto.Email, dto.Phone, dto.PhoneAdditional, dto.PhoneHome, dto.WorkRegion, shared.OptionalInt64(dto.WorkProvinceId), dto.WorkCompany, dto.WorkCompanyAccountantNumber, shared.OptionalTime(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, shared.OptionalInt64(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) var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM loan_orders lo`+whereClause, args...).Scan(&count); err != nil { return loanorders.ListLoanOrderDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 query := fmt.Sprintf( `SELECT %s%s%s ORDER BY lo.id DESC LIMIT $%d OFFSET $%d`, loanOrderListColumns, loanOrderListFromClause, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...) if err != nil { return loanorders.ListLoanOrderDTO{}, err } defer rows.Close() items := []loanorders.LoanOrderListItemDTO{} for rows.Next() { item, err := scanLoanOrderListItem(rows) if err != nil { return loanorders.ListLoanOrderDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return loanorders.ListLoanOrderDTO{}, err } return loanorders.ListLoanOrderDTO{Count: count, LoanOrders: items}, nil } func buildListQuery(filter loanorders.ListFilter) (whereClause string, args []interface{}) { conditions := []string{"lo.deleted_at IS NULL"} if filter.Status != nil { args = append(args, *filter.Status) conditions = append(conditions, fmt.Sprintf("lo.status = $%d", len(args))) } if len(filter.BranchIds) > 0 { conditions, args = rbac.AppendBranchIDs(conditions, args, "lo.branch_id", filter.BranchIds) } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("lo.branch_id = $%d", len(args))) } if filter.UserId != nil { args = append(args, *filter.UserId) conditions = append(conditions, fmt.Sprintf("lo.user_id = $%d", len(args))) } if filter.Region != "" { args = append(args, filter.Region) conditions = append(conditions, fmt.Sprintf("lo.region = $%d", len(args))) } if filter.Source != "" { args = append(args, filter.Source) conditions = append(conditions, fmt.Sprintf("lo.source = $%d", len(args))) } return " WHERE " + strings.Join(conditions, " AND "), args } func (r *repository) GetByID(ctx context.Context, id int64) (loanorders.LoanOrderDTO, error) { query := `SELECT ` + loanOrderSelectColumns + loanOrderFromClause + ` WHERE lo.id = $1 AND lo.deleted_at IS NULL` return scanLoanOrder(r.client.QueryRow(ctx, query, id)) } // nextUniqueIDExprTemplate builds unique_id as "TB" + the referenced branch's // unique_code + "-" + the last numeric suffix stored in loan_orders plus one, // zero-padded to 4 digits, e.g. "TB1303-8027". substring(... from '([0-9]+)$') // pulls the trailing digit run regardless of prefix, so both legacy plain rows // ("0008") and new "TB-NNNN" rows are accounted for when computing the // next value. The single %s is filled in with the placeholder bound to the // target branch id. const nextUniqueIDExprTemplate = `( SELECT 'TB' || COALESCE((SELECT unique_code FROM branches WHERE id = %s), '') || '-' || LPAD((SELECT COALESCE(MAX(substring(unique_id from '([0-9]+)$')::bigint), 0) + 1 FROM loan_orders)::text, 4, '0') )` func (r *repository) Create(ctx context.Context, dto loanorders.CreateLoanOrderDTO) (loanorders.LoanOrderDTO, error) { // unique_id is supplied positionally via nextUniqueIDExpr below, so it's not // part of createArgs; the target branch id is bound a second time (as its // own dedicated trailing placeholder) so that subquery doesn't need to guess // which $N slot branch_id already occupies among the other bound columns. args := createArgs(dto) placeholders := make([]string, len(args)) for i := range args { placeholders[i] = fmt.Sprintf("$%d", i+1) } branchIDPlaceholder := fmt.Sprintf("$%d", len(args)+1) args = append(args, dto.BranchId.Int64()) nextUniqueIDExpr := fmt.Sprintf(nextUniqueIDExprTemplate, branchIDPlaceholder) query := fmt.Sprintf(` WITH inserted AS ( INSERT INTO loan_orders (%s) VALUES (%s, %s) RETURNING %s ) SELECT %s FROM inserted lo LEFT JOIN loan_types lt ON lt.id = lo.loan_type LEFT JOIN branches b ON b.id = lo.branch_id LEFT JOIN users u ON u.id = lo.user_id LEFT JOIN provinces p ON p.id = lo.work_province_id LEFT JOIN loan_order_required_docs d ON d.id = lo.loan_order_required_doc_id`, loanOrderWritableColumnsSQL, nextUniqueIDExpr, strings.Join(placeholders, ", "), loanOrderColumnsSQL, loanOrderSelectColumns, ) 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) // unique_id is assigned once at creation and never touched again, so it's // excluded here (index 0 of loanOrderWritableColumns) — including it would // overwrite the assigned reference number with NULL on every update. writableColumns := loanOrderWritableColumns[1:] assignments := make([]string, len(writableColumns)) for i, column := range writableColumns { assignments[i] = fmt.Sprintf("%s = $%d", column, i+1) } args = append(args, id) query := fmt.Sprintf(` WITH updated AS ( UPDATE loan_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d AND deleted_at IS NULL RETURNING %s ) SELECT %s FROM updated lo LEFT JOIN loan_types lt ON lt.id = lo.loan_type LEFT JOIN branches b ON b.id = lo.branch_id LEFT JOIN users u ON u.id = lo.user_id LEFT JOIN provinces p ON p.id = lo.work_province_id LEFT JOIN loan_order_required_docs d ON d.id = lo.loan_order_required_doc_id`, strings.Join(assignments, ", "), len(args), loanOrderColumnsSQL, loanOrderSelectColumns, ) 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 scanLoanOrderListItem(row genericrepo.Scanner) (loanorders.LoanOrderListItemDTO, error) { var item loanorders.LoanOrderListItemDTO var loanTypeId, branchId int64 var loanTypeNameJSON, branchNameJSON, provinceNameJSON []byte err := row.Scan( &item.Id, &loanTypeId, &loanTypeNameJSON, &item.CreatedAt, &item.Region, &branchId, &branchNameJSON, &provinceNameJSON, &item.CustomerName, &item.CustomerSurname, &item.Phone, &item.Status, ) if err != nil { return loanorders.LoanOrderListItemDTO{}, err } var loanTypeName, branchName shared.LocalizedText _ = shared.UnmarshalLocalized(loanTypeNameJSON, &loanTypeName) _ = shared.UnmarshalLocalized(branchNameJSON, &branchName) _ = shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName) if loanTypeId != 0 { item.LoanType = &shared.NamedInfo{Id: loanTypeId, Name: loanTypeName} } if branchId != 0 { item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName} } return item, nil } func scanLoanOrder(row genericrepo.Scanner) (loanorders.LoanOrderDTO, error) { var item loanorders.LoanOrderDTO var loanTypeNameJSON, branchNameJSON, provinceNameJSON []byte var userName, userUsername, userPhone, userEmail string var requiredDocName string 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, &loanTypeNameJSON, &branchNameJSON, &userName, &userUsername, &userPhone, &userEmail, &provinceNameJSON, &requiredDocName, ) if err != nil { return loanorders.LoanOrderDTO{}, err } var loanTypeName, branchName, provinceName shared.LocalizedText _ = shared.UnmarshalLocalized(loanTypeNameJSON, &loanTypeName) _ = shared.UnmarshalLocalized(branchNameJSON, &branchName) _ = shared.UnmarshalLocalized(provinceNameJSON, &provinceName) if item.LoanType != 0 { item.LoanTypeInfo = &shared.NamedInfo{Id: item.LoanType, Name: loanTypeName} } if item.BranchId != 0 { item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName} } if item.WorkProvinceId != nil { item.WorkProvince = &shared.NamedInfo{Id: *item.WorkProvinceId, Name: provinceName} } if item.UserId != nil { item.User = &shared.UserInfo{ Id: *item.UserId, Name: userName, Username: userUsername, Phone: userPhone, Email: userEmail, } } if item.LoanOrderRequiredDocId != nil { item.LoanOrderRequiredDoc = &shared.TextInfo{Id: *item.LoanOrderRequiredDocId, Name: requiredDocName} } return item, nil }