package db import ( "context" "fmt" "strings" "online-back/internal/identity/rbac" "online-back/internal/lending/loanpaidletter" "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[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, } } const letterFromClause = ` FROM loan_paid_off_letters l LEFT JOIN branches b ON b.id = l.branch_id LEFT JOIN users u ON u.id = l.user_id LEFT JOIN provinces p ON p.id = b.province_id` // letterWritableColumns lists every loan_paid_off_letters column except id, created_at // and updated_at, in the exact order CreateLoanPaidLetterDTO/UpdateLoanPaidLetterDTO fields are read. 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, ", ") var letterSelectColumns = shared.PrefixedColumns("l", letterColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), b.province_id, p.name, ` + shared.UserInfoSQL 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) var count int64 if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM loan_paid_off_letters l`+whereClause, args...).Scan(&count); err != nil { return loanpaidletter.ListLoanPaidLetterDTO{}, err } offset := (filter.Page - 1) * filter.Limit limitPlaceholder := len(args) + 1 offsetPlaceholder := len(args) + 2 query := fmt.Sprintf( `SELECT l.id, l.unique_id, l.customer_name, l.customer_surname, l.phone, l.status FROM loan_paid_off_letters l%s ORDER BY l.id DESC LIMIT $%d OFFSET $%d`, whereClause, limitPlaceholder, offsetPlaceholder, ) rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...) if err != nil { return loanpaidletter.ListLoanPaidLetterDTO{}, err } defer rows.Close() items := []loanpaidletter.LoanPaidLetterListItemDTO{} for rows.Next() { var item loanpaidletter.LoanPaidLetterListItemDTO if err := rows.Scan( &item.Id, &item.UniqueId, &item.CustomerName, &item.CustomerSurname, &item.Phone, &item.Status, ); err != nil { return loanpaidletter.ListLoanPaidLetterDTO{}, err } items = append(items, item) } if err := rows.Err(); err != nil { return loanpaidletter.ListLoanPaidLetterDTO{}, err } return loanpaidletter.ListLoanPaidLetterDTO{Count: count, LoanPaidLetters: items}, nil } func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args []interface{}) { conditions := []string{"l.deleted_at IS NULL"} if filter.PassportId != "" { args = append(args, shared.LikePattern(filter.PassportId)) conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%d", len(args))) } if filter.Name != "" { args = append(args, shared.LikePattern(filter.Name)) n := len(args) conditions = append(conditions, fmt.Sprintf(`( l.customer_name ILIKE $%[1]d OR l.customer_surname ILIKE $%[1]d OR COALESCE(l.customer_patronic_name, '') ILIKE $%[1]d )`, n)) } if filter.Status != nil { args = append(args, *filter.Status) conditions = append(conditions, fmt.Sprintf("l.status = $%d", len(args))) } if filter.UserId != nil { args = append(args, *filter.UserId) conditions = append(conditions, fmt.Sprintf("l.user_id = $%d", len(args))) } if len(filter.BranchIds) > 0 { conditions, args = rbac.AppendBranchIDs(conditions, args, "l.branch_id", filter.BranchIds) } else if filter.BranchId != nil { args = append(args, *filter.BranchId) conditions = append(conditions, fmt.Sprintf("l.branch_id = $%d", len(args))) } if filter.Region != "" { args = append(args, filter.Region) conditions = append(conditions, fmt.Sprintf("l.region = $%d", len(args))) } return " WHERE " + strings.Join(conditions, " AND "), args } func (r *repository) ListBranchesByProvince(ctx context.Context, provinceID int64, activeOnly bool) (loanpaidletter.ListBranchesByProvinceDTO, error) { args := []interface{}{provinceID} where := ` WHERE province_id = $1 AND deleted_at IS NULL` if activeOnly { where += ` AND active = true` } query := ` SELECT id, COALESCE(unique_code, ''), name, region, province_id, active FROM branches` + where + ` ORDER BY name->>'tm', name->>'en', id` rows, err := r.client.Query(ctx, query, args...) if err != nil { return loanpaidletter.ListBranchesByProvinceDTO{}, err } defer rows.Close() branches := make([]loanpaidletter.BranchByProvinceDTO, 0) for rows.Next() { var item loanpaidletter.BranchByProvinceDTO var nameJSON []byte if err := rows.Scan(&item.Id, &item.UniqueCode, &nameJSON, &item.Region, &item.ProvinceId, &item.Active); err != nil { return loanpaidletter.ListBranchesByProvinceDTO{}, err } if err := shared.UnmarshalLocalized(nameJSON, &item.Name); err != nil { return loanpaidletter.ListBranchesByProvinceDTO{}, err } branches = append(branches, item) } if err := rows.Err(); err != nil { return loanpaidletter.ListBranchesByProvinceDTO{}, err } return loanpaidletter.ListBranchesByProvinceDTO{ Count: int64(len(branches)), Branches: branches, }, nil } func (r *repository) GetByID(ctx context.Context, id int64) (loanpaidletter.LoanPaidLetterDTO, error) { query := `SELECT ` + letterSelectColumns + letterFromClause + ` WHERE l.id = $1 AND l.deleted_at IS NULL` return scanLoanPaidLetter(r.client.QueryRow(ctx, query, 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(` WITH inserted AS ( INSERT INTO loan_paid_off_letters (%s) VALUES (%s) RETURNING %s ) SELECT %s FROM inserted l LEFT JOIN branches b ON b.id = l.branch_id LEFT JOIN users u ON u.id = l.user_id LEFT JOIN provinces p ON p.id = b.province_id`, letterWritableColumnsSQL, strings.Join(placeholders, ", "), letterColumnsSQL, letterSelectColumns, ) 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(` WITH updated AS ( UPDATE loan_paid_off_letters SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d AND deleted_at IS NULL RETURNING %s ) SELECT %s FROM updated l LEFT JOIN branches b ON b.id = l.branch_id LEFT JOIN users u ON u.id = l.user_id LEFT JOIN provinces p ON p.id = b.province_id`, strings.Join(assignments, ", "), len(args), letterColumnsSQL, letterSelectColumns, ) 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 var regionNameJSON, branchNameJSON, provinceNameJSON []byte var branchUniqueCode string var userName, userUsername, userPhone, userEmail string 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, ®ionNameJSON, &branchNameJSON, &branchUniqueCode, &item.ProvinceId, &provinceNameJSON, &userName, &userUsername, &userPhone, &userEmail, ) if err != nil { return loanpaidletter.LoanPaidLetterDTO{}, err } _ = shared.UnmarshalLocalized(regionNameJSON, &item.RegionName) var branchName, provinceName shared.LocalizedText _ = shared.UnmarshalLocalized(branchNameJSON, &branchName) _ = shared.UnmarshalLocalized(provinceNameJSON, &provinceName) if item.BranchId != 0 { item.Branch = &shared.BranchInfo{Id: item.BranchId, Name: branchName, UniqueCode: branchUniqueCode} } if item.ProvinceId != nil { item.Province = &shared.NamedInfo{Id: *item.ProvinceId, Name: provinceName} } if item.UserId != nil { item.User = &shared.UserInfo{ Id: *item.UserId, Name: userName, Username: userUsername, Phone: userPhone, Email: userEmail, } } return item, nil }